// Tela: Pipeline de Vendas — kanban de leads + modal Novo Lead + drawer detalhe

const { useState: usePipeState } = React;

function TempPill({ temp, big }) {
  const map = {
    frio:   { cls: "pill-blue",   label: "FRIO"   },
    morno:  { cls: "pill-yellow", label: "MORNO"  },
    quente: { cls: "pill-pink",   label: "QUENTE" },
  };
  const m = map[temp] || map.morno;
  return (
    <span className={`pill ${m.cls}`} style={{
      fontSize: big ? 12 : 10,
      letterSpacing: '0.08em',
      padding: big ? '6px 12px' : '3px 9px',
    }}>{m.label}</span>
  );
}

function LeadCard({ lead, onOpen, onWhatsApp, onDragStart, onDragEnd, isDragging }) {
  const statusIcon = lead.status?.toLowerCase().includes('aguard') ? ICN.mic : ICN.phone;
  const hasAi  = lead.status?.toLowerCase() === 'em conversa';
  const isGanho = lead.etapa === 'fechado' && lead.status === 'Ganho';

  const BoltIcon = () => (
    <svg width="9" height="9" viewBox="0 0 24 24" fill="currentColor"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"/></svg>
  );

  return (
    <div
      className={`lead-card ${hasAi ? 'lead-card-ai' : ''} ${isGanho ? 'lead-card-ganho' : ''} ${isDragging ? 'lead-card-dragging' : ''}`}
      draggable="true"
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      onClick={() => onOpen(lead)}
    >
      {hasAi && !isGanho && (
        <div className="lead-ai-badge" title="IA SDR ativa nesta conversa">
          <BoltIcon /> IA
          <span className="lead-ai-pulse" />
        </div>
      )}
      {isGanho && (
        <div className="lead-ganho-badge">🏆 Ganho</div>
      )}
      <div className="lead-card-top">
        <div className="lead-name">{lead.nome.split(' ').slice(0,2).join(' ')}</div>
        <TempPill temp={lead.temp} />
      </div>
      <div className="lead-empresa muted">{lead.empresa}</div>
      <div className="lead-valor money">R$ {lead.valor.toLocaleString('pt-BR')},00</div>
      <div className="lead-foot">
        <span className="lead-status">
          <span className="lead-status-ic">{statusIcon}</span>
          {lead.status}
        </span>
        <div className={`lead-wa ${hasAi ? 'lead-wa-ai' : ''}`} title="Abrir conversa WhatsApp" onClick={(e) => { e.stopPropagation(); onWhatsApp && onWhatsApp(lead); }}>{ICN.whatsapp}</div>
      </div>
    </div>
  );
}

function PrioridadeCard({ lead, rank, onOpen }) {
  return (
    <div className="prio-card" onClick={() => onOpen(lead)}>
      <div className="prio-row">
        <span className="prio-rank">#{rank}</span>
        <span className="prio-pts">{lead.pontos} <span>PTS</span></span>
      </div>
      <div className="prio-nome">{lead.nome.split(' ').slice(0,2).join(' ')}</div>
      <div className="prio-fone muted">{lead.whatsapp}</div>
    </div>
  );
}

function NovoLeadModal({ onClose, onCreate }) {
  const [temp, setTemp] = usePipeState('morno');
  const [iaVoz, setIaVoz] = usePipeState(false);
  const [nome, setNome] = usePipeState('');
  const [wapp, setWapp] = usePipeState('');
  const [origem, setOrigem] = usePipeState('Site');
  const [nicho, setNicho] = usePipeState('');
  const [instrucoes, setInstrucoes] = usePipeState('');
  const [valor, setValor] = usePipeState('');

  const valid = nome.trim().length > 0;

  const submit = () => {
    if (!valid) return;
    onCreate({
      nome: nome.trim(),
      empresa: nicho.trim() || null,
      whatsapp: wapp || null,
      origem,
      nicho: nicho || null,
      valor: parseInt(valor.replace(/\D/g, '')) || 0,
      temp,
      etapa: 'novo-lead',
      status: iaVoz ? 'Em conversa' : 'Aguardando',
      pontos: temp === 'quente' ? 82 : temp === 'morno' ? 54 : 32,
    });
  };

  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">Novo Lead <em>Comercial</em></div>
            <div className="modal-sub muted">Preencha os dados da negociação</div>
          </div>
          <div className="mini-btn" onClick={onClose}>{ICN.x}</div>
        </div>

        <div className="form-grid">
          <Field label="Nome do lead / empresa" full>
            <input className="ezz-input" placeholder="Ex: Investimentos S.A." value={nome} onChange={e => setNome(e.target.value)} />
          </Field>
          <Field label="WhatsApp">
            <input className="ezz-input" placeholder="(11) 99999-9999" value={wapp} onChange={e => setWapp(e.target.value)} />
          </Field>
          <Field label="Origem do lead">
            <select className="ezz-input" value={origem} onChange={e => setOrigem(e.target.value)} style={{appearance:'auto'}}>
              {['Indicação','Meta Ads','Site','LinkedIn','Evento'].map(o => <option key={o}>{o}</option>)}
            </select>
          </Field>
          <Field label="Nicho / Segmento" full>
            <input className="ezz-input" placeholder="Ex: Construção civil, SaaS…" value={nicho} onChange={e => setNicho(e.target.value)} />
          </Field>
          <Field label="Instruções para IA" full>
            <textarea className="ezz-input" rows="3" placeholder="Ex: Focar em agendamento, ser persuasivo…"
              value={instrucoes} onChange={e => setInstrucoes(e.target.value)} style={{fontFamily:'inherit', resize:'vertical'}} />
          </Field>
          <Field label="Valor estimado">
            <div className="ezz-input ezz-input-prefix">
              <span className="muted" style={{fontSize:13, fontWeight:600}}>R$</span>
              <input placeholder="0" value={valor} onChange={e => setValor(e.target.value)} style={{border:0, outline:0, flex:1, fontFamily:'inherit', fontSize:13}} />
            </div>
          </Field>
          <Field label="Temperatura (interesse)">
            <div className="temp-seg">
              {['frio','morno','quente'].map(t => (
                <button key={t} className={`temp-btn ${temp === t ? 'temp-btn-on temp-btn-' + t : ''}`} onClick={() => setTemp(t)}>
                  {t.toUpperCase()}
                </button>
              ))}
            </div>
          </Field>
        </div>

        <div className={`ai-toggle ${iaVoz ? 'ai-toggle-on' : ''}`} onClick={() => setIaVoz(!iaVoz)}>
          <div className="ai-toggle-ic">{ICN.bolt2}</div>
          <div className="col" style={{flex:1}}>
            <div className="ai-toggle-title">Ativar IA de Voz Imediata</div>
            <div className="ai-toggle-sub muted">O robô ligará para o cliente assim que o lead for salvo.</div>
          </div>
          <div className={`switch ${iaVoz ? 'switch-on' : ''}`}>
            <div className="switch-knob" />
          </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}}>Criar Negócio</button>
        </div>
      </div>
    </div>
  );
}

function Field({ label, full, children }) {
  return (
    <div className={`field ${full ? 'field-full' : ''}`}>
      <div className="field-lbl">{label}</div>
      {children}
    </div>
  );
}

