﻿// Main app

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#1F93FF",
  "density": "comfortable",
  "showMotivation": true
}/*EDITMODE-END*/;

function buildLeadSummary() {
  const leads = window.LEADS || [];
  const hotCount    = leads.filter(l => l.temp === 'hot').length;
  const activeCount = leads.filter(l => !ARCHIVED_COLS.has(l.col) && l.col !== 'fechado').length;
  return { total: leads.length, hotCount, activeCount };
}

function App() {
  const [active, setActive] = React.useState('dashboard');
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [summary, setSummary] = React.useState(() => buildLeadSummary());

  React.useEffect(() => {
    const handler = () => setSummary(buildLeadSummary());
    window.addEventListener('horos:lead-created', handler);
    return () => window.removeEventListener('horos:lead-created', handler);
  }, []);

  // Theme: persist to localStorage; default = light
  const [theme, setTheme] = React.useState(() => {
    try { return localStorage.getItem('horos-theme') || 'light'; }
    catch { return 'light'; }
  });
  React.useEffect(() => {
    document.documentElement.dataset.theme = theme;
    try { localStorage.setItem('horos-theme', theme); } catch {}
  }, [theme]);

  // Map accent to CSS vars
  React.useEffect(() => {
    const root = document.documentElement;
    const accent = t.accent;
    root.style.setProperty('--accent', accent);
    root.style.setProperty('--accent-soft', shade(accent, 60));
    root.style.setProperty('--accent-glow', hexA(accent, 0.35));
  }, [t.accent]);

  const greeting = () => {
    const h = new Date().getHours();
    if (h < 12) return 'Bom dia';
    if (h < 18) return 'Boa tarde';
    return 'Boa noite';
  };

  const [userName, setUserName] = React.useState('');

  React.useEffect(() => {
    const u = window.HOROS_USER;
    if (!u) return;
    const sb = window.HOROS_SB;
    if (!sb) return;
    sb.from('profiles').select('nome').eq('id', u.id).single()
      .then(({ data }) => {
        if (data?.nome) setUserName(data.nome);
        else {
          const meta = u.user_metadata || {};
          setUserName(meta.nome || u.email?.split('@')[0] || '');
        }
      });
  }, []);

  return (
    <div className={`app density-${t.density}`}>
      <Sidebar active={active} onNav={setActive} />

      <div className="main">
        <Topbar theme={theme} onThemeChange={setTheme} />

        <div className="content">
          <div className="page-head">
            <div>
              <h1 className="page-title">
                <span className="greeting">{greeting()}{userName ? `, ${userName}` : ''}</span>
                <span className="date">· {new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: '2-digit', month: 'long' })}</span>
              </h1>
              <p className="page-sub">
                {summary.total === 0
                  ? <>Bem-vindo ao Horos! <button onClick={() => window.dispatchEvent(new CustomEvent('horos:new-lead'))} style={{ background:'none', border:'none', color:'var(--accent)', cursor:'pointer', fontSize:'inherit', fontWeight:600, padding:0, textDecoration:'underline' }}>Crie seu primeiro lead</button> para começar.</>
                  : summary.hotCount > 0
                  ? <>Você tem <b>{summary.hotCount} lead{summary.hotCount !== 1 ? 's' : ''} quente{summary.hotCount !== 1 ? 's' : ''}</b> e {summary.activeCount} conversa{summary.activeCount !== 1 ? 's' : ''} ativa{summary.activeCount !== 1 ? 's' : ''}.</>
                  : <>Você tem <b>{summary.activeCount} lead{summary.activeCount !== 1 ? 's' : ''} ativo{summary.activeCount !== 1 ? 's' : ''}</b> no funil de vendas.</>
                }
              </p>
            </div>

          </div>

          {t.showMotivation !== false && <MotivationStrip />}

          <KPICards />

          <ClientsTable segment="all" />
        </div>
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection title="Aparência">
          <TweakColor label="Cor de destaque" value={t.accent} onChange={(v) => setTweak('accent', v)}
                      options={['#1F93FF', '#007dff', '#10b981', '#f97316', '#ec4899']} />
          <TweakRadio label="Densidade" value={t.density} onChange={(v) => setTweak('density', v)}
                      options={[{ value: 'comfortable', label: 'Confortável' }, { value: 'compact', label: 'Compacta' }]} />
        </TweakSection>

        <TweakSection title="Layout">
          <TweakToggle label="Metas e ranking" value={t.showMotivation !== false} onChange={(v) => setTweak('showMotivation', v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// Color helpers
function hexA(hex, a) {
  const h = hex.replace('#', '');
  const r = parseInt(h.slice(0, 2), 16);
  const g = parseInt(h.slice(2, 4), 16);
  const b = parseInt(h.slice(4, 6), 16);
  return `rgba(${r}, ${g}, ${b}, ${a})`;
}
function shade(hex, amount) {
  // lighten by amount (0..100)
  const h = hex.replace('#', '');
  const r = Math.min(255, parseInt(h.slice(0, 2), 16) + amount);
  const g = Math.min(255, parseInt(h.slice(2, 4), 16) + amount);
  const b = Math.min(255, parseInt(h.slice(4, 6), 16) + amount);
  return `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`;
}

(async () => {
  if (window.DB_PROMISE) await window.DB_PROMISE;
  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(<App />);
})();
