// SylenProspec — FLUXO direction (feed/focus first)
const { useState: uF, useEffect: eF, useMemo: mF, useRef: rF } = React;
const F = window.SYLEN_DATA;

const scoreCls = (s) => s >= 75 ? 'hot' : s >= 50 ? 'warm' : 'cool';
const stOf = (id) => F.STATUSES.find(s => s.id === id) || F.STATUSES[0];

// ============ HEADER ============
function Header({ onCmdK, status }) {
  return (
    <div className="header">
      <div className="brand">
        <div className="brand-mark image"><img src="shared/sylen-mark.png" alt="SYLEN" /></div>
        <div>SYLEN<span> AI</span></div>
      </div>
      <div className="header-mid">
        <div className="search" onClick={onCmdK}>
          <span className="mono" style={{ color: 'var(--text-muted)' }}>⌕</span>
          <span style={{ flex: 1 }}>Buscar leads, ações, atalhos…</span>
          <span className="kbd">⌘K</span>
        </div>
      </div>
      <div className="header-right">
        <div className={`pill conn-pill conn-${status}`} title={status === 'live' ? 'Conectado ao Supabase + n8n' : 'Modo demo — dados de exemplo'}>
          <div className="live-dot" style={{ background: status === 'live' ? 'var(--ok)' : 'var(--warm)' }} />
          <span>{status === 'live' ? 'CONECTADO' : 'DEMO'}</span>
        </div>
        <div className="avatar" title="Sair" style={{ cursor: 'pointer' }} onClick={() => {
          if (window.confirm('Sair da conta?')) {
            window.SYLEN_API.clearSession();
            location.reload();
          }
        }}>SR</div>
      </div>
    </div>
  );
}

// ============ SIDEBAR ============
const NAV_F = [
  { id: 'feed',      label: 'Feed',           glyph: '≡' },
  { id: 'focus',     label: 'Modo Foco',      glyph: '◎', highlight: true },
  { id: 'campanhas', label: 'Campanhas',      glyph: '◈' },
  { id: 'pipeline',  label: 'Pipeline',       glyph: '∥' },
  { id: 'composer',  label: 'Disparo',        glyph: '▶' },
  { id: 'templates', label: 'Templates',      glyph: '✎' },
  { id: 'lista',     label: 'Todos os leads', glyph: '○' },
];

function Sidebar({ view, setView, leads, opName }) {
  const hot = leads.filter(l => l.score >= 75).length;
  const waiting = leads.filter(l => l.status === 'respondeu').length;
  return (
    <div className="side">
      <div className="side-h">Hoje</div>
      {NAV_F.map(n => (
        <div key={n.id} className={`side-item ${view === n.id ? 'on' : ''}`} onClick={() => setView(n.id)}>
          <span className="glyph">{n.glyph}</span>
          <span>{n.label}</span>
          {n.id === 'focus' && hot > 0 && <span className="dot-h" />}
        </div>
      ))}

      <div className="side-h">Filas</div>
      <div className="side-item" onClick={() => setView('pipeline')}>
        <span className="glyph">!</span>
        <span>Aguardam resposta</span>
        <span className="count">{waiting}</span>
      </div>
      <div className="side-item" onClick={() => setView('pipeline')}>
        <span className="glyph">★</span>
        <span style={{ color: 'var(--accent-bright)' }}>Quentes</span>
        <span className="count">{hot}</span>
      </div>
      <div className="side-item" onClick={() => setView('lista')}>
        <span className="glyph">+</span>
        <span>Novos hoje</span>
        <span className="count">2</span>
      </div>

      <div className="side-h">Segmentos</div>
      {Object.entries(F.SEGMENTS).map(([k, v]) => (
        <div key={k} className="side-item">
          <span className="glyph">·</span>
          <span>{v.label}</span>
          <span className="count">{leads.filter(l => l.segmento === k).length}</span>
        </div>
      ))}

      <div style={{ flex: 1 }} />
      <div className="side-h">Sua operação</div>
      <div className={`side-item ${view === 'operacao' ? 'on' : ''}`} onClick={() => setView('operacao')}>
        <span className="glyph">⦿</span>
        <span>{opName || 'Configurações'}</span>
      </div>
    </div>
  );
}