function SelectMock({ value, muted }) {
  return (
    <div className="ezz-input ezz-select">
      <span style={{color: muted ? 'var(--ink-faint)' : 'var(--ink)', fontSize: 13, fontWeight: muted ? 400 : 600}}>{value}</span>
      <span className="muted">{ICN.chevron}</span>
    </div>
  );
}

function LeadDrawer({ lead, onClose, onRemove, onUpdate }) {
  if (!lead) return null;
  const toast = useToast();
  const ringPct = lead.pontos;
  const grau = lead.pontos >= 80 ? 'A' : lead.pontos >= 50 ? 'B' : 'C';
  const [aiResumo, setAiResumo] = React.useState(null);
  const [aiLoading, setAiLoading] = React.useState(false);

  // ── Edição inline ─────────────────────────────────────────
  const [editing, setEditing] = React.useState(false);
  const [editNome, setEditNome] = React.useState(lead.nome);
  const [editValor, setEditValor] = React.useState(lead.valor);
  const [editEtapa, setEditEtapa] = React.useState(lead.etapa);
  const [editTemp, setEditTemp] = React.useState(lead.temp);

  const salvarEdicao = () => {
    if (onUpdate) onUpdate(lead.id, { nome: editNome, valor: Number(editValor), etapa: editEtapa, temp: editTemp });
    toast('Lead atualizado ✓');
    setEditing(false);
  };

  // ── Notas ─────────────────────────────────────────────────
  const [notas, setNotas] = React.useState([]);
  const [novaNota, setNovaNota] = React.useState('');
  const addNota = () => {
    if (!novaNota.trim()) return;
    const agora = new Date();
    const when = agora.toLocaleDateString('pt-BR') + ', ' + agora.toLocaleTimeString('pt-BR', { hour:'2-digit', minute:'2-digit' });
    setNotas(prev => [{ texto: novaNota.trim(), when }, ...prev]);
    setNovaNota('');
    toast('Anotação salva');
  };

  // ── Timeline com datas reais ───────────────────────────────
  const hoje = new Date();
  const fmt = (d) => d.toLocaleDateString('pt-BR') + ', ' + d.toLocaleTimeString('pt-BR', { hour:'2-digit', minute:'2-digit' });
  const d1 = new Date(hoje); d1.setDate(d1.getDate() - 3);
  const d2 = new Date(hoje); d2.setDate(d2.getDate() - 2); d2.setHours(16, 8);
  const d3 = new Date(hoje); d3.setDate(d3.getDate() - 1); d3.setHours(9, 12);

  const gerarResumo = async () => {
    setAiLoading(true);
    setAiResumo(null);
    try {
      const res = await fetch('/api/ai/resumo', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          lead: {
            nome: lead.nome,
            empresa: lead.empresa || lead.nicho,
            stage: lead.stage,
            valor: lead.valor,
            temp: lead.temp,
            origem: lead.origem,
            historico: `Lead com pontuação ${lead.pontos}/100, nicho: ${lead.nicho}, origem: ${lead.origem}.`,
          }
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || 'Erro desconhecido');
      setAiResumo(data);
    } catch (err) {
      toast('Erro ao gerar resumo: ' + err.message);
    } finally {
      setAiLoading(false);
    }
  };

  return (
    <>
      <div className="drawer-scrim" onClick={onClose} />
      <aside className="drawer card">
        <div className="drawer-head">
          <div className="row" style={{gap: 14, flex: 1}}>
            <div className="drawer-av">{ICN.user}</div>
            <div className="col">
              <div className="drawer-name">{lead.nome.split(' ').slice(0,2).join(' ')}</div>
              <div className="row" style={{gap: 8, fontSize: 11.5, color: 'var(--ink-muted)', marginTop: 2}}>
                <span className="row" style={{gap:4, whiteSpace:'nowrap'}}>{ICN.phone} {lead.whatsapp}</span>
                <span className="dot-sep">•</span>
                <span style={{textTransform:'uppercase', letterSpacing:'0.06em', fontWeight: 600}}>{lead.origem}</span>
                <span className="dot-sep">•</span>
                <span style={{textTransform:'uppercase', letterSpacing:'0.06em', fontWeight: 600}}>{lead.nicho}</span>
              </div>
            </div>
          </div>
          <div className="row" style={{gap: 4}}>
            <ActionBtn icon={editing ? ICN.check : ICN.edit} title={editing ? 'Salvar' : 'Editar lead'} onClick={editing ? salvarEdicao : () => setEditing(true)} />
            {editing && <ActionBtn icon={ICN.x} title="Cancelar edição" onClick={() => setEditing(false)} />}
            <button className="mini-btn" onClick={onClose}>{ICN.x}</button>
          </div>
        </div>

        {/* Seletor de etapa quando editando */}
        {editing && (
          <div style={{padding:'0 20px 12px 20px', borderBottom:'1px solid oklch(0.93 0.01 250)', marginBottom:4}}>
            <div style={{fontSize:10, fontWeight:700, letterSpacing:'0.08em', color:'var(--ink-muted)', textTransform:'uppercase', marginBottom:8}}>Etapa do lead</div>
            <div style={{display:'flex', gap:6, overflowX:'auto', paddingBottom:4}}>
              {PIPELINE_ETAPAS.map(et => (
                <span key={et.id}
                  onClick={() => setEditEtapa(et.id)}
                  style={{
                    padding:'5px 12px', borderRadius:999, fontSize:11, fontWeight:700,
                    cursor:'pointer', whiteSpace:'nowrap', flexShrink:0,
                    background: editEtapa === et.id ? 'oklch(0.55 0.16 250)' : 'oklch(0.93 0.02 250)',
                    color: editEtapa === et.id ? 'white' : 'var(--ink-muted)',
                    transition:'all .15s',
                    boxShadow: editEtapa === et.id ? '0 2px 8px -2px oklch(0.55 0.16 250 / 0.4)' : 'none',
                  }}>{et.label}</span>
              ))}
            </div>
          </div>
        )}

        <div className="drawer-body">
          {/* Edição de nome e valor */}
          {editing && (
            <div className="drawer-block" style={{display:'flex', gap:10}}>
              <div className="field" style={{flex:2}}>
                <label className="field-lbl">Nome</label>
                <input className="ezz-input" value={editNome} onChange={e => setEditNome(e.target.value)} />
              </div>
              <div className="field" style={{flex:1}}>
                <label className="field-lbl">Valor (R$)</label>
                <input className="ezz-input" type="number" value={editValor} onChange={e => setEditValor(e.target.value)} />
              </div>
              <div className="field" style={{flex:1}}>
                <label className="field-lbl">Temperatura</label>
                <select className="ezz-input" value={editTemp} onChange={e => setEditTemp(e.target.value)}>
                  <option value="frio">Frio</option>
                  <option value="morno">Morno</option>
                  <option value="quente">Quente</option>
                </select>
              </div>
            </div>
          )}

          <div className="drawer-block">
            <div className="drawer-block-lbl">Anotações do lead</div>
            <div style={{display:'flex', gap:8, marginBottom:8}}>
              <input
                className="ezz-input"
                style={{flex:1, fontSize:12}}
                placeholder="Adicionar anotação…"
                value={novaNota}
                onChange={e => setNovaNota(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && addNota()}
              />
              <button className="btn-primary btn-sm" onClick={addNota} disabled={!novaNota.trim()}>Salvar</button>
            </div>
            {notas.length === 0
              ? <div className="drawer-block-body muted">Nenhuma anotação registrada.</div>
              : notas.map((n, i) => (
                  <div key={i} style={{background:'oklch(0.97 0.01 250)', borderRadius:10, padding:'8px 12px', marginBottom:6}}>
                    <div style={{fontSize:12.5}}>{n.texto}</div>
                    <div style={{fontSize:10.5, color:'var(--ink-muted)', marginTop:4}}>{n.when}</div>
                  </div>
                ))
            }
          </div>

          <div className="drawer-block">
            <div className="drawer-block-lbl">Pontuação do lead</div>
            <div className="row" style={{gap: 16, alignItems:'center'}}>
              <div className="col" style={{flex: 1}}>
                <div style={{fontSize: 19, fontWeight: 700, letterSpacing: '-0.02em'}}>Qualidade Grau {grau}</div>
                <div className="muted" style={{fontSize: 12, marginTop: 4, lineHeight: 1.4}}>Calculada com base na temperatura, valor e engajamento.</div>
              </div>
              <ScoreRing pct={ringPct} />
            </div>
          </div>

          <div className="ai-card">
            <div className="row" style={{gap: 12, alignItems: 'flex-start'}}>
              <div className="ai-card-ic">{ICN.bolt2}</div>
              <div className="col" style={{flex: 1}}>
                <div className="ai-card-title">Análise Inteligente</div>
                <div className="ai-card-sub">
                  {aiLoading ? 'Consultando IA…' : aiResumo ? aiResumo.resumo : 'Gere um resumo imediato das dores e necessidades deste lead.'}
                </div>
              </div>
              <button
                className="btn-primary btn-sm"
                onClick={gerarResumo}
                disabled={aiLoading}
                style={{opacity: aiLoading ? 0.6 : 1, whiteSpace:'nowrap'}}
              >
                {aiLoading ? '⏳ Gerando…' : aiResumo ? '↻ Atualizar' : 'Gerar Resumo IA'}
              </button>
            </div>

            {aiResumo && (
              <div style={{marginTop: 14, display:'flex', flexDirection:'column', gap: 8}}>
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap: 8}}>
                  <div style={{background:'oklch(0.96 0.03 160)', borderRadius: 10, padding:'10px 12px'}}>
                    <div style={{fontSize:10, fontWeight:700, letterSpacing:'0.08em', color:'oklch(0.45 0.14 160)', textTransform:'uppercase', marginBottom:4}}>Dor principal</div>
                    <div style={{fontSize:12.5, fontWeight:500, color:'oklch(0.25 0.05 160)'}}>{aiResumo.dor}</div>
                  </div>
                  <div style={{background:'oklch(0.96 0.04 250)', borderRadius: 10, padding:'10px 12px'}}>
                    <div style={{fontSize:10, fontWeight:700, letterSpacing:'0.08em', color:'oklch(0.45 0.14 250)', textTransform:'uppercase', marginBottom:4}}>Próximo passo</div>
                    <div style={{fontSize:12.5, fontWeight:500, color:'oklch(0.25 0.05 250)'}}>{aiResumo.proximo_passo}</div>
                  </div>
                </div>
                <div style={{display:'flex', alignItems:'center', gap:10, background:'oklch(0.97 0.01 255)', borderRadius:10, padding:'8px 12px'}}>
                  <div style={{fontSize:10, fontWeight:700, letterSpacing:'0.08em', color:'var(--ink-muted)', textTransform:'uppercase', whiteSpace:'nowrap'}}>Score IA</div>
                  <div style={{flex:1, height:6, borderRadius:6, background:'oklch(0.90 0.02 255)', overflow:'hidden'}}>
                    <div style={{height:'100%', width: aiResumo.score + '%', borderRadius:6, background: aiResumo.score >= 70 ? 'oklch(0.58 0.18 155)' : aiResumo.score >= 40 ? 'oklch(0.68 0.18 95)' : 'oklch(0.58 0.20 25)', transition:'width .6s ease'}} />
                  </div>
                  <span style={{fontSize:14, fontWeight:800, color: aiResumo.score >= 70 ? 'oklch(0.40 0.16 155)' : aiResumo.score >= 40 ? 'oklch(0.45 0.16 95)' : 'oklch(0.45 0.18 25)', minWidth:44, textAlign:'right', letterSpacing:'-0.02em'}}>{aiResumo.score}<span style={{fontSize:10, fontWeight:600, opacity:0.6}}>/100</span></span>
                </div>
              </div>
            )}
          </div>

          <div className="row" style={{gap: 10, alignItems:'stretch'}}>
            <div className="drawer-block" style={{flex:1, margin:0}}>
              <div className="drawer-block-lbl">Valor do negócio</div>
              <div className="money" style={{fontSize: 20, fontWeight: 700, letterSpacing:'-0.02em'}}>R$ {lead.valor.toLocaleString('pt-BR')},00</div>
            </div>
            <div className="drawer-block" style={{flex:1, margin:0}}>
              <div className="drawer-block-lbl">Temperatura</div>
              <TempPill temp={lead.temp} big />
            </div>
          </div>

          <div className="drawer-block">
            <div className="drawer-block-lbl row" style={{gap:8}}>
              {ICN.cal} Histórico do lead
            </div>
            <div className="timeline">
              <TLItem ic={ICN.plus}  title="Lead criado"       body="Lead adicionado ao sistema."                    when={fmt(d1)} color="mint" />
              <TLItem ic={ICN.phone} title="Primeiro contato"  body={`Conversa iniciada via ${lead.origem}.`}        when={fmt(d2)} color="blue" />
              <TLItem ic={ICN.mail}  title="Material enviado"  body="Catálogo de produtos compartilhado."            when={fmt(d3)} color="yellow" />
              {notas.map((n, i) => (
                <TLItem key={i} ic={ICN.edit} title="Anotação adicionada" body={n.texto} when={n.when} color="lav" />
              ))}
            </div>
          </div>
        </div>

        <div className="drawer-foot">
          {lead.etapa === 'perdido' ? (
            <div className="row" style={{gap: 8}}>
              <button className="btn-reativar" onClick={() => {
                onUpdate && onUpdate(lead.id, { etapa: 'novo-lead', status: 'Aguardando', temp: 'morno' });
                toast(`↩ ${lead.nome.split(' ')[0]} reativado — voltou para Novo Lead`);
                onClose();
              }}>↩ Reativar lead</button>
              <button className="btn-danger" onClick={() => { onRemove && onRemove(lead.id); onClose(); toast('Lead excluído definitivamente'); }}>{ICN.trash} Excluir</button>
            </div>
          ) : (
            <div className="row" style={{gap: 8}}>
              <button className="btn-ganhou" onClick={() => {
                onUpdate && onUpdate(lead.id, { etapa: 'fechado', status: 'Ganho', temp: 'quente' });
                toast(`🏆 ${lead.nome.split(' ')[0]} movido para Fechado · Ganho!`);
                onClose();
              }}>{ICN.check} Ganhou</button>
              <button className="btn-perdeu" onClick={() => {
                onUpdate && onUpdate(lead.id, { etapa: 'perdido', status: 'Perdido', temp: 'frio' });
                toast(`${lead.nome.split(' ')[0]} marcado como Perdido`);
                onClose();
              }}>{ICN.x} Perdeu</button>
            </div>
          )}
          {lead.etapa !== 'perdido' && (
            <button className="btn-danger" onClick={() => { onRemove && onRemove(lead.id); onClose(); toast('Lead excluído'); }}>{ICN.trash} Excluir lead</button>
          )}
        </div>
      </aside>
    </>
  );
}

