import { useEffect, useState } from 'react'; import { getCurrentUser } from '../../auth/services/sessionService'; import { getContactProfile, saveContactProfile } from '../services/contactProfileService'; function getUserId(user) { const value = user?.databaseId || user?.id; const numeric = Number(value); return Number.isFinite(numeric) ? numeric : null; } function formatPhone(phone) { const digits = String(phone || '').replace(/\D/g, ''); if (!digits) return 'Telefone não disponível'; if (digits.startsWith('55') && digits.length === 13) { return `+55 (${digits.slice(2, 4)}) ${digits.slice(4, 9)}-${digits.slice(9)}`; } if (digits.startsWith('55') && digits.length === 12) { return `+55 (${digits.slice(2, 4)}) ${digits.slice(4, 8)}-${digits.slice(8)}`; } if (digits.length === 11) { return `(${digits.slice(0, 2)}) ${digits.slice(2, 7)}-${digits.slice(7)}`; } if (digits.length === 10) { return `(${digits.slice(0, 2)}) ${digits.slice(2, 6)}-${digits.slice(6)}`; } return phone; } export function ContactProfilePanel({ isOpen, contact, onClose, onSaved }) { const [profile, setProfile] = useState(null); const [form, setForm] = useState({ name: '', company: '', note: '' }); const [isSaving, setIsSaving] = useState(false); const [error, setError] = useState(''); useEffect(() => { let isMounted = true; async function loadProfile() { if (!isOpen || !contact?.id) return; try { const data = await getContactProfile(contact.id); if (!isMounted) return; setProfile(data); setForm({ name: data.name || contact.name || '', company: data.company || '', note: data.note || '', }); setError(''); } catch (err) { if (isMounted) setError(err.message); } } loadProfile(); return () => { isMounted = false; }; }, [isOpen, contact?.id]); if (!isOpen) { return null; } const fieldStyle = { width: '100%', border: '1px solid var(--color-border)', borderRadius: '16px', padding: '0.9rem 1rem', background: '#fff', outline: 'none', }; async function submit() { if (!contact?.id) return; setIsSaving(true); try { const userId = getUserId(getCurrentUser()); const saved = await saveContactProfile(contact.id, { phone: profile?.phone || contact?.contactProfile?.phone || '', name: form.name, company: form.company, note: form.note, userId, }); setProfile(saved); onSaved?.(contact.id, saved); setError(''); } catch (err) { setError(err.message); } finally { setIsSaving(false); } } return (