// ============ FEED (DASHBOARD) ============
function Feed({ leads, onSelectLead, onEnterFocus }) {
  const m = F.metrics();
  const heat = F.heatmapByUf();
  const ufs = Object.entries(heat).sort((a, b) => b[1] - a[1]);
  const maxUf = Math.max(...ufs.map(([, n]) => n));

  // Build event feed across leads
  const events = leads.flatMap(l =>
    l.events.map(e => ({ ...e, lead: l }))
  ).sort((a, b) => new Date(b.t) - new Date(a.t)).slice(0, 12);

  return (
    <div className="feed-page">
      <div className="feed-main">

        <div className="hero-stat">
          <div>
            <div className="hero-big">
              {m.responderam}<span className="accent">/{m.total}</span>
            </div>
            <div className="hero-cap" style={{ marginTop: 8 }}>
              <b>{m.responderam} leads responderam</b> dos {m.total} ativos na sua base. Taxa de resposta da semana subiu 38% versus a anterior.
            </div>
          </div>
          <div className="hero-side">
            <div className="hero-side-row">
              <div className="hero-side-n" style={{ color: 'var(--accent)' }}>{m.interessados}</div>
              <div className="hero-side-l">interessados — aguardam ação sua</div>
            </div>
            <div className="hero-side-row">
              <div className="hero-side-n">{m.reunioes}</div>
              <div className="hero-side-l">reunião marcada esta semana</div>
            </div>
            <div className="hero-side-row">
              <div className="hero-side-n">{m.enviados}</div>
              <div className="hero-side-l">em sequência ativa</div>
            </div>
          </div>
        </div>

        <div className="feed-h">
          <span>Atividade recente</span>
          <span className="mono">tempo real</span>
        </div>

        {events.map((e, i) => {
          const verb = { reply: 'Respondeu', send: 'Enviado', open: 'Abriu', meeting: 'Reunião com', created: 'Importado' }[e.kind] || 'Evento';
          const isReply = e.kind === 'reply';
          return (
            <div key={i} className="entry" onClick={() => onSelectLead(e.lead)}>
              <div className="entry-time">
                <span className="ago">{F.timeAgo(e.t)}</span>
                <span>{e.ch !== '—' ? e.ch.toUpperCase() : ''}</span>
              </div>
              <div className="entry-body">
                <div className="entry-name">{e.lead.nome}</div>
                <div className="entry-meta">
                  <span>{e.lead.cidade} · {e.lead.uf}</span>
                  <span>·</span>
                  <span style={{ color: isReply ? 'var(--accent)' : 'var(--text-muted)' }}>{verb}</span>
                </div>
                <div className={`entry-msg ${isReply ? 'in' : 'out'}`}>
                  {isReply ? '"' + e.txt + '"' : e.txt}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="feed-rail">
        <div className="rail-card">
          <div className="rail-h">Temperatura da base</div>
          <div className="rail-temp">
            <div className="n">{m.taxaInteresse}%</div>
            <div className="l">leads quentes ou em reunião</div>
          </div>
        </div>

        <div className="rail-card">
          <div className="rail-h">Por estado</div>
          <div className="uf-list">
            {ufs.map(([uf, n]) => (
              <div key={uf} className="uf-row">
                <span className="uf">{uf}</span>
                <div className="uf-bar"><div className="uf-bar-fill" style={{ width: (n / maxUf * 100) + '%' }} /></div>
                <span className="n">{n}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="cta-foco">
          <div className="ck">Recomendado agora</div>
          <div className="ct">Modo Foco</div>
          <div className="cb">{leads.filter(l => l.score >= 75).length} leads quentes aguardam decisão sua. Entre no Modo Foco para decidir em segundos.</div>
          <button onClick={onEnterFocus}>
            <span>Entrar no Modo Foco</span>
            <span className="kbd" style={{ background: 'rgba(5,5,5,0.2)', color: '#F5F5F7', borderColor: 'rgba(5,5,5,0.3)' }}>F</span>
          </button>
        </div>
      </div>
    </div>
  );
}

// ============ FOCUS (HERO of Fluxo) ============
function Focus({ leads, onExit, onUpdate }) {
  const queue = leads
    .filter(l => l.status === 'respondeu' || l.status === 'interessado' || l.status === 'novo')
    .sort((a, b) => b.score - a.score);
  const [idx, setIdx] = uF(0);
  const [history, setHistory] = uF([]);

  const current = queue[idx];

  function decide(d) {
    setHistory([...history, { lead: current, d }]);
    setIdx(i => i + 1);
  }

  eF(() => {
    function k(e) {
      if (['INPUT', 'TEXTAREA'].includes(document.activeElement?.tagName)) return;
      if (e.key === 'ArrowRight' || e.key === 'i') decide('interessado');
      if (e.key === 'ArrowLeft' || e.key === 'x') decide('descartar');
      if (e.key === 'ArrowDown' || e.key === 'f') decide('followup');
      if (e.key === 'Escape') onExit();
    }
    window.addEventListener('keydown', k);
    return () => window.removeEventListener('keydown', k);
  }, [idx, current]);

  if (!current) {
    return (
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 18, padding: 40 }}>
        <div className="display" style={{ fontSize: 84, color: 'var(--accent)', lineHeight: 1 }}>○</div>
        <div className="display" style={{ fontSize: 36 }}>Fila zerada</div>
        <div style={{ color: 'var(--text-dim)', fontSize: 14, textAlign: 'center', maxWidth: 400 }}>
          Você processou {history.length} leads nesta sessão. {history.filter(h => h.d === 'interessado').length} marcados como interessados.
        </div>
        <button className="btn" onClick={onExit}>Voltar ao feed</button>
      </div>
    );
  }

  return (
    <div className="focus-page">
      <div className="focus-stage">
        <div className="focus-progress">
          {queue.map((_, i) => (
            <div key={i} className={`seg ${i < idx ? 'done' : i === idx ? 'cur' : ''}`} />
          ))}
        </div>

        <div className="focus-card">
          <div className="focus-tag">
            <span className="id">{current.id}</span>
            <span>·</span>
            <span>{F.SEGMENTS[current.segmento].label}</span>
            <span>·</span>
            <span>{stOf(current.status).label}</span>
          </div>
          <div className="focus-name">{current.nome}</div>
          <div className="focus-loc">{current.cidade}, {current.uf}</div>
          <div className="focus-contato">
            <b>{current.contato}</b> · {current.cargo}
          </div>

          <div className="focus-row no-border" style={{ borderTop: '1px solid var(--border)', paddingTop: 28 }}>
            <div>
              <div className="focus-block-h">Score de temperatura</div>
              <div className="focus-score">{current.score}<span className="of">/100</span></div>
              <div className="focus-reasons">
                {current.scoreReasons.map((r, i) => <div key={i}>{r}</div>)}
              </div>
            </div>
            <div>
              <div className="focus-block-h">Últimas mensagens</div>
              {current.events.slice(0, 3).map((e, i) => (
                <div key={i} className="last-event">
                  <div className="meta">{e.t.slice(5, 16).replace('T', ' · ')} · {e.ch.toUpperCase()}{e.kind === 'reply' ? ' · resposta' : ''}</div>
                  <div className="txt">{e.txt}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="focus-rail">
        <div className="focus-rail-h">Decidir e avançar</div>
        <button className="focus-action primary" onClick={() => decide('interessado')}>
          <div className="focus-action-head">
            <div className="focus-action-l">Marcar como interessado</div>
            <span className="key">→</span>
          </div>
          <div className="focus-action-sub">Move para "Interessado" e avança</div>
        </button>
        <button className="focus-action" onClick={() => decide('followup')}>
          <div className="focus-action-head">
            <div className="focus-action-l">Follow-up em 3 dias</div>
            <span className="key">↓</span>
          </div>
          <div className="focus-action-sub">Reagenda e avança</div>
        </button>
        <button className="focus-action" onClick={() => decide('descartar')}>
          <div className="focus-action-head">
            <div className="focus-action-l">Descartar lead</div>
            <span className="key">←</span>
          </div>
          <div className="focus-action-sub">Marca não interessado e avança</div>
        </button>

        <div className="focus-rail-h">Sugestão da Sylen</div>
        <div style={{ padding: 14, background: 'var(--accent-soft)', border: '1px solid var(--accent)', borderRadius: 10, fontSize: 12, color: 'var(--accent)', lineHeight: 1.5 }}>
          {current.score >= 75
            ? '→ Enviar proposta agora. Tempo de resposta médio quando o score é >75 cai 4x.'
            : current.score >= 50
            ? '→ Follow-up WPP em 24h. Resposta provável.'
            : '→ Reduzir cadência. Aguardar 3-5d antes de reabrir.'}
        </div>

        <div className="focus-rail-h">Ações rápidas</div>
        <div className="focus-shortcuts">
          <div><span>Abrir conversa</span><span className="k">↵</span></div>
          <div><span>Enviar template</span><span className="k">T</span></div>
          <div><span>Marcar reunião</span><span className="k">M</span></div>
          <div><span>Sair do modo foco</span><span className="k">esc</span></div>
        </div>

        <div style={{ flex: 1 }} />
        <div className="focus-rail-h" style={{ marginTop: 24 }}>Sessão</div>
        <div style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.6 }}>
          <div>{history.length} decisões tomadas</div>
          <div>{queue.length - idx} restantes</div>
          <div className="mono" style={{ marginTop: 6, color: 'var(--text-muted)', fontSize: 10 }}>
            Lead {idx + 1} de {queue.length}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Header, Sidebar, Feed, Focus, scoreCls, stOf, NAV_F });