function ScoreRing({ pct }) {
  const r = 32, c = 2 * Math.PI * r;
  const off = c * (1 - pct/100);
  return (
    <div style={{position:'relative', width: 80, height: 80}}>
      <svg width="80" height="80" viewBox="0 0 80 80">
        <circle cx="40" cy="40" r={r} fill="none" stroke="oklch(0.93 0.01 250)" strokeWidth="7"/>
        <circle cx="40" cy="40" r={r} fill="none" stroke="oklch(0.55 0.16 250)" strokeWidth="7"
          strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off}
          transform="rotate(-90 40 40)"/>
      </svg>
      <div style={{position:'absolute', inset:0, display:'grid', placeItems:'center', textAlign:'center'}}>
        <div>
          <div style={{fontSize: 19, fontWeight: 700, lineHeight: 1, letterSpacing:'-0.02em'}}>{pct}</div>
          <div style={{fontSize: 9, color: 'var(--ink-muted)', marginTop: 2}}>pts</div>
        </div>
      </div>
    </div>
  );
}

function TLItem({ ic, title, body, when, color }) {
  return (
    <div className="tl-item">
      <div className={`tl-bullet tl-${color}`}>{ic}</div>
      <div className="tl-card">
        <div className="row" style={{justifyContent:'space-between', gap: 8}}>
          <span className="tl-title">{title}</span>
          <span className="tl-when muted">{when}</span>
        </div>
        <div className="tl-body muted">{body}</div>
      </div>
    </div>
  );
}

