// SylenProspec — FLUXO entry
const { useState: uFE, useEffect: eFE } = React;

// ============ AUTH SCREEN ============
function AuthScreen({ onAuth }) {
  const [tab, setTab] = uFE('login'); // 'login' | 'signup'
  const [email, setEmail] = uFE('');
  const [password, setPassword] = uFE('');
  const [loading, setLoading] = uFE(false);
  const [error, setError] = uFE('');
  const [shake, setShake] = uFE(false);

  async function handle(e) {
    e.preventDefault();
    if (!email || !password) return;
    setLoading(true); setError('');
    try {
      if (tab === 'login') {
        await window.SYLEN_API.signIn(email, password);
      } else {
        await window.SYLEN_API.signUp(email, password);
      }
      onAuth();
    } catch (err) {
      setError(err.message);
      setShake(true);
      setTimeout(() => setShake(false), 500);
    }
    setLoading(false);
  }

  const inp = {
    width: '100%', padding: '10px 14px', background: 'var(--bg-3)',
    border: `1px solid ${error ? '#a83232' : 'var(--border-2)'}`,
    borderRadius: 10, color: 'var(--text)', fontSize: 14, outline: 'none',
    fontFamily: 'var(--font-body)', boxSizing: 'border-box',
  };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg)', fontFamily: 'var(--font-body)' }}>
      <div style={{ width: 360, padding: '2.5rem', background: 'var(--bg-2)', border: '1px solid var(--border)', borderRadius: 20 }}
           className={shake ? 'login-shake' : ''}>

        {/* Brand */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: '2rem' }}>
          <img src="shared/sylen-mark.png" alt="SYLEN" style={{ width: 34, height: 34 }} />
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 19, color: 'var(--text)' }}>SYLEN AI</div>
            <div style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>CRM de prospecção</div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: 'flex', gap: 0, marginBottom: '1.5rem', background: 'var(--bg-3)', borderRadius: 10, padding: 4 }}>
          {[{ id: 'login', label: 'Entrar' }, { id: 'signup', label: 'Criar conta' }].map(t => (
            <button key={t.id} onClick={() => { setTab(t.id); setError(''); }}
              style={{ flex: 1, padding: '8px', borderRadius: 8, border: 'none', cursor: 'pointer', fontSize: 13, fontWeight: 600, fontFamily: 'var(--font-body)',
                background: tab === t.id ? 'var(--bg-2)' : 'transparent',
                color: tab === t.id ? 'var(--text)' : 'var(--text-muted)',
                boxShadow: tab === t.id ? '0 1px 4px rgba(0,0,0,0.08)' : 'none',
              }}>
              {t.label}
            </button>
          ))}
        </div>

        <form onSubmit={handle}>
          <div style={{ marginBottom: 12 }}>
            <label style={{ display: 'block', fontSize: 11, color: 'var(--text-muted)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)' }}>
              E-mail
            </label>
            <input type="email" autoFocus required style={inp} value={email}
              onChange={e => { setEmail(e.target.value); setError(''); }}
              placeholder="seu@email.com" />
          </div>

          <div style={{ marginBottom: '1.25rem' }}>
            <label style={{ display: 'block', fontSize: 11, color: 'var(--text-muted)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.08em', fontFamily: 'var(--font-mono)' }}>
              Senha
            </label>
            <input type="password" required style={inp} value={password}
              onChange={e => { setPassword(e.target.value); setError(''); }}
              placeholder="••••••••" minLength={6} />
          </div>

          {error && (
            <div style={{ fontSize: 12, color: '#a83232', marginBottom: 12, padding: '8px 12px', background: 'rgba(168,50,50,0.08)', borderRadius: 8 }}>
              {error}
            </div>
          )}

          <button type="submit" disabled={loading} className="btn btn-primary"
            style={{ width: '100%', padding: '11px', fontSize: 14, opacity: loading ? 0.7 : 1 }}>
            {loading ? 'Aguarde…' : tab === 'login' ? 'Entrar' : 'Criar conta'}
          </button>
        </form>
      </div>
      <style>{`.login-shake{animation:shake 0.4s}@keyframes shake{0%,100%{transform:translateX(0)}20%,60%{transform:translateX(-8px)}40%,80%{transform:translateX(8px)}}`}</style>
    </div>
  );
}

function AppFluxo() {
  const [view, setView] = uFE('feed');
  const [leads, setLeads] = uFE(window.SYLEN_DATA.LEADS);
  const [selectedLead, setSelectedLead] = uFE(null);
  const [cpOpen, setCpOpen] = uFE(false);
  const [config, setConfig] = uFE(window.SYLEN_DATA.loadConfig());
  const [leadsLoading, setLeadsLoading] = uFE(false);
  const [showNewLead, setShowNewLead] = uFE(false);

  const isLive = !!(config.integrations?.supabaseUrl && config.integrations?.supabaseAnonKey);
  const connStatus = isLive ? 'live' : 'demo';
  const liveKey = isLive ? config.integrations.supabaseUrl + '::' + config.integrations.supabaseAnonKey : '';

  // Carrega leads do Supabase quando configurado + polling a cada 30s
  eFE(() => {
    if (!liveKey) return;
    let cancelled = false;
    async function pull() {
      setLeadsLoading(true);
      const rows = await window.SYLEN_API.loadLeads(config);
      if (!cancelled) {
        if (rows) setLeads(rows);
        setLeadsLoading(false);
      }
    }
    pull();
    const t = setInterval(pull, 30000);
    return () => { cancelled = true; clearInterval(t); };
  }, [liveKey]);

  // Atalhos de teclado
  eFE(() => {
    function onKey(e) {
      const inInput = ['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement?.tagName);
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault(); setCpOpen(true); return;
      }
      if (inInput) return;
      if (e.key === '/') { e.preventDefault(); setCpOpen(true); return; }
      if (e.key === 'f' || e.key === 'F') setView('focus');
      if (e.key === '1') setView('feed');
      if (e.key === '2') setView('focus');
      if (e.key === '3') setView('campanhas');
      if (e.key === '4') setView('pipeline');
      if (e.key === '5') setView('composer');
      if (e.key === '6') setView('templates');
      if (e.key === '7') setView('lista');
      if (e.key === ',') setView('operacao');
      if (e.key === 'Escape') { setSelectedLead(null); setCpOpen(false); }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  function handleCmd(act) {
    if (act.t === 'nav') setView(act.v);
    if (act.t === 'lead') setSelectedLead(act.lead);
  }

  function handleConfigSave(c) {
    setConfig(c);
    // Se acabou de configurar Supabase, carrega imediatamente
    const nowLive = !!(c.integrations?.supabaseUrl && c.integrations?.supabaseAnonKey);
    if (nowLive) {
      setLeadsLoading(true);
      window.SYLEN_API.loadLeads(c).then(rows => {
        if (rows) setLeads(rows);
        setLeadsLoading(false);
      });
    }
  }

  const heads = {
    feed:      { title: 'Hoje na sua operação', sub: 'Atividade dos últimos 3 dias · feed em tempo real' },
    focus:     { title: 'Modo Foco', sub: 'Decida um lead por vez. Use as setas.' },
    campanhas: { title: 'Campanhas', sub: 'Defina destino, período e categoria · busca SerpAPI popula a base' },
    pipeline:  { title: 'Pipeline', sub: 'Arraste para mudar de estágio. Cards mostram a última conversa.' },
    composer:  { title: 'Disparo', sub: 'Cadência multicanal → audiência por segmento → preview ao vivo' },
    templates: { title: 'Templates', sub: 'Crie e edite mensagens reaproveitáveis com variáveis' },
    lista:     { title: 'Todos os leads', sub: leads.length + ' leads · filtros e busca' },
    operacao:  { title: 'Operação', sub: 'Configure o SylenProspec pro seu negócio' },
  };
  const h = heads[view] || heads.feed;

  return (
    <div className="app">
      <Header onCmdK={() => setCpOpen(true)} status={connStatus} />
      <Sidebar view={view} setView={setView} leads={leads} opName={config.operationName} />

      <div className="main">
        {view !== 'focus' && (
          <div className="ph">
            <div>
              <div className="ph-title">{h.title}</div>
              <div className="ph-sub">
                {h.sub}
                {leadsLoading && (
                  <span className="mono" style={{ marginLeft: 10, color: 'var(--accent)', fontSize: 11 }}>
                    ↻ sincronizando…
                  </span>
                )}
              </div>
            </div>
            <div className="ph-act">
              {view === 'feed' && (
                <button className="btn btn-primary" onClick={() => setView('focus')}>◎ Modo Foco</button>
              )}
              {(view === 'pipeline' || view === 'lista') && (
                <button className="btn btn-primary" onClick={() => setShowNewLead(true)}>+ Lead</button>
              )}
              {view === 'lista' && (
                <button className="btn btn-primary" onClick={() => setView('composer')}>▶ Disparar</button>
              )}
              {view === 'feed' && (
                <button className="btn" onClick={() => setShowNewLead(true)} style={{ marginRight: 8 }}>+ Lead</button>
              )}
              {view === 'templates' && (
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', alignSelf: 'center' }}>
                  Templates salvam automaticamente
                </span>
              )}
              {view === 'composer' && (
                <span className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', alignSelf: 'center' }}>
                  <span className="kbd">⌘K</span> para comandos
                </span>
              )}
            </div>
          </div>
        )}

        {view === 'feed'      && <Feed      leads={leads} onSelectLead={setSelectedLead} onEnterFocus={() => setView('focus')} />}
        {view === 'focus'     && <Focus     leads={leads} onExit={() => setView('feed')} onUpdate={setLeads} />}
        {view === 'pipeline'  && <River     leads={leads} setLeads={setLeads} onSelectLead={setSelectedLead} config={config} />}
        {view === 'composer'  && <Composer  leads={leads} onSelectLead={setSelectedLead} config={config} />}
        {view === 'templates' && <Templates leads={leads} />}
        {view === 'campanhas' && <Campanhas onSelectAudience={() => setView('composer')} config={config} onNewLeads={(rows) => setLeads(prev => {
          const ids = new Set(prev.map(l => l.id));
          const merged = [...prev];
          rows.forEach(r => { if (!ids.has(r.id)) merged.unshift(r); });
          return merged;
        })} />}
        {view === 'lista'     && <ListaF    leads={leads} onSelectLead={setSelectedLead} />}
        {view === 'operacao'  && <Operacao  config={config} setConfig={handleConfigSave} />}
      </div>

      <DetailF
        lead={selectedLead}
        onClose={() => setSelectedLead(null)}
        onDelete={(l) => {
          setLeads(prev => prev.filter(x => x.id !== l.id));
          setSelectedLead(null);
          window.SYLEN_API.deleteLead(config, l.id);
        }}
        onMarkLost={(l) => {
          setLeads(prev => prev.map(x => x.id === l.id ? { ...x, status: 'perdido' } : x));
          window.SYLEN_API.updateLeadStatus(config, l.id, 'perdido');
        }}
      />
      {showNewLead && (
        <NewLeadModal
          onClose={() => setShowNewLead(false)}
          onSave={async (fields) => {
            const lead = await window.SYLEN_API.createLead(config, fields);
            setLeads(prev => [lead, ...prev]);
          }}
        />
      )}
      <CmdP open={cpOpen} onClose={() => setCpOpen(false)} onAction={handleCmd} />
    </div>
  );
}

function Root() {
  const [authed, setAuthed] = uFE(() => !!window.SYLEN_API.getSession());
  if (!authed) return <AuthScreen onAuth={() => setAuthed(true)} />;
  return <AppFluxo />;
}

ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
