// Tela: Contatos — lista + detalhe

const { useState: useContatoState } = React;

/* ─── Modal criar / editar ──────────────────────────────────── */
function ContatoModal({ onClose, onSave, initialData }) {
  const isEdit = !!initialData;
  const [nome,    setNome]    = useContatoState(initialData?.nome    || '');
  const [cargo,   setCargo]   = useContatoState(initialData?.cargo   || '');
  const [empresa, setEmpresa] = useContatoState(initialData?.empresa || '');
  const [email,   setEmail]   = useContatoState(initialData?.email   || '');
  const [fone,    setFone]    = useContatoState(initialData?.fone    || '');
  const [cidade,  setCidade]  = useContatoState(initialData?.cidade  || '');
  const [tag,     setTag]     = useContatoState(initialData?.tag     || 'Recorrente');
  const [avatar,  setAvatar]  = useContatoState(initialData?.avatar  || null);
  const [avatarDrag, setAvatarDrag] = useContatoState(false);
  const avatarRef = React.useRef(null);
  const toast = useToast();

  const TAGS    = ['VIP', 'Quente', 'Recorrente', 'Frio'];
  const TAG_CLS = { VIP: 'pill-dark', Quente: 'pill-pink', Recorrente: 'pill-mint', Frio: '' };
  const valid   = nome.trim().length > 0;

  const handleAvatarFile = (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    const url = URL.createObjectURL(file);
    setAvatar(url);
  };

  const submit = () => {
    if (!valid) return;
    const dados = {
      id:      initialData?.id || Date.now(),
      avatar:  avatar || `https://i.pravatar.cc/120?img=${Math.floor(Math.random()*70)+1}`,
      nome:    nome.trim(),
      cargo:   cargo.trim()   || 'Contato',
      empresa: empresa.trim() || '—',
      email:   email.trim()   || '—',
      fone:    fone.trim()    || '—',
      cidade:  cidade.trim()  || '—',
      tag,
    };
    if (onSave) onSave(dados);
    toast(isEdit
      ? `Contato "${nome.trim().split(' ')[0]}" atualizado ✓`
      : `Contato "${nome.trim().split(' ')[0]}" adicionado ✓`
    );
    onClose();
  };

  return (
    <div className="modal-wrap" onClick={onClose}>
      <div className="card modal-card" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div>
            <div className="modal-title">
              {isEdit ? <>Editar <em>Contato</em></> : <>Novo <em>Contato</em></>}
            </div>
            <div className="modal-sub muted">
              {isEdit ? 'Atualize as informações do contato' : 'Adicione um novo contato à base'}
            </div>
          </div>
          <div className="mini-btn" onClick={onClose}>{ICN.x}</div>
        </div>

        {/* ── upload de foto ── */}
        <div style={{display:'flex',justifyContent:'center',marginBottom:20}}>
          <div
            style={{position:'relative',cursor:'pointer'}}
            onClick={() => avatarRef.current?.click()}
            onDragOver={e => { e.preventDefault(); setAvatarDrag(true); }}
            onDragLeave={() => setAvatarDrag(false)}
            onDrop={e => { e.preventDefault(); setAvatarDrag(false); handleAvatarFile(e.dataTransfer.files?.[0]); }}
          >
            <input ref={avatarRef} type="file" accept="image/*" style={{display:'none'}} onChange={e => handleAvatarFile(e.target.files?.[0])} />
            <div style={{
              width:80, height:80, borderRadius:'50%', overflow:'hidden',
              border: avatarDrag ? '2.5px dashed oklch(0.55 0.18 265)' : '2.5px dashed oklch(0.80 0.06 255)',
              background: avatarDrag ? 'oklch(0.93 0.04 265)' : 'oklch(0.96 0.01 255)',
              display:'flex', alignItems:'center', justifyContent:'center',
              transition:'all .15s', boxShadow: avatar ? '0 0 0 3px oklch(0.93 0.06 255)' : 'none',
            }}>
              {avatar
                ? <img src={avatar} style={{width:'100%',height:'100%',objectFit:'cover'}} alt="" />
                : <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="oklch(0.65 0.08 255)" strokeWidth="1.5"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/></svg>
              }
            </div>
            <div style={{
              position:'absolute', bottom:0, right:0,
              width:24, height:24, borderRadius:'50%',
              background:'oklch(0.30 0.08 255)', color:'white',
              display:'flex', alignItems:'center', justifyContent:'center',
              boxShadow:'0 1px 4px rgba(0,0,0,.25)', border:'2px solid white',
            }}>
              <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
            </div>
          </div>
        </div>

        <div className="form-grid">
          <div className="field" style={{gridColumn:'1/-1'}}>
            <label className="field-lbl">Nome completo *</label>
            <input className="ezz-input" placeholder="Ex: Ana Beatriz Carvalho"
              value={nome} onChange={e => setNome(e.target.value)} autoFocus />
          </div>
          <div className="field">
            <label className="field-lbl">Cargo</label>
            <input className="ezz-input" placeholder="Ex: CEO"
              value={cargo} onChange={e => setCargo(e.target.value)} />
          </div>
          <div className="field">
            <label className="field-lbl">Empresa</label>
            <input className="ezz-input" placeholder="Ex: Tecnoluz Solar"
              value={empresa} onChange={e => setEmpresa(e.target.value)} />
          </div>
          <div className="field">
            <label className="field-lbl">E-mail</label>
            <input className="ezz-input" type="email" placeholder="contato@empresa.com.br"
              value={email} onChange={e => setEmail(e.target.value)} />
          </div>
          <div className="field">
            <label className="field-lbl">Telefone / WhatsApp</label>
            <input className="ezz-input" placeholder="(11) 99999-9999"
              value={fone} onChange={e => setFone(e.target.value)} />
          </div>
          <div className="field">
            <label className="field-lbl">Cidade, UF</label>
            <input className="ezz-input" placeholder="Ex: São Paulo, SP"
              value={cidade} onChange={e => setCidade(e.target.value)} />
          </div>
          <div className="field">
            <label className="field-lbl">Tag / Classificação</label>
            <div className="row" style={{gap: 6, flexWrap: 'wrap'}}>
              {TAGS.map(t => (
                <span key={t}
                  className={`pill ${tag === t ? TAG_CLS[t] || 'pill-dark' : ''}`}
                  onClick={() => setTag(t)}
                  style={{cursor:'default', fontSize:11}}>
                  {t}
                </span>
              ))}
            </div>
          </div>
        </div>

        <div className="modal-actions">
          <button className="btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn-primary" onClick={submit} disabled={!valid} style={{opacity: valid ? 1 : 0.5}}>
            {isEdit ? <>{ICN.edit} Salvar alterações</> : <>{ICN.plus} Salvar contato</>}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ─── Linha da lista ────────────────────────────────────────── */
function ContactRow({ c, selected, onClick }) {
  return (
    <div className={`crow ${selected ? 'crow-sel' : ''}`} onClick={onClick}>
      <img src={c.avatar} alt="" />
      <div className="col" style={{flex:1, minWidth:0}}>
        <div className="crow-name">{c.nome}</div>
        <div className="crow-sub muted">{c.cargo} · {c.empresa}</div>
      </div>
      <div className={`pill ${
        c.tag === 'VIP'        ? 'pill-dark' :
        c.tag === 'Quente'    ? 'pill-pink' :
        c.tag === 'Recorrente'? 'pill-mint' : ''}`}>
        {c.tag}
      </div>
      <style jsx>{`
        .crow { display: flex; align-items: center; gap: 14px; padding: 12px 14px; border-radius: 18px; cursor: default; }
        .crow:hover { background: oklch(0.97 0.01 250 / 0.6); }
        .crow-sel { background: white; box-shadow: 0 1px 0 rgba(255,255,255,.7) inset, 0 12px 24px -16px rgba(20,30,60,.2); }
        .crow img { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; }
        .crow-name { font-size: 13.5px; font-weight: 600; }
        .crow-sub { font-size: 11.5px; }
      `}</style>
    </div>
  );
}

/* ─── Lista de contatos ─────────────────────────────────────── */
function ContactsList({ localContatos, setLocalContatos, onSelect, selectedId, onCreateContato }) {
  const [sort,      setSort]     = useContatoState('recentes');
  const [tagFilter, setTagFilter]= useContatoState('Todos');
  const [showNovo,  setShowNovo] = useContatoState(false);

  const SORTS = ['recentes','nome','empresa'];
  const TAGS  = ['Todos','VIP','Quente','Recorrente','Frio'];

  let lista = [...localContatos];
  if (tagFilter !== 'Todos') lista = lista.filter(c => c.tag === tagFilter);
  if (sort === 'nome')       lista.sort((a,b) => a.nome.localeCompare(b.nome));
  if (sort === 'empresa')    lista.sort((a,b) => a.empresa.localeCompare(b.empresa));

  return (
    <>
      <PageHead
        title={<>Informações <em>do Cliente</em></>}
        subtitle="Visão consolidada das contas e contatos"
        right={
          <div className="row">
            <StatInline label="Pipeline total"   value={`R$ ${(OPORTUNIDADES.reduce((s,n)=>s+n.valor,0)/1000000).toFixed(1).replace('.',',')}M`} pill={`+${OPORTUNIDADES.length} negócios`} pillColor="yellow" icon={ICN.chart}/>
            <StatInline label="Contatos ativos" value={`+${CONTATOS.length}`} pill="+2 hoje" pillColor="blue" icon={ICN.users}/>
            <StatInline label="Tarefas abertas" value={`+${JORNADAS.reduce((s,j)=>s+j.cards.length,0)}`} pill="+4 hoje" pillColor="mint" icon={ICN.cal}/>
          </div>
        }
      />

      <div className="card">
        <div className="card-head" style={{flexWrap:'wrap', gap:10}}>
          <div className="card-title">Contatos · {lista.length}</div>
          <div className="row" style={{gap:6, flex:1, flexWrap:'wrap'}}>
            <div className="row" style={{gap:4}}>
              {TAGS.map(t => (
                <span key={t} className={`pill ${tagFilter===t?'pill-dark':''}`}
                  onClick={()=>setTagFilter(t)} style={{cursor:'default',fontSize:11}}>{t}</span>
              ))}
            </div>
            <div style={{width:'1px',background:'var(--ink-line)',alignSelf:'stretch'}}/>
            <div className="row" style={{gap:4}}>
              {SORTS.map(s => (
                <span key={s} className={`pill ${sort===s?'pill-dark':''}`}
                  onClick={()=>setSort(s)} style={{cursor:'default',fontSize:11,textTransform:'capitalize'}}>{s}</span>
              ))}
            </div>
            <ActionBtn icon={ICN.plus} title="Novo contato" size="icon" onClick={() => setShowNovo(true)} />
          </div>
        </div>

        <div className="contacts-grid">
          {lista.map(c => (
            <ContactRow key={c.id} c={c} selected={selectedId === c.id} onClick={() => onSelect(c.id)} />
          ))}
        </div>

        <style>{`.contacts-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 4px 24px; }`}</style>
      </div>

      {showNovo && (
        <ContatoModal
          onClose={() => setShowNovo(false)}
          onSave={onCreateContato || ((novo) => setLocalContatos(prev => [{ ...novo, id: Date.now() }, ...prev]))}
        />
      )}
    </>
  );
}

/* ─── Stat inline do cabeçalho ──────────────────────────────── */
function StatInline({ label, value, pill, pillColor, icon }) {
  return (
    <div className="row stat-inline" style={{gap: 12, padding: '6px 14px 6px 6px'}}>
      <div className="icon-btn" style={{width: 36, height: 36}}>{icon}</div>
      <div className="col">
        <div className="row" style={{gap: 6}}>
          <span className="money" style={{fontWeight: 700, fontSize: 15}}>{value}</span>
          <span className={`pill pill-${pillColor}`} style={{fontSize: 10}}>{pill}</span>
        </div>
        <span className="muted" style={{fontSize: 11}}>{label}</span>
      </div>
    </div>
  );
}

/* ─── Mini calendário ───────────────────────────────────────── */
function MiniCalendar({ goto }) {
  const months = ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
  const [m, setM] = React.useState(4);
  const toast = useToast();
  const today    = m === 4 ? 13 : -1;
  const days     = Array.from({length: 31}, (_, i) => i + 1);
  const startPad = 3;

  return (
    <div className="mc">
      <div className="mc-head">
        <div className="row" style={{gap: 6}}>
          <ActionBtn icon={ICN.arrowLeft}  title="Mês anterior"  onClick={() => setM((m + 11) % 12)} />
          <ActionBtn icon={ICN.arrowRight} title="Próximo mês"   onClick={() => setM((m + 1)  % 12)} />
        </div>
        <div style={{fontFamily:'var(--font-display)', fontStyle:'italic', fontSize: 22}}>{months[m]}</div>
        <ActionBtn
          icon={ICN.arrowUp}
          title="Abrir calendário"
          onClick={() => goto ? goto('calendario') : toast(`Abrindo ${months[m]} no calendário`)}
        />
      </div>
      <div className="mc-dows">
        {['D','S','T','Q','Q','S','S'].map((d,i) => <div key={i}>{d}</div>)}
      </div>
      <div className="mc-grid">
        {Array(startPad).fill(null).map((_, i) => <div key={'p'+i} />)}
        {days.slice(0, 21).map(d => {
          const isToday = d === today;
          const hasEv   = [4, 11, 12, 16].includes(d);
          const isWeek  = d >= 11 && d <= 17;
          return (
            <div key={d} className={`mc-day ${isToday?'mc-today':''} ${hasEv?'mc-ev':''} ${isWeek?'mc-week':''}`}>
              {hasEv && d !== today && (
                <img src={AVATAR_URLS[d % AVATAR_URLS.length]} className="mc-mini-av" alt="" />
              )}
              <span>{d}</span>
            </div>
          );
        })}
      </div>
      <style>{`
        .mc-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
        .mc-dows { display: grid; grid-template-columns: repeat(7, 1fr); font-size: 10px; color: var(--ink-faint); text-align: center; padding-bottom: 6px; font-weight: 600; }
        .mc-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 4px; }
        .mc-day { aspect-ratio: 1; border-radius: 12px; display: flex; align-items: flex-end; justify-content: space-between; padding: 5px; font-size: 11.5px; color: var(--ink-soft); position: relative; }
        .mc-week { background: oklch(0.96 0.012 250); }
        .mc-today { background: var(--acc-teal); color: oklch(0.22 0.06 200); font-weight: 700; }
        .mc-ev { background: var(--acc-yellow); color: oklch(0.30 0.13 80); font-weight: 600; }
        .mc-ev.mc-today { background: var(--acc-blue); color: white; }
        .mc-mini-av { position: absolute; top: 4px; left: 4px; width: 16px; height: 16px; border-radius: 50%; border: 1.5px solid white; }
      `}</style>
    </div>
  );
}

/* ─── DL Row ────────────────────────────────────────────────── */
function DLRow({ icon, label, value, action }) {
  const toast = useToast();
  return (
    <div className="dl-row">
      <div className="dl-ic">{icon}</div>
      <div className="col">
        <div className="dl-lbl">{label}</div>
        <div className="dl-val">{value}</div>
      </div>
      <ActionBtn
        icon={action || ICN.edit}
        title={`Editar ${label.toLowerCase()}`}
        onClick={() => toast(`${label} editado`)}
      />
    </div>
  );
}

function SrcChip({ color, label }) {
  return (
    <div style={{
      width: 28, height: 28, borderRadius: '50%',
      background: `var(--acc-${color})`,
      display: 'grid', placeItems: 'center',
      fontSize: 10, fontWeight: 700, letterSpacing: '0.04em',
      color: 'oklch(0.22 0.04 250)',
    }}>{label}</div>
  );
}

/* ─── Modal: Atribuir responsável ───────────────────────────── */
function AtribuirModal({ contact, onClose }) {
  const toast = useToast();
  const [selected, setSelected] = React.useState(null);
  const membros = CONTATOS.slice(0, 6).map(m => ({
    id: m.id, nome: m.nome.split(' ').slice(0, 2).join(' '), cargo: m.cargo, avatar: m.avatar,
  }));

  const confirmar = () => {
    if (!selected) { toast('Selecione um responsável'); return; }
    const m = membros.find(x => x.id === selected);
    toast(`${contact.nome.split(' ')[0]} atribuído(a) a ${m.nome.split(' ')[0]} ✓`);
    onClose();
  };

  return (
    <div className="modal-backdrop" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal-box" style={{width: 380}}>
        <div className="modal-head">
          <div className="modal-title">Atribuir responsável</div>
          <button className="icon-btn" onClick={onClose} style={{marginLeft:'auto'}}>✕</button>
        </div>
        <div style={{padding: '4px 0 8px', fontSize: 12.5, color: 'var(--ink-soft)'}}>
          Selecione quem ficará responsável por <strong>{contact.nome.split(' ')[0]}</strong>:
        </div>
        <div className="col" style={{gap: 6, maxHeight: 280, overflowY: 'auto'}}>
          {membros.map(m => (
            <div key={m.id}
              onClick={() => setSelected(m.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
                borderRadius: 10, cursor: 'pointer',
                background: selected === m.id ? 'var(--acc-blue)' : 'var(--bg-soft)',
                color: selected === m.id ? 'white' : 'inherit',
                transition: 'background .15s',
              }}
            >
              <img src={m.avatar} style={{width:32, height:32, borderRadius:'50%', objectFit:'cover'}} alt="" />
              <div className="col" style={{gap: 1}}>
                <div style={{fontSize: 13, fontWeight: 600}}>{m.nome}</div>
                <div style={{fontSize: 11.5, opacity: .7}}>{m.cargo}</div>
              </div>
              {selected === m.id && <span style={{marginLeft:'auto', fontSize:16}}>✓</span>}
            </div>
          ))}
        </div>
        <div className="row" style={{justifyContent:'flex-end', gap:8, marginTop:14}}>
          <button className="btn-sec" onClick={onClose}>Cancelar</button>
          <button className="btn-pri" onClick={confirmar}>Confirmar</button>
        </div>
      </div>
    </div>
  );
}

/* ─── Detalhe do contato ────────────────────────────────────── */
const { InteractionCard, FunnelBars } = window;

function ContactDetail({ contact, onBack, onEdit, onDelete, goto }) {
  const [showEdit, setShowEdit] = useContatoState(false);
  const [showAtribuir, setShowAtribuir] = React.useState(false);
  const [expandedInfo, setExpandedInfo] = React.useState(false);
  const toast = useToast();
  const c = contact;

  const handleDelete = () => {
    if (onDelete) onDelete(c.id);
    toast(`Contato "${c.nome.split(' ')[0]}" excluído`);
    onBack();
  };

  return (
    <>
      <PageHead
        title={<>Informações <em>do Cliente</em></>}
        subtitle={`${c.cargo} · ${c.empresa}`}
        back onBack={onBack}
        right={
          <div className="row">
            <StatInline label="Pipeline total"   value={`R$ ${(OPORTUNIDADES.reduce((s,n)=>s+n.valor,0)/1000000).toFixed(1).replace('.',',')}M`} pill={`+${OPORTUNIDADES.length} negócios`} pillColor="yellow" icon={ICN.chart}/>
            <StatInline label="Contatos ativos" value={`+${CONTATOS.length}`} pill="+2 hoje" pillColor="blue" icon={ICN.users}/>
            <StatInline label="Tarefas abertas" value={`+${JORNADAS.reduce((s,j)=>s+j.cards.length,0)}`} pill="+4 hoje" pillColor="mint" icon={ICN.cal}/>
          </div>
        }
      />

      <div className="cd-grid">
        {/* Coluna principal */}
        <div className="col" style={{gap: 14}}>
          <div className="card">
            <div className="card-head">
              <div className="card-title">Histórico de Interações</div>
              <div className="row" style={{gap:4}}>
                <MoreMenu items={[
                  { ic: ICN.refresh, label: 'Atualizar',         toast: 'Histórico atualizado' },
                  { ic: ICN.upload,  label: 'Exportar histórico', onClick: () => {
                    const rows = [['Data','Negócio','Valor'],['04/05','Pacote Royal — Oportunidade','11250'],['16/05','Negócio mais relevante','21300'],['12/05','Sucesso absoluto — fechado','2100'],['11/05','Pacote Royal — Oportunidade','4160'],['02/05','Business Adaptativo','3140'],['02/05','Segundo negócio — comum','12350']];
                    const csv = '﻿' + rows.map(r => r.map(v => `"${v}"`).join(',')).join('\n');
                    const a = Object.assign(document.createElement('a'), { href: URL.createObjectURL(new Blob([csv], {type:'text/csv;charset=utf-8'})), download: `historico-${c.nome.split(' ')[0].toLowerCase()}.csv` });
                    a.click(); URL.revokeObjectURL(a.href);
                    toast('Histórico exportado em CSV ✓');
                  }},
                  { ic: ICN.filter,  label: 'Filtrar período',    toast: 'Filtros aplicados'    },
                ]} />
                <ActionBtn icon={ICN.arrowUp} title="Ver tudo" onClick={() => goto && goto('oportunidades')} />
              </div>
            </div>
            <div className="interactions">
              {[
                { d:"04/05", t:"Pacote Royal — Oportunidade",  v:"R$ 11.250", c:"azul",    ids:[0,4,10] },
                { d:"16/05", t:"Negócio mais relevante",        v:"R$ 21.300", c:"teal",    ids:[1,5,11] },
                { d:"12/05", t:"Sucesso absoluto — fechado",    v:"R$ 2.100",  c:"preto",   ids:[2,6]    },
                { d:"11/05", t:"Pacote Royal — Oportunidade",  v:"R$ 4.160",  c:"amarelo", ids:[3,7]    },
                { d:"02/05", t:"Business Adaptativo",           v:"R$ 3.140",  c:"claro",   ids:[8]      },
                { d:"02/05", t:"Segundo negócio — comum",       v:"R$ 12.350", c:"claro",   ids:[9,11]   },
              ].map((it,i) => <InteractionCard key={i} it={it} />)}
            </div>
          </div>

          <div className="row" style={{gap:14, alignItems:'stretch'}}>
            <div className="card" style={{flex:1}}>
              <div className="card-head">
                <div className="card-title">Agenda de Tarefas</div>
                <div className="row" style={{gap:4}}>
                  <MoreMenu items={[
                    { ic: ICN.plus,  label: 'Nova tarefa',        onClick: () => { toast('Tarefa criada para ' + c.nome.split(' ')[0] + ' ✓'); } },
                    { ic: ICN.cal,   label: 'Ir para hoje',        onClick: () => goto && goto('calendario') },
                    { ic: ICN.share, label: 'Compartilhar agenda', onClick: () => { navigator.clipboard?.writeText(`https://app.ezza.com.br/agenda/${c.id}`).catch(()=>{}); toast('Link da agenda copiado ✓'); } },
                  ]} />
                  <ActionBtn icon={ICN.arrowUp} title="Abrir calendário" onClick={() => goto && goto('calendario')} />
                </div>
              </div>
              <MiniCalendar goto={goto} />
            </div>

            <div className="card" style={{flex:1.1}}>
              <div className="card-head">
                <div className="col">
                  <div className="card-title">Funil de Etapas</div>
                  <div className="muted" style={{fontSize:12, marginTop:4}}>R$ {(OPORTUNIDADES.filter(n => n.etapa !== 'Fechado').reduce((s,n) => s + n.valor, 0) / 1000).toFixed(0)}k em pipeline</div>
                </div>
                <div className="row" style={{gap:4}}>
                  <span className="pill pill-dark" style={{cursor:'default'}}>Ponderado</span>
                  <span className="pill" style={{cursor:'default'}}>Total</span>
                </div>
              </div>
              <FunnelBars goto={goto} />
            </div>
          </div>
        </div>

        {/* Coluna lateral */}
        <div className="col" style={{gap: 14}}>
          <div className="card cd-card">
            <div className="row" style={{justifyContent:'flex-end', gap:6}}>
              <ActionBtn icon={ICN.share} title="Compartilhar" onClick={() => { navigator.clipboard?.writeText(`https://app.ezza.com.br/contatos/${c.id}`).catch(()=>{}); toast('Link do contato copiado ✓'); }} />
              <MoreMenu items={[
                { ic: ICN.edit,  label: 'Editar contato',    onClick: () => setShowEdit(true)  },
                { ic: ICN.users, label: 'Atribuir a alguém', onClick: () => setShowAtribuir(true) },
                { ic: ICN.cal,   label: 'Agendar reunião',   onClick: () => goto && goto('calendario') },
                { divider: true },
                { ic: ICN.trash, label: 'Excluir contato',   danger: true, onClick: handleDelete },
              ]} />
              <ActionBtn icon={ICN.arrowUp} title="Ver perfil completo" onClick={() => window.scrollTo({top:0, behavior:'smooth'})} />
            </div>

            <div style={{display:'flex', flexDirection:'column', alignItems:'center', padding:'4px 0 14px'}}>
              <img src={c.avatar} style={{width:124, height:124, borderRadius:'50%', objectFit:'cover', border:'4px solid white', boxShadow:'0 16px 32px -14px rgba(20,30,60,.25)'}} alt="" />
              <div style={{fontSize:22, fontWeight:700, marginTop:16, letterSpacing:'-0.02em', textAlign:'center'}}>{c.nome}</div>
              <div className="muted" style={{fontSize:12.5, marginTop:2, textAlign:'center'}}>{c.cargo}<br/>{c.empresa}</div>
              <div className="row" style={{marginTop:18, gap:8}}>
                <ActionBtn icon={ICN.edit}     title="Editar"            onClick={() => setShowEdit(true)} />
                <ActionBtn icon={ICN.mail}     title="Enviar e-mail"     onClick={() => window.open(`mailto:${c.email}?subject=Olá, ${c.nome.split(' ')[0]}!`)} />
                <ActionBtn icon={ICN.phone}    title="Ligar"             onClick={() => window.open(`tel:${c.fone.replace(/\D/g,'')}`)} />
                <ActionBtn icon={ICN.plus}     title="Nova oportunidade" onClick={() => goto && goto('oportunidades')} />
                <ActionBtn icon={ICN.cal}      title="Agendar"           onClick={() => goto && goto('calendario')} />
              </div>
            </div>
          </div>

          <div className="card">
            <div className="card-head">
              <div className="card-title">Informações Detalhadas</div>
              <div className="row" style={{gap:4}}>
                <ActionBtn icon={ICN.edit}    title="Editar dados" onClick={() => setShowEdit(true)} />
                <ActionBtn icon={ICN.arrowUp} title={expandedInfo ? 'Recolher' : 'Expandir'} onClick={() => setExpandedInfo(e => !e)} />
              </div>
            </div>
            <div className="dl">
              <DLRow icon={ICN.users} label="Nome"           value={c.nome.split(' ')[0]} />
              <DLRow icon={ICN.users} label="Sobrenome"      value={c.nome.split(' ').slice(1).join(' ')} />
              <DLRow icon={ICN.mail}  label="E-mail"         value={c.email}  action={ICN.plus} />
              <DLRow icon={ICN.phone} label="Telefone"       value={c.fone}   action={ICN.plus} />
              <DLRow icon={ICN.share} label="Fontes"
                value={
                  <div className="row" style={{gap:6}}>
                    <SrcChip color="mint" label="WA"/>
                    <SrcChip color="blue" label="LI"/>
                    <SrcChip color="pink" label="IG"/>
                    <SrcChip color="lav"  label="DC"/>
                  </div>
                }
                action={ICN.link}
              />
              <DLRow icon={ICN.cal} label="Último contato" value="13/05 às 16:42" action={ICN.arrowUp} />
              {expandedInfo && <>
                <DLRow icon={ICN.share} label="Cidade"       value={c.cidade} />
                <DLRow icon={ICN.chart} label="Tag"          value={<span className="pill">{c.tag}</span>} />
                <DLRow icon={ICN.users} label="ID do contato" value={`#${c.id}`} />
                <DLRow icon={ICN.send}  label="Criado em"    value="01/01/2025 às 09:00" />
              </>}
            </div>
          </div>
        </div>
      </div>

      {showEdit && (
        <ContatoModal
          initialData={c}
          onClose={() => setShowEdit(false)}
          onSave={(updated) => { if (onEdit) onEdit(updated); setShowEdit(false); }}
        />
      )}
      {showAtribuir && (
        <AtribuirModal contact={c} onClose={() => setShowAtribuir(false)} />
      )}

      <style>{`
        .cd-grid { display: grid; grid-template-columns: 1.6fr 1fr; gap: 14px; align-items: start; }
        .cd-card { padding: 16px 18px 8px !important; }
        .interactions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
        .dl { display: flex; flex-direction: column; }
        .dl-row { display: grid; grid-template-columns: 28px 1fr auto; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid oklch(0.93 0.01 255); }
        .dl-row:last-child { border-bottom: 0; }
        .dl-ic { color: var(--ink-muted); }
        .dl-lbl { font-size: 11px; color: var(--ink-muted); }
        .dl-val { font-size: 13px; font-weight: 500; }
      `}</style>
    </>
  );
}

/* ─── helpers API ───────────────────────────────────────────── */
const contatoHeaders = () => {
  const t = localStorage.getItem('ezza_token');
  return { 'Content-Type': 'application/json', ...(t ? { 'Authorization': `Bearer ${t}` } : {}) };
};

/* ─── Contatos (root) ───────────────────────────────────────── */
function Contatos({ contactId, setContactId, goto }) {
  const { useEffect: useContatoEffect } = React;
  const [localContatos, setLocalContatos] = useContatoState([]);
  const [apiReady, setApiReady] = useContatoState(false);

  // Carrega do banco
  useContatoEffect(() => {
    fetch('/api/contatos', { headers: contatoHeaders() })
      .then(r => r.json())
      .then(d => {
        if (d.ok) setLocalContatos(d.contatos);
        else setLocalContatos([...CONTATOS]); // fallback demo
      })
      .catch(() => setLocalContatos([...CONTATOS]))
      .finally(() => setApiReady(true));
  }, []);

  const handleEdit = async (updated) => {
    setLocalContatos(prev => prev.map(c => c.id === updated.id ? { ...c, ...updated } : c));
    try {
      await fetch(`/api/contatos/${updated.id}`, {
        method: 'PUT', headers: contatoHeaders(), body: JSON.stringify(updated),
      });
    } catch (e) {}
  };

  const handleDelete = async (id) => {
    setLocalContatos(prev => prev.filter(c => c.id !== id));
    setContactId(null);
    try { await fetch(`/api/contatos/${id}`, { method: 'DELETE', headers: contatoHeaders() }); } catch (e) {}
  };

  const handleCreate = async (novo) => {
    try {
      const r = await fetch('/api/contatos', {
        method: 'POST', headers: contatoHeaders(), body: JSON.stringify(novo),
      });
      const d = await r.json();
      if (d.ok) setLocalContatos(prev => [d.contato, ...prev]);
      else setLocalContatos(prev => [{ ...novo, id: Date.now() }, ...prev]);
    } catch (e) {
      setLocalContatos(prev => [{ ...novo, id: Date.now() }, ...prev]);
    }
  };

  if (contactId) {
    const c = localContatos.find(x => x.id === contactId);
    if (c) {
      return (
        <ContactDetail
          contact={c}
          onBack={() => setContactId(null)}
          onEdit={handleEdit}
          onDelete={handleDelete}
          goto={goto}
        />
      );
    }
  }

  return (
    <ContactsList
      localContatos={localContatos}
      setLocalContatos={setLocalContatos}
      onSelect={setContactId}
      selectedId={contactId}
      onCreateContato={handleCreate}
    />
  );
}

window.Contatos = Contatos;