// Helpers de API autenticada
const apiHeaders = () => {
  const t = localStorage.getItem('ezza_token');
  return { 'Content-Type': 'application/json', ...(t ? { 'Authorization': `Bearer ${t}` } : {}) };
};

function Pipeline() {
  const [modal, setModal] = usePipeState(false);
  const [selectedLead, setSelectedLead] = usePipeState(null);
  const [activeConv, setActiveConv] = usePipeState(null);
  const [localLeads, setLocalLeads] = usePipeState([]);
  const [etapas, setEtapas] = usePipeState([...PIPELINE_ETAPAS]); // fallback para as etapas padrão
  const [dragLeadId, setDragLeadId] = usePipeState(null);
  const [dragOverEtapa, setDragOverEtapa] = usePipeState(null);
  const [apiLoading, setApiLoading] = usePipeState(true);
  const toast = useToast();

  // ── Carrega leads e etapas do banco ─────────────────────────────
  const { useState: _u, useEffect: useApiEffect } = React;
  useApiEffect(() => {
    const load = async () => {
      try {
        const [rLeads, rEtapas] = await Promise.all([
          fetch('/api/pipeline/leads', { headers: apiHeaders() }),
          fetch('/api/pipeline/etapas', { headers: apiHeaders() }),
        ]);
        const dLeads  = await rLeads.json();
        const dEtapas = await rEtapas.json();
        if (dLeads.ok)  setLocalLeads(dLeads.leads.map(l => ({ ...l, valor: parseFloat(l.valor) || 0 })));
        if (dEtapas.ok && dEtapas.etapas.length) setEtapas(dEtapas.etapas.map(e => ({ id: e.slug, label: e.label, color: e.cor })));
      } catch (e) {
        console.warn('Pipeline: usando dados locais', e);
        setLocalLeads([...LEADS]);
      } finally {
        setApiLoading(false);
      }
    };
    load();
  }, []);

  const handleDragStart = (e, lead) => {
    setDragLeadId(lead.id);
    e.dataTransfer.effectAllowed = 'move';
  };
  const handleDragEnd = () => {
    setDragLeadId(null);
    setDragOverEtapa(null);
  };
  const handleDragOver = (e, etapaId) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    if (dragOverEtapa !== etapaId) setDragOverEtapa(etapaId);
  };
  const handleDragLeave = (e) => {
    const rel = e.relatedTarget;
    if (!rel || !e.currentTarget.contains(rel)) setDragOverEtapa(null);
  };
  const handleDrop = async (e, etapaId) => {
    e.preventDefault();
    if (dragLeadId == null) return;
    // Otimista: atualiza UI imediatamente
    setLocalLeads(prev => prev.map(l => l.id === dragLeadId ? { ...l, etapa: etapaId } : l));
    setDragLeadId(null);
    setDragOverEtapa(null);
    // Persiste no banco
    try {
      await fetch(`/api/pipeline/leads/${dragLeadId}/etapa`, {
        method: 'PATCH',
        headers: apiHeaders(),
        body: JSON.stringify({ etapa: etapaId }),
      });
    } catch (err) {
      toast('Erro ao salvar movimentação');
    }
  };

  const openConv = (lead) => {
    const contato = { nome: lead.nome, avatar: AVATAR_URLS[(lead.id - 1) % 12] };
    setActiveConv(contato);
  };
  const handleCreate = async (formData) => {
    try {
      const r = await fetch('/api/pipeline/leads', {
        method: 'POST',
        headers: apiHeaders(),
        body: JSON.stringify(formData),
      });
      const d = await r.json();
      if (d.ok) {
        setLocalLeads(prev => [{ ...d.lead, valor: parseFloat(d.lead.valor) || 0 }, ...prev]);
        setModal(false);
        toast(`Lead "${d.lead.nome.split(' ')[0]}" criado!`);
      } else {
        toast('Erro ao criar lead: ' + d.error);
      }
    } catch (err) {
      toast('Erro de conexão ao criar lead');
    }
  };
  const handleRemove = async (id) => {
    setLocalLeads(prev => prev.filter(l => l.id !== id));
    try {
      await fetch(`/api/pipeline/leads/${id}`, { method: 'DELETE', headers: apiHeaders() });
    } catch (e) {}
  };
  const handleUpdate = async (id, changes) => {
    setLocalLeads(prev => prev.map(l => l.id === id ? { ...l, ...changes } : l));
    if (selectedLead && selectedLead.id === id) setSelectedLead(prev => ({ ...prev, ...changes }));
    try {
      const lead = localLeads.find(l => l.id === id) || {};
      await fetch(`/api/pipeline/leads/${id}`, {
        method: 'PUT',
        headers: apiHeaders(),
        body: JSON.stringify({ ...lead, ...changes }),
      });
    } catch (e) {}
  };

  const [tempFilter, setTempFilter] = usePipeState('Todas');
  const [origemFilter, setOrigemFilter] = usePipeState('Todas');
  const [search, setSearch] = usePipeState('');

  const [showPerdidos, setShowPerdidos] = usePipeState(false);

  const filtered = localLeads.filter(l => {
    if (l.etapa === 'perdido') return false; // perdidos ficam fora do pipeline principal
    if (tempFilter !== 'Todas' && l.temp.toLowerCase() !== tempFilter.toLowerCase()) return false;
    if (origemFilter !== 'Todas' && l.origem !== origemFilter) return false;
    if (search && !(`${l.nome} ${l.empresa} ${l.whatsapp}`.toLowerCase().includes(search.toLowerCase()))) return false;
    return true;
  });

  const perdidos = localLeads.filter(l => l.etapa === 'perdido');
  const totalPipe = filtered.reduce((s, l) => s + l.valor, 0);
  const top5 = [...localLeads].filter(l => l.etapa !== 'perdido').sort((a,b) => b.pontos - a.pontos).slice(0, 5);

  // KPIs calculados dos dados reais
  const leadsGanhos = localLeads.filter(l => l.etapa === 'fechado').length;
  const taxaConv    = ((leadsGanhos / Math.max(1, localLeads.length)) * 100).toFixed(1);
  // Ciclo médio: extrai dia do campo criado "DD/MM às HH:MM" e computa distância até hoje
  const cicloMedio = (() => {
    const hoje = new Date();
    const diffs = localLeads.filter(l => l.criado).map(l => {
      const m = l.criado.match(/(\d{2})\/(\d{2})/);
      if (!m) return null;
      const d = new Date(hoje.getFullYear(), parseInt(m[2])-1, parseInt(m[1]));
      return Math.round((hoje - d) / 86400000);
    }).filter(Boolean);
    return diffs.length ? Math.round(diffs.reduce((s,d) => s+d, 0) / diffs.length) : 27;
  })();

  return (
    <>
      <div className="pipe-head card">
        <div className="row" style={{gap: 14, flex: 1, minWidth: 0}}>
          <div className="pipe-bolt">{ICN.bolt2}</div>
          <div className="col" style={{minWidth: 0}}>
            <div className="pipe-title">Pipeline <em>de Vendas</em></div>
            <div className="pipe-sub muted">Gestão de leads & conversão</div>
          </div>
        </div>

        <div className="pipe-search">
          <span className="muted">{ICN.search}</span>
          <input
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Buscar por nome ou telefone…" />
        </div>

        <PipeDropdown label="Temp" value={tempFilter} options={['Todas','Frio','Morno','Quente']} onChange={setTempFilter} />
        <PipeDropdown label="Origem" value={origemFilter} options={['Todas','Indicação','Meta Ads','Site','LinkedIn','Evento']} onChange={setOrigemFilter} />

        <button className="btn-primary" onClick={() => setModal(true)}>
          {ICN.plus} <span>Novo Lead</span>
        </button>
      </div>

      <div className="pipe-strip">
        <Strip label="Leads no pipeline"     value={filtered.length}                pill="ativos" color="blue" />
        <Strip label="Valor total"           value={`R$ ${(totalPipe/1000).toFixed(1)}k`} pill="estimado" color="mint" />
        <Strip label="Taxa de conversão"     value={`${taxaConv}%`}                 pill={leadsGanhos > 0 ? `${leadsGanhos} ganho${leadsGanhos>1?'s':''}`  : 'nenhum fechado'} color="yellow" />
        <Strip label="Ciclo médio"           value={`${cicloMedio} dias`}           pill="desde criação" color="pink" />
      </div>

      {apiLoading && (
        <div style={{display:'flex', alignItems:'center', gap:12, padding:'24px 0', color:'var(--ink-muted)', fontSize:14}}>
          <div className="splash-spinner" style={{width:16,height:16}} />
          Carregando leads...
        </div>
      )}

      <div className="pipe-layout">
        <div className="pipe-kanban">
          {etapas.map(et => {
            const cards = filtered.filter(l => l.etapa === et.id);
            const isOver = dragOverEtapa === et.id && dragLeadId != null;
            return (
              <div
                key={et.id}
                className={`pipe-col pipe-col-${et.color} ${isOver ? 'pipe-col-over' : ''}`}
                onDragOver={(e) => handleDragOver(e, et.id)}
                onDragLeave={handleDragLeave}
                onDrop={(e) => handleDrop(e, et.id)}
              >
                <div className="pipe-col-head">
                  <span className="pipe-col-label">{et.label}</span>
                  <span className="pipe-col-count">{cards.length}</span>
                </div>
                <div className={`pipe-col-body ${isOver ? 'pipe-col-body-over' : ''}`}>
                  {cards.map(l => (
                    <LeadCard
                      key={l.id}
                      lead={l}
                      onOpen={setSelectedLead}
                      onWhatsApp={openConv}
                      onDragStart={(e) => handleDragStart(e, l)}
                      onDragEnd={handleDragEnd}
                      isDragging={dragLeadId === l.id}
                    />
                  ))}
                  {cards.length === 0 && <div className="pipe-empty muted">Arraste leads para cá</div>}
                </div>
              </div>
            );
          })}
        </div>

        <aside className="pipe-aside card">
          <div className="row" style={{gap: 8, marginBottom: 14}}>
            <span style={{color:'oklch(0.55 0.18 295)'}}>{ICN.bolt2}</span>
            <div className="card-title" style={{fontSize: 15}}>Top 5 Prioritários</div>
          </div>
          <div className="col" style={{gap: 10}}>
            {top5.map((l, i) => <PrioridadeCard key={l.id} lead={l} rank={i+1} onOpen={setSelectedLead} />)}
          </div>
        </aside>
      </div>

      {/* ── Seção Leads Perdidos ── */}
      {perdidos.length > 0 && (
        <div className="pipe-perdidos-wrap">
          <button className="pipe-perdidos-toggle" onClick={() => setShowPerdidos(v => !v)}>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" style={{transform: showPerdidos ? 'rotate(90deg)' : '', transition:'transform .2s'}}>
              <polyline points="9 18 15 12 9 6"/>
            </svg>
            <span>Leads perdidos</span>
            <span className="pipe-perdidos-badge">{perdidos.length}</span>
          </button>
          {showPerdidos && (
            <div className="pipe-perdidos-list">
              {perdidos.map(l => (
                <div key={l.id} className="pipe-perdido-row" onClick={() => setSelectedLead(l)}>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontWeight:600, fontSize:13}}>{l.nome.split(' ').slice(0,2).join(' ')}</div>
                    <div style={{fontSize:11, color:'var(--ink-muted)', marginTop:1}}>{l.empresa}</div>
                  </div>
                  <div style={{fontSize:12, color:'var(--ink-soft)', fontWeight:600}}>R$ {l.valor.toLocaleString('pt-BR')},00</div>
                  <button className="btn-reativar-sm" onClick={e => { e.stopPropagation(); handleUpdate(l.id, { etapa:'novo-lead', status:'Aguardando', temp:'morno' }); toast(`↩ ${l.nome.split(' ')[0]} reativado`); }}>↩ Reativar</button>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {modal && <NovoLeadModal onClose={() => setModal(false)} onCreate={handleCreate} />}
      <LeadDrawer lead={selectedLead} onClose={() => setSelectedLead(null)} onRemove={handleRemove} onUpdate={handleUpdate} />
      {activeConv && <ConversaDrawer contato={activeConv} onClose={() => setActiveConv(null)} />}

      <style>{`
        /* head */
        .pipe-head { display: flex; align-items: center; gap: 12px; padding: 14px 16px !important; margin-bottom: 14px; position: relative; z-index: 30; }
        .pipe-bolt {
          width: 44px; height: 44px; border-radius: 14px;
          background: linear-gradient(135deg, var(--acc-lav) 0%, oklch(0.70 0.15 295) 100%);
          color: white; display: grid; place-items: center;
          box-shadow: 0 12px 24px -10px oklch(0.55 0.20 295 / 0.5);
        }
        .pipe-title { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; line-height: 1; }
        .pipe-title em { font-family: var(--font-display); font-style: italic; font-weight: 400; color: var(--ink-soft); }
        .pipe-sub { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 600; margin-top: 4px; }

        .pipe-search {
          flex: 1; min-width: 200px;
          display: flex; align-items: center; gap: 10px;
          background: oklch(0.97 0.01 250 / 0.7);
          border: 0.5px solid oklch(1 0 0 / 0.8);
          border-radius: 999px;
          padding: 8px 16px;
        }
        .pipe-search input { border: 0; background: transparent; outline: none; flex: 1; font-family: inherit; font-size: 13px; color: var(--ink); }

        .pipe-dd {
          display: flex; align-items: center; gap: 8px;
          background: oklch(0.97 0.01 250 / 0.7);
          border: 0.5px solid oklch(1 0 0 / 0.8);
          border-radius: 999px;
          padding: 8px 14px 8px 16px;
          font-size: 13px; font-weight: 500;
          cursor: default;
          position: relative;
          user-select: none;
          z-index: 1;
        }
        .pipe-dd-open { z-index: 60; }
        .pipe-dd:hover { background: white; }
        .pipe-dd-open { background: white; box-shadow: 0 0 0 3px oklch(0.55 0.16 250 / 0.12); }
        .pipe-dd-val { color: var(--ink); }
        .pipe-dd-lbl { color: var(--ink-muted); }

        .pipe-dd-menu {
          position: absolute;
          top: calc(100% + 6px);
          left: 0;
          min-width: 160px;
          background: white;
          border: 0.5px solid oklch(0.92 0.01 250);
          border-radius: 14px;
          box-shadow: 0 16px 40px -12px rgba(20,30,60,.22), 0 4px 12px -4px rgba(20,30,60,.1);
          padding: 6px;
          z-index: 50;
          animation: fadein .15s ease;
        }
        .pipe-dd-item {
          display: flex; align-items: center; justify-content: space-between;
          padding: 8px 12px;
          border-radius: 10px;
          font-size: 13px;
          color: var(--ink);
          cursor: default;
        }
        .pipe-dd-item:hover { background: oklch(0.96 0.012 250); }
        .pipe-dd-item-on { background: var(--black); color: white; }
        .pipe-dd-item-on:hover { background: var(--black); color: white; }
        .pipe-dd-check { display: inline-flex; }

        /* strip */
        .pipe-strip { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 14px; }
        .strip { background: var(--card); backdrop-filter: blur(20px) saturate(160%); -webkit-backdrop-filter: blur(20px) saturate(160%); border: 0.5px solid var(--card-border); box-shadow: var(--card-shadow); border-radius: var(--radius-lg); padding: 14px 18px; }
        .cs-flat .strip { background: var(--card-solid); border: 0; box-shadow: none; }
        .cs-outlined .strip { background: transparent; border: 1px solid oklch(0.86 0.012 255); box-shadow: none; }
        .strip-lbl { font-size: 11px; color: var(--ink-muted); font-weight: 500; }
        .strip-row { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; margin-top: 6px; }
        .strip-val { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; }

        /* layout */
        .pipe-layout { display: grid; grid-template-columns: 1fr 280px; gap: 14px; align-items: start; }
        .pipe-kanban { display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; }

        .pipe-col { border-radius: var(--radius-md); padding: 14px 12px; min-height: 540px; }
        .pipe-col-blue   { background: linear-gradient(180deg, oklch(0.96 0.04 245) 0%, oklch(1 0 0 / 0.45) 100%); }
        .pipe-col-yellow { background: linear-gradient(180deg, oklch(0.97 0.06 95) 0%, oklch(1 0 0 / 0.45) 100%); }
        .pipe-col-lav    { background: linear-gradient(180deg, oklch(0.96 0.04 295) 0%, oklch(1 0 0 / 0.45) 100%); }
        .pipe-col-mint   { background: linear-gradient(180deg, oklch(0.96 0.05 160) 0%, oklch(1 0 0 / 0.45) 100%); }
        .pipe-col-pink   { background: linear-gradient(180deg, oklch(0.96 0.04 18) 0%, oklch(1 0 0 / 0.45) 100%); }
        .pipe-col-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px; padding: 0 4px; }
        .pipe-col-label { font-size: 10.5px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-soft); }
        .pipe-col-count { font-size: 11px; font-weight: 700; min-width: 22px; height: 22px; border-radius: 50%; background: white; color: var(--ink); display: grid; place-items: center; box-shadow: 0 1px 2px rgba(20,30,60,.08); }
        .pipe-col-body { display: flex; flex-direction: column; gap: 8px; }
        .pipe-empty { font-size: 11px; padding: 32px 12px; text-align: center; opacity: 0.6; border: 1px dashed oklch(0.85 0.01 250); border-radius: 14px; }

        /* lead card */
        .pipe-col-body { min-height: 80px; border-radius: 14px; transition: outline .12s, background .12s; }
        .pipe-col-body-over { outline: 2px dashed oklch(0.62 0.14 250 / 0.55); outline-offset: -2px; background: oklch(0.94 0.03 250 / 0.45); }

        .lead-card {
          position: relative;
          background: white;
          border-radius: 16px;
          padding: 12px 14px;
          box-shadow: 0 1px 0 rgba(255,255,255,.7) inset, 0 8px 18px -12px rgba(20,30,60,.15);
          cursor: grab;
          transition: transform .15s, box-shadow .15s, opacity .15s;
        }
        .lead-card:hover { transform: translateY(-2px); box-shadow: 0 1px 0 rgba(255,255,255,.7) inset, 0 14px 24px -12px rgba(20,30,60,.22); }
        .lead-card-dragging { opacity: 0.38; transform: scale(0.97) !important; box-shadow: none !important; cursor: grabbing; }
        .lead-card-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
        .lead-name { font-size: 13.5px; font-weight: 600; letter-spacing: -0.01em; line-height: 1.2; }
        .lead-empresa { font-size: 11px; margin-top: 3px; }
        .lead-valor { font-size: 15px; font-weight: 700; letter-spacing: -0.015em; margin-top: 10px; }
        .lead-foot { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; }
        .lead-status { display: inline-flex; align-items: center; gap: 6px; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: var(--ink-muted); }
        .lead-status-ic { display: grid; place-items: center; width: 22px; height: 22px; border-radius: 50%; background: oklch(0.95 0.01 250); color: var(--ink-soft); }
        .lead-wa { display: grid; place-items: center; width: 32px; height: 32px; border-radius: 50%; background: oklch(0.88 0.10 155); color: oklch(0.32 0.13 155); transition: transform .15s; }
        .lead-wa:hover { transform: scale(1.1); }
        .lead-wa-ai { background: oklch(0.88 0.08 295); color: oklch(0.38 0.16 295); }

        .lead-card-ai   { border: 1.5px solid oklch(0.82 0.08 295); box-shadow: 0 1px 0 rgba(255,255,255,.7) inset, 0 8px 20px -10px oklch(0.70 0.15 295 / 0.25); }
        .lead-card-ganho { border: 1.5px solid oklch(0.78 0.16 155); background: oklch(0.97 0.03 155); box-shadow: 0 1px 0 rgba(255,255,255,.8) inset, 0 8px 20px -10px oklch(0.65 0.18 155 / 0.30); }
        .lead-ganho-badge { position:absolute; top:10px; right:10px; background:oklch(0.65 0.18 155); color:white; border-radius:999px; padding:2px 8px; font-size:10px; font-weight:700; letter-spacing:0.02em; }
        .btn-reativar { flex:1; padding:10px; border-radius:10px; border:1.5px solid oklch(0.72 0.12 250); background:oklch(0.95 0.03 250); color:oklch(0.35 0.14 250); font-family:inherit; font-size:13px; font-weight:700; cursor:default; transition:all .15s; }
        .btn-reativar:hover { background:oklch(0.88 0.07 250); border-color:oklch(0.60 0.16 250); }
        .pipe-perdidos-wrap { margin: 8px 0 16px; }
        .pipe-perdidos-toggle { display:flex; align-items:center; gap:7px; background:none; border:none; cursor:default; font-family:inherit; font-size:12px; font-weight:600; color:var(--ink-muted); padding:6px 4px; transition:color .15s; }
        .pipe-perdidos-toggle:hover { color:var(--ink-soft); }
        .pipe-perdidos-badge { background:oklch(0.88 0.06 25); color:oklch(0.45 0.16 25); border-radius:999px; padding:1px 7px; font-size:10px; font-weight:700; }
        .pipe-perdidos-list { margin-top:6px; border:1px solid var(--ink-line); border-radius:12px; overflow:hidden; }
        .pipe-perdido-row { display:flex; align-items:center; gap:12px; padding:10px 14px; background:white; border-bottom:1px solid var(--ink-line); cursor:default; transition:background .12s; }
        .pipe-perdido-row:last-child { border-bottom:none; }
        .pipe-perdido-row:hover { background:oklch(0.97 0.01 255); }
        .btn-reativar-sm { background:oklch(0.95 0.03 250); color:oklch(0.35 0.14 250); border:1.5px solid oklch(0.82 0.06 250); border-radius:999px; padding:4px 11px; font-family:inherit; font-size:11px; font-weight:700; cursor:default; white-space:nowrap; transition:all .15s; flex-shrink:0; }
        .btn-reativar-sm:hover { background:oklch(0.88 0.07 250); border-color:oklch(0.60 0.16 250); }

        .lead-ai-badge {
          position: absolute; top: -1px; right: 12px;
          display: inline-flex; align-items: center; gap: 4px;
          background: oklch(0.55 0.18 295); color: white;
          font-size: 9.5px; font-weight: 800; letter-spacing: 0.06em;
          padding: 3px 8px 3px 6px; border-radius: 0 0 8px 8px;
          text-transform: uppercase;
        }
        .lead-ai-pulse {
          width: 6px; height: 6px; border-radius: 50%; background: white; opacity: 0.9;
          animation: ai-card-pulse 1.6s ease-in-out infinite;
        }
        @keyframes ai-card-pulse {
          0%,100% { opacity: 0.9; transform: scale(1); }
          50%      { opacity: 0.4; transform: scale(0.7); }
        }

        /* aside */
        .pipe-aside { position: sticky; top: 0; padding: 16px !important; }
        .prio-card {
          background: oklch(0.98 0.01 250);
          border-radius: 14px;
          padding: 10px 12px;
          cursor: default;
          border: 0.5px solid oklch(0.92 0.01 250);
        }
        .prio-card:hover { background: white; }
        .prio-row { display: flex; align-items: center; justify-content: space-between; }
        .prio-rank { font-size: 11px; font-weight: 700; color: oklch(0.55 0.16 295); }
        .prio-pts { font-size: 12.5px; font-weight: 700; color: var(--ink); font-feature-settings: "tnum"; white-space: nowrap; }
        .prio-pts span { font-size: 9px; color: var(--ink-muted); margin-left: 2px; letter-spacing: 0.08em; }
        .prio-nome { font-size: 13px; font-weight: 600; margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .prio-fone { font-size: 11px; margin-top: 2px; font-family: var(--font-mono); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

        /* btn — global rules live in styles.css; keep only overrides here */
        .ai-card .btn-primary { background: white; color: oklch(0.30 0.18 295); }
        .ai-card .btn-primary:hover { background: oklch(0.96 0.012 250); }

        /* modal */
        .modal-wrap {
          position: fixed; inset: 0;
          background: oklch(0.18 0.01 255 / 0.55);
          backdrop-filter: blur(8px);
          -webkit-backdrop-filter: blur(8px);
          z-index: 100;
          display: grid; place-items: center;
          animation: fadein .2s ease;
          padding: 24px;
        }
        .modal-card {
          width: 560px; max-width: 100%;
          max-height: 92vh; overflow-y: auto;
          background: oklch(1 0 0) !important;
        }
        .modal-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px; }
        .modal-title { font-size: 22px; font-weight: 700; letter-spacing: -0.02em; }
        .modal-title em { font-family: var(--font-display); font-style: italic; font-weight: 400; color: var(--ink-soft); }
        .modal-sub { font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 600; margin-top: 4px; }

        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 12px; }
        .field { display: flex; flex-direction: column; gap: 6px; }
        .field-full { grid-column: 1 / -1; }
        .field-lbl { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 700; color: var(--ink-muted); }
        .ezz-input {
          background: oklch(0.97 0.01 250);
          border: 0.5px solid oklch(0.90 0.01 250);
          border-radius: 12px;
          padding: 10px 14px;
          font-family: inherit;
          font-size: 13.5px;
          color: var(--ink);
          outline: none;
          width: 100%;
        }
        .ezz-input:focus { border-color: oklch(0.65 0.13 250); background: white; }
        .ezz-input::placeholder { color: var(--ink-faint); }
        .ezz-input-prefix { display: flex; align-items: center; gap: 8px; }
        .ezz-input-prefix input { border: 0; background: transparent; outline: none; flex: 1; font: inherit; }
        .ezz-select { display: flex; align-items: center; justify-content: space-between; cursor: default; }
        textarea.ezz-input { resize: vertical; font-family: inherit; }

        .temp-seg { display: flex; gap: 6px; }
        .temp-btn {
          flex: 1;
          background: oklch(0.97 0.01 250);
          border: 0.5px solid oklch(0.90 0.01 250);
          border-radius: 12px;
          padding: 9px 8px;
          font-family: inherit;
          font-size: 10.5px;
          font-weight: 700;
          letter-spacing: 0.1em;
          color: var(--ink-muted);
          cursor: default;
        }
        .temp-btn-on { color: var(--ink); }
        .temp-btn-frio   { background: oklch(0.92 0.06 250); border-color: oklch(0.70 0.10 250); color: oklch(0.36 0.13 250); }
        .temp-btn-morno  { background: oklch(0.94 0.10 95);  border-color: oklch(0.78 0.13 95);  color: oklch(0.38 0.13 80); }
        .temp-btn-quente { background: oklch(0.93 0.07 18);  border-color: oklch(0.74 0.11 18);  color: oklch(0.40 0.15 18); }

        .ai-toggle {
          margin-top: 18px;
          display: flex; align-items: center; gap: 12px;
          padding: 14px 16px;
          border-radius: 14px;
          background: oklch(0.96 0.025 295);
          border: 1px solid oklch(0.85 0.07 295);
        }
        .ai-toggle-ic { width: 32px; height: 32px; border-radius: 50%; background: oklch(0.55 0.18 295); color: white; display: grid; place-items: center; }
        .ai-toggle-title { font-size: 13px; font-weight: 700; color: oklch(0.30 0.15 295); }
        .ai-toggle-sub { font-size: 11.5px; color: oklch(0.40 0.10 295); margin-top: 2px; }

        /* switch base in styles.css */

        .modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 22px; }

        /* drawer */
        .drawer-scrim {
          position: fixed; inset: 0;
          background: oklch(0.18 0.01 255 / 0.4);
          backdrop-filter: blur(4px);
          -webkit-backdrop-filter: blur(4px);
          z-index: 90;
          animation: fadein .2s ease;
        }
        .drawer {
          position: fixed;
          top: 14px; right: 14px; bottom: 14px;
          width: 480px; max-width: calc(100vw - 28px);
          z-index: 100;
          display: flex; flex-direction: column;
          background: oklch(1 0 0) !important;
          padding: 0 !important;
          overflow: hidden;
          animation: slidein .25s ease;
        }
        @keyframes slidein { from { transform: translateX(20px); opacity: 0; } to { transform: none; opacity: 1; } }

        .drawer-head { display: flex; align-items: flex-start; gap: 8px; padding: 18px 20px; border-bottom: 1px solid oklch(0.93 0.01 255); }
        .drawer-av { width: 44px; height: 44px; border-radius: 50%; background: oklch(0.94 0.05 295); color: oklch(0.45 0.13 295); display: grid; place-items: center; flex-shrink: 0; }
        .drawer-name { font-size: 18px; font-weight: 700; letter-spacing: -0.02em; }
        .dot-sep { color: var(--ink-faint); }

        .drawer-body { flex: 1; overflow-y: auto; padding: 18px 20px; display: flex; flex-direction: column; gap: 14px; }
        .drawer-block { background: oklch(0.97 0.01 250 / 0.7); border: 0.5px solid oklch(0.92 0.01 250); border-radius: 16px; padding: 14px 16px; }
        .drawer-block-lbl { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.1em; font-weight: 700; color: var(--ink-muted); margin-bottom: 8px; }
        .drawer-block-body { font-size: 13px; }

        .ai-card {
          background: linear-gradient(135deg, oklch(0.42 0.18 295) 0%, oklch(0.48 0.20 280) 100%);
          color: white;
          border-radius: 16px;
          padding: 14px 16px;
        }
        .ai-card-ic { width: 28px; height: 28px; border-radius: 50%; background: oklch(1 0 0 / 0.18); display: grid; place-items: center; }
        .ai-card-title { font-size: 14px; font-weight: 700; }
        .ai-card-sub { font-size: 11.5px; opacity: 0.85; margin-top: 2px; line-height: 1.4; }
        .ai-card .btn-primary { background: white; color: oklch(0.30 0.18 295); }

        .timeline { display: flex; flex-direction: column; gap: 10px; margin-top: 8px; position: relative; padding-left: 30px; }
        .timeline::before { content: ''; position: absolute; left: 13px; top: 8px; bottom: 8px; width: 1px; background: oklch(0.90 0.01 250); }
        .tl-item { position: relative; }
        .tl-bullet { position: absolute; left: -30px; top: 2px; width: 26px; height: 26px; border-radius: 50%; display: grid; place-items: center; background: white; border: 1.5px solid; }
        .tl-mint   { color: oklch(0.42 0.15 160); border-color: oklch(0.42 0.15 160); }
        .tl-blue   { color: oklch(0.42 0.16 250); border-color: oklch(0.42 0.16 250); }
        .tl-yellow { color: oklch(0.50 0.13 80);  border-color: oklch(0.50 0.13 80); }
        .tl-card { background: white; border: 0.5px solid oklch(0.92 0.01 250); border-radius: 12px; padding: 10px 12px; }
        .tl-title { font-size: 11px; font-weight: 700; letter-spacing: 0.08em; text-transform: uppercase; color: var(--ink); }
        .tl-when { font-size: 10.5px; font-family: var(--font-mono); }
        .tl-body { font-size: 12.5px; margin-top: 4px; }

        .drawer-foot { padding: 14px 20px 18px; border-top: 1px solid oklch(0.93 0.01 255); display: flex; flex-direction: column; gap: 10px; }
        .btn-ganhou, .btn-perdeu, .btn-danger {
          flex: 1;
          border: 0;
          border-radius: 999px;
          padding: 12px 18px;
          font-family: inherit;
          font-size: 13px;
          font-weight: 700;
          letter-spacing: 0.04em;
          text-transform: uppercase;
          display: inline-flex; align-items: center; justify-content: center; gap: 8px;
          cursor: default;
        }
        .btn-ganhou { background: oklch(0.70 0.16 155); color: white; box-shadow: 0 12px 24px -12px oklch(0.55 0.16 155 / 0.5); }
        .btn-perdeu { background: oklch(0.94 0.01 250); color: var(--ink-soft); }
        .btn-danger { background: transparent; color: var(--danger); padding: 8px; font-size: 12px; }
      `}</style>
    </>
  );
}

function Strip({ label, value, pill, color }) {
  return (
    <div className="strip">
      <div className="strip-lbl">{label}</div>
      <div className="strip-row">
        <div className="strip-val money">{value}</div>
        <span className={`pill pill-${color}`}>{pill}</span>
      </div>
    </div>
  );
}

function PipeDropdown({ label, value, options, onChange }) {
  const [open, setOpen] = usePipeState(false);
  const ref = useOvRef ? useOvRef() : null;
  // close on outside click
  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (!e.target.closest('.pipe-dd')) setOpen(false); };
    window.addEventListener('mousedown', h);
    return () => window.removeEventListener('mousedown', h);
  }, [open]);
  return (
    <div className={`pipe-dd ${open ? 'pipe-dd-open' : ''}`} onClick={() => setOpen(o => !o)}>
      <span className="pipe-dd-lbl">{label}:</span>
      <span className="pipe-dd-val">{value}</span>
      <span className="muted">{ICN.chevron}</span>
      {open && (
        <div className="pipe-dd-menu" onClick={(e) => e.stopPropagation()}>
          {options.map(o => (
            <div
              key={o}
              className={`pipe-dd-item ${o === value ? 'pipe-dd-item-on' : ''}`}
              onClick={() => { onChange(o); setOpen(false); }}
            >
              <span>{o}</span>
              {o === value && <span className="pipe-dd-check">{ICN.check}</span>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

window.Pipeline = Pipeline;
