/* global React, ReactDOM, Sidebar, Topbar, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakToggle, TweakSlider, Login, supa */
const { useState, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#d4f752",
  "density": "regular",
  "theme": "dark",
  "showTicker": true,
  "highlightCritical": true,
  "fontSize": 13
}/*EDITMODE-END*/;

function deriveUserInfo(session) {
  const u = session?.user;
  if (!u) return null;
  const email = u.email || '';
  const fullName = u.user_metadata?.full_name;
  const fromEmail = email ? email.split('@')[0].replace(/[._-]/g, ' ').replace(/\b\w/g, c => c.toUpperCase()) : '';
  // Prioridade: full_name (se tiver sobrenome) > derivado do email > metadata.name > fallback
  const displayName = (fullName && fullName.trim().includes(' ')) ? fullName : (fromEmail || u.user_metadata?.name || 'Usuário');
  const parts = displayName.split(' ').filter(Boolean);
  const initials = ((parts[0]?.[0] || '') + (parts.length > 1 ? parts[parts.length - 1]?.[0] || '' : '')).toUpperCase() || 'U';
  return { id: u.id, email, displayName, initials, role: u.user_metadata?.role || 'Usuário' };
}

function App() {
  const [active, setActive] = useState('dashboard');
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [session, setSession] = useState(null);
  const [bootstrapping, setBootstrapping] = useState(true);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  const userInfo = deriveUserInfo(session);
  window.sglUser = userInfo;

  // Reflete estado do drawer mobile no body (controla CSS)
  useEffect(() => {
    document.body.classList.toggle('sidebar-open', mobileMenuOpen);
    return () => document.body.classList.remove('sidebar-open');
  }, [mobileMenuOpen]);

  // Navegação que também fecha o drawer mobile
  const navigate = (id) => {
    setActive(id);
    setMobileMenuOpen(false);
  };

  useEffect(() => {
    let mounted = true;
    window.supa.auth.getSession().then(({ data }) => {
      if (!mounted) return;
      setSession(data.session || null);
      setBootstrapping(false);
    }).catch(() => {
      if (!mounted) return;
      setBootstrapping(false);
    });
    const { data: listener } = window.supa.auth.onAuthStateChange((_event, newSession) => {
      setSession(newSession || null);
    });
    return () => {
      mounted = false;
      listener?.subscription?.unsubscribe?.();
    };
  }, []);

  const handleLogin = (data) => {
    setSession(data.session || null);
  };

  const handleLogout = async () => {
    try { await window.supa.auth.signOut(); } catch {}
    setSession(null);
    setActive('dashboard');
  };

  // Apply tweaks to CSS variables
  useEffect(() => {
    const r = document.documentElement;
    r.style.setProperty('--lime', t.accent);
    // derive softer variants
    r.style.setProperty('--lime-soft', t.accent + '14');
    r.style.setProperty('--lime-border', t.accent + '4d');
    r.style.setProperty('--row-pad', t.density === 'compact' ? '6px 10px' : t.density === 'comfy' ? '14px 14px' : '10px 12px');
    r.style.setProperty('--base-fs', t.fontSize + 'px');
    document.body.classList.toggle('theme-light', t.theme === 'light');
    document.body.classList.toggle('hide-ticker', !t.showTicker);
    document.body.classList.toggle('no-crit-highlight', !t.highlightCritical);
  }, [t]);

  const renderModule = () => {
    switch (active) {
      case 'dashboard': return <MDashboard onNav={navigate} />;
      case 'prospeccao': return <MProspeccao onNav={navigate} />;
      case 'ocr': return <MOcr onNav={navigate} />;
      case 'precificacao': return <MPrecificacao onNav={navigate} />;
      case 'disputa': return <MDisputa onNav={navigate} />;
      case 'empenhos': return <MEmpenhos onNav={navigate} />;
      case 'logistica': return <MLogistica onNav={navigate} />;
      case 'financeiro': return <MFinanceiro onNav={navigate} />;
      case 'ia': return <MIa onNav={navigate} />;
      case 'integracoes': return <MGoogle onNav={navigate} />;
      case 'portais': return <MPortais onNav={navigate} />;
      case 'pdv': return <MPdv onNav={navigate} />;
      case 'auditoria': return <MAuditoria onNav={navigate} />;
      case 'config': return <MConfig onNav={navigate} />;
      default: return <MDashboard onNav={navigate} />;
    }
  };

  if (bootstrapping) {
    return (
      <div style={{ position: 'fixed', inset: 0, display: 'grid', placeItems: 'center', background: 'var(--bg-0)', color: 'var(--fg-3)', fontFamily: 'IBM Plex Mono, monospace', fontSize: 12, letterSpacing: '0.08em' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <span className="spinner"></span>
          <span>VERIFICANDO SESSÃO...</span>
        </div>
      </div>
    );
  }

  if (!session) {
    return <Login onLogin={handleLogin} />;
  }

  return (
    <div className="app">
      <Sidebar active={active} onNav={navigate} onLogout={handleLogout} user={userInfo} />
      <div className="mobile-sidebar-backdrop" onClick={() => setMobileMenuOpen(false)}></div>
      <main className="main">
        <Topbar moduleId={active} onNav={navigate} onMenuClick={() => setMobileMenuOpen(v => !v)} />
        <div className="main-body" data-screen-label={active}>
          {renderModule()}
        </div>
      </main>
      <TweaksPanel>
        <TweakSection label="Aparência" />
        <TweakRadio label="Tema" value={t.theme} options={['dark', 'light']} onChange={v => setTweak('theme', v)} />
        <TweakRadio label="Densidade" value={t.density} options={['compact', 'regular', 'comfy']} onChange={v => setTweak('density', v)} />
        <TweakSlider label="Tamanho fonte" value={t.fontSize} min={11} max={15} unit="px" onChange={v => setTweak('fontSize', v)} />
        <TweakColor label="Cor de destaque" value={t.accent} options={['#d4f752', '#6ad7e5', '#ffb020', '#ff5d5d', '#b794f4']} onChange={v => setTweak('accent', v)} />
        <TweakSection label="Comportamento" />
        <TweakToggle label="Ticker de eventos" value={t.showTicker} onChange={v => setTweak('showTicker', v)} />
        <TweakToggle label="Destacar críticos" value={t.highlightCritical} onChange={v => setTweak('highlightCritical', v)} />
      </TweaksPanel>
    </div>
  );
}

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