/* global React, ReactDOM,
   Sidebar, Topbar,
   Dashboard,
   CRMClientes, CRMSaloes, CRMDistribuidores, CRMRepresentantes,
   MensagensInbox, MensagensConversas, MensagensCanais,
   IAComercial, IASac, IAInterna,
   ProdutosLista, ProdutosLinhas, ProdutosCategorias, ProdutosTabelasPreco, ProdutosEstoque,
   PedidosAbertos, PedidosFaturados, PedidosCancelados, CriarPedido,
   PDV,
   ContasReceber, ContasPagar, Entradas, Saidas, FluxoCaixa, ExtratoConsolidado,
   Kanban, Agenda,
   NFEmissao, NFHistorico, NFImportarXml, NFLogs,
   Formularios, FormLeads,
   RelVendas, RelDistribuidores, RelClientes, RelFinanceiro, RelInsights, RelProdutos, RelExecutivo,
   ConfigPage,
   useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakColor
*/
const { useState: useAppState, useEffect: useAppEffect } = React;

// ─── Login / Setup screen ──────────────────────────────────────
const SUPABASE_FN_URL_APP = 'https://ilgxpxfdrhshitkozlqs.supabase.co/functions/v1';

function LoginScreen() {
  const [mode, setMode]   = React.useState('checking'); // 'checking' | 'login' | 'setup'

  // On mount: check if any auth-linked admin exists. If none → go straight to setup.
  React.useEffect(() => {
    if (!window.tmSupabase) { setMode('login'); return; }
    window.tmSupabase
      .from('usuarios')
      .select('id', { count: 'exact', head: true })
      .not('auth_user_id', 'is', null)
      .eq('perfil', 'Administrador')
      .then(({ count }) => setMode((count || 0) === 0 ? 'setup' : 'login'));
  }, []);

  if (mode === 'checking') return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--tm-bg-0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ textAlign: 'center', color: 'var(--tm-fg-3)', fontSize: 13 }}>Verificando configuração…</div>
    </div>
  );

  return mode === 'setup'
    ? <SetupAdmin onDone={() => setMode('login')} />
    : <LoginForm onSetup={() => setMode('setup')} />;
}

function LoginBrand() {
  return (
    <div style={{ textAlign: 'center', marginBottom: 32 }}>
      <div style={{ fontFamily: 'var(--tm-font-display)', fontSize: 30, color: 'var(--tm-brand-champagne)', letterSpacing: '0.06em' }}>TopMix</div>
      <div style={{ fontSize: 10.5, letterSpacing: '0.24em', color: 'var(--tm-fg-3)', marginTop: 4, textTransform: 'uppercase' }}>ProHub</div>
    </div>
  );
}

function PwdInput({ value, onChange, placeholder }) {
  const [show, setShow] = React.useState(false);
  return (
    <div style={{ position: 'relative' }}>
      <input className="input" type={show ? 'text' : 'password'}
        value={value} onChange={e => onChange(e.target.value)}
        placeholder={placeholder || '••••••••'} style={{ paddingRight: 40 }} />
      <button type="button" className="icon-btn"
        style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)' }}
        onClick={() => setShow(v => !v)}>
        <Icon name={show ? 'eye-off' : 'eye'} size={14} />
      </button>
    </div>
  );
}

function LoginForm({ onSetup }) {
  const [email, setEmail] = React.useState('');
  const [pwd, setPwd]     = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]     = React.useState('');

  const submit = async () => {
    if (!email || !pwd) { setErr('Preencha e-mail e senha.'); return; }
    setLoading(true); setErr('');
    const { error } = await window.tmSignIn(email, pwd);
    if (error) { setErr('E-mail ou senha incorretos. Tente novamente.'); setLoading(false); }
  };
  const onKey = (e) => { if (e.key === 'Enter') submit(); };

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--tm-bg-0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ width: 380 }}>
        <LoginBrand />
        <div style={{ background: 'var(--tm-bg-1)', borderRadius: 12, padding: '28px 28px 24px', border: '1px solid var(--tm-line-1)' }}>
          <div style={{ fontFamily: 'var(--tm-font-display)', fontSize: 20, marginBottom: 4 }}>Entrar na sua conta</div>
          <div className="muted" style={{ fontSize: 12.5, marginBottom: 22 }}>Use as credenciais fornecidas pelo administrador.</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div className="field">
              <label>E-mail</label>
              <input className="input" type="email" autoFocus value={email}
                onChange={e => setEmail(e.target.value)} onKeyDown={onKey} placeholder="seu@email.com.br" />
            </div>
            <div className="field">
              <label>Senha</label>
              <PwdInput value={pwd} onChange={setPwd} />
            </div>
            {err && <div style={{ fontSize: 12.5, padding: '8px 12px', borderRadius: 6, background: 'rgba(239,68,68,0.12)', color: 'var(--tm-danger)' }}>{err}</div>}
            <Button variant="primary" size="lg" style={{ width: '100%', marginTop: 4 }} onClick={submit} disabled={loading}>
              {loading ? 'Entrando…' : 'Entrar'}
            </Button>
          </div>
        </div>
        <div style={{ textAlign: 'center', marginTop: 18 }}>
          <button onClick={onSetup}
            style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 12.5, color: 'var(--tm-brand-champagne)', textDecoration: 'underline', textDecorationStyle: 'dotted', textUnderlineOffset: 3 }}>
            Criar conta de administrador
          </button>
        </div>
        <div className="muted" style={{ textAlign: 'center', fontSize: 11, marginTop: 12 }}>
          TopMix ProHub · ERP &amp; CRM para Cosméticos
        </div>
      </div>
    </div>
  );
}

function SetupAdmin({ onDone }) {
  const [nome, setNome]       = React.useState('');
  const [email, setEmail]     = React.useState('');
  const [pwd, setPwd]         = React.useState('');
  const [pwd2, setPwd2]       = React.useState('');
  const [cargo, setCargo]     = React.useState('Administrador');
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]         = React.useState('');
  const [done, setDone]       = React.useState(false);

  const submit = async () => {
    if (!nome.trim() || !email.trim() || !pwd) { setErr('Preencha todos os campos obrigatórios.'); return; }
    if (pwd.length < 6) { setErr('A senha deve ter pelo menos 6 caracteres.'); return; }
    if (pwd !== pwd2) { setErr('As senhas não coincidem.'); return; }
    setLoading(true); setErr('');
    try {
      const res = await fetch(`${SUPABASE_FN_URL_APP}/create-user`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${window.tmAnonKey || ''}` },
        body: JSON.stringify({ nome, email, password: pwd, cargo, perfil: 'Administrador' }),
      });
      const result = await res.json();
      if (result.error) throw new Error(result.error);
      // Auto-login after creation
      const { error: loginErr } = await window.tmSignIn(email, pwd);
      if (loginErr) { setDone(true); } // creation ok but login failed — show success msg
    } catch (e) {
      setErr(e.message);
    }
    setLoading(false);
  };

  if (done) return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--tm-bg-0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ width: 380, textAlign: 'center' }}>
        <LoginBrand />
        <div style={{ background: 'var(--tm-bg-1)', borderRadius: 12, padding: 32, border: '1px solid var(--tm-line-1)' }}>
          <Icon name="check-circle" size={40} style={{ color: 'var(--tm-success)' }} />
          <div style={{ fontFamily: 'var(--tm-font-display)', fontSize: 20, marginTop: 16 }}>Conta criada!</div>
          <div className="muted" style={{ fontSize: 13, marginTop: 8 }}>Faça login com seu e-mail e senha.</div>
          <Button variant="primary" style={{ marginTop: 20 }} onClick={onDone}>Ir para o login</Button>
        </div>
      </div>
    </div>
  );

  return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--tm-bg-0)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflowY: 'auto' }}>
      <div style={{ width: 420, padding: '32px 0' }}>
        <LoginBrand />
        <div style={{ background: 'var(--tm-bg-1)', borderRadius: 12, padding: '28px 28px 24px', border: '1px solid var(--tm-line-1)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: 'color-mix(in srgb, var(--tm-brand-champagne) 18%, transparent)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon name="shield-check" size={16} style={{ color: 'var(--tm-brand-champagne)' }} />
            </div>
            <div style={{ fontFamily: 'var(--tm-font-display)', fontSize: 20 }}>Criar conta de administrador</div>
          </div>
          <div className="muted" style={{ fontSize: 12.5, marginBottom: 22, marginLeft: 42 }}>
            Esse será o usuário principal com acesso total ao sistema.
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div className="field">
              <label>Nome completo <span style={{ color: 'var(--tm-danger)' }}>*</span></label>
              <input className="input" type="text" autoFocus value={nome}
                onChange={e => setNome(e.target.value)} placeholder="Ex: Maria Silva" />
            </div>
            <div className="field">
              <label>E-mail de acesso <span style={{ color: 'var(--tm-danger)' }}>*</span></label>
              <input className="input" type="email" value={email}
                onChange={e => setEmail(e.target.value)} placeholder="maria@topmix.com.br" />
            </div>
            <div className="field">
              <label>Cargo / Função</label>
              <input className="input" type="text" value={cargo}
                onChange={e => setCargo(e.target.value)} placeholder="Ex: Administrador, CEO, Gerente…" />
            </div>
            <div className="field">
              <label>Senha <span style={{ color: 'var(--tm-danger)' }}>*</span></label>
              <PwdInput value={pwd} onChange={setPwd} placeholder="Mínimo 6 caracteres" />
            </div>
            <div className="field">
              <label>Confirmar senha <span style={{ color: 'var(--tm-danger)' }}>*</span></label>
              <PwdInput value={pwd2} onChange={setPwd2} placeholder="Repita a senha" />
            </div>

            {err && <div style={{ fontSize: 12.5, padding: '8px 12px', borderRadius: 6, background: 'rgba(239,68,68,0.12)', color: 'var(--tm-danger)' }}>{err}</div>}

            <Button variant="primary" size="lg" style={{ width: '100%', marginTop: 4 }} onClick={submit} disabled={loading}>
              {loading ? 'Criando conta…' : 'Criar minha conta e entrar'}
            </Button>
          </div>
        </div>

        <div style={{ textAlign: 'center', marginTop: 18 }}>
          <button onClick={onDone}
            style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 12.5, color: 'var(--tm-fg-3)' }}>
            ← Já tenho uma conta
          </button>
        </div>
      </div>
    </div>
  );
}

// Tweakable defaults — three expressive dials that reshape the feel of the app.
// Keep this block as the ONLY EDITMODE block in this file; the host parses it as JSON.
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "champanhe",
  "display": "editorial",
  "density": "compacto"
}/*EDITMODE-END*/;

// Palette table — each entry has a dark-surface shade (used when theme=dark),
// a light-surface shade (used when theme=light), and soft/deep variants. The
// effect picks the right shade based on the current theme so the accent stays
// readable on either background.
const PALETTES = {
  champanhe: { label: "Champanhe",  dark: "#E8B547", light: "#8E6B3A", soft: "#F4CE7A", deep: "#B8862A" },
  rose:      { label: "Rosé",       dark: "#D49494", light: "#9A4949", soft: "#E8B5B5", deep: "#6F2E2E" },
  sage:      { label: "Sage",       dark: "#8FB89E", light: "#4D7560", soft: "#B9D6C5", deep: "#36533F" },
  cobalto:   { label: "Cobalto",    dark: "#7F9ECF", light: "#3D5D8E", soft: "#AFC4E2", deep: "#2C4368" },
};

const DISPLAY_FONTS = {
  editorial:  { label: "Editorial",  family: `"Tenor Sans", "Cormorant Garamond", Georgia, serif`, weight: 400, tracking: "0.01em" },
  moderno:    { label: "Moderno",    family: `"Inter", -apple-system, system-ui, sans-serif`,     weight: 600, tracking: "-0.02em" },
  boutique:   { label: "Boutique",   family: `"Playfair Display", "Cormorant Garamond", serif`,    weight: 500, tracking: "-0.01em" },
  industrial: { label: "Industrial", family: `"Space Grotesk", "Inter", sans-serif`,                weight: 500, tracking: "-0.01em" },
};

function App() {
  // ── Auth ──────────────────────────────────────────────────────
  const [sessionLoading, setSessionLoading] = useAppState(true);
  const [authUser, setAuthUser] = useAppState(null);
  const [profile, setProfile] = useAppState(null);

  useAppEffect(() => {
    if (!window.tmSupabase) { setSessionLoading(false); return; }

    const loadProfile = async (user) => {
      if (!user) return;
      const { data } = await window.tmSupabase
        .from('usuarios').select('*').eq('auth_user_id', user.id).single();

      let permissoes = null;
      if (data?.perfil_id) {
        const { data: pd } = await window.tmSupabase
          .from('perfis_acesso').select('permissoes').eq('id', data.perfil_id).single();
        permissoes = pd?.permissoes ?? null;
      }

      const fullProfile = data ? { ...data, _permissoes: permissoes } : null;
      setProfile(fullProfile);
      window.tmUserProfile = data || null;
      window.tmPermissoes  = permissoes;

      if (data) window.tmSupabase.from('usuarios')
        .update({ ultimo_acesso: new Date().toISOString() }).eq('id', data.id).then(() => {});
    };

    window.tmSupabase.auth.getSession().then(({ data: { session } }) => {
      window.tmSession = session;
      window.tmUser = session?.user ?? null;
      setAuthUser(session?.user ?? null);
      setSessionLoading(false);
      if (session?.user) loadProfile(session.user);
    });

    const { data: { subscription } } = window.tmSupabase.auth.onAuthStateChange(
      (event, session) => {
        window.tmSession = session;
        window.tmUser = session?.user ?? null;
        setAuthUser(session?.user ?? null);
        if (!session) { setProfile(null); window.tmUserProfile = null; }
        else loadProfile(session.user);
      }
    );
    return () => subscription.unsubscribe();
  }, []);

  // ── Global profile refresh (PerfilContent chama após salvar avatar/nome) ──
  useAppEffect(() => {
    window.tmReloadProfile = async () => {
      if (!window.tmUser || !window.tmSupabase) return;
      const { data } = await window.tmSupabase
        .from('usuarios').select('*').eq('auth_user_id', window.tmUser.id).single();
      let permissoes = null;
      if (data?.perfil_id) {
        const { data: pd } = await window.tmSupabase
          .from('perfis_acesso').select('permissoes').eq('id', data.perfil_id).single();
        permissoes = pd?.permissoes ?? null;
      }
      const full = data ? { ...data, _permissoes: permissoes } : null;
      setProfile(full);
      window.tmUserProfile = data || null;
      window.tmPermissoes  = permissoes;
    };
    return () => { delete window.tmReloadProfile; };
  }, []);

  // ── Empresas ──────────────────────────────────────────────────
  const [empresas, setEmpresas]         = useAppState([]);
  const [empresaAtual, setEmpresaAtual] = useAppState(null);

  useAppEffect(() => {
    if (!authUser || !window.tmSupabase) return;
    const load = async () => {
      const { data } = await window.tmSupabase
        .from('empresas')
        .select('*')
        .eq('ativo', true)
        .order('principal', { ascending: false })
        .order('nome_fantasia');
      if (data) {
        setEmpresas(data);
        window.tmEmpresas = data;
        // Se ainda não há empresa selecionada, pré-seleciona a principal
        setEmpresaAtual(prev => {
          if (!data || data.length === 0) return null;
          if (!prev) {
            const principal = data.find(e => e.principal);
            return principal || null;
          }
          // Refresh data for the currently selected company (picks up new logo_url etc.)
          return data.find(e => e.id === prev.id) || prev;
        });
      }
    };
    load();
    window.tmReloadEmpresas = load;
    return () => { delete window.tmReloadEmpresas; };
  }, [authUser]);

  // Mantém os globals de empresa sincronizados com o estado React
  useAppEffect(() => {
    window.tmEmpresa   = empresaAtual;
    window.tmEmpresaId = empresaAtual?.id ?? null;
  }, [empresaAtual]);

  // ── Theme — single source of truth, also synced to localStorage + dataset
  const [theme, setTheme] = useAppState(() => {
    try { return localStorage.getItem("tm-theme") || "dark"; } catch (e) { return "dark"; }
  });
  useAppEffect(() => {
    document.documentElement.dataset.theme = theme;
    try { localStorage.setItem("tm-theme", theme); } catch (e) {}
  }, [theme]);

  // Tweaks
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks → CSS custom properties + dataset attrs whenever any of
  // (tweaks, theme) changes.
  useAppEffect(() => {
    const root = document.documentElement;
    const pal = PALETTES[t.palette] || PALETTES.champanhe;
    const main = theme === "light" ? pal.light : pal.dark;
    const soft = theme === "light" ? pal.dark : pal.soft;
    root.style.setProperty("--tm-brand-champagne", main);
    root.style.setProperty("--tm-brand-champagne-soft", soft);
    root.style.setProperty("--tm-brand-champagne-deep", pal.deep);
    root.style.setProperty("--tm-ring-focus", `0 0 0 2px ${main}59`);

    const font = DISPLAY_FONTS[t.display] || DISPLAY_FONTS.editorial;
    root.style.setProperty("--tm-font-display", font.family);
    root.style.setProperty("--tm-display-weight", String(font.weight));
    root.style.setProperty("--tm-display-tracking", font.tracking);

    root.dataset.density = t.density;
  }, [t.palette, t.display, t.density, theme]);

  const initial = () => {
    const h = window.location.hash.replace("#", "");
    return h || "dashboard";
  };
  const [active, setActive] = useAppState(initial);

  useAppEffect(() => {
    window.location.hash = active;
  }, [active]);

  useAppEffect(() => {
    const onHash = () => setActive(window.location.hash.replace("#", "") || "dashboard");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const onNav = (id) => setActive(id);

  const ROUTE = {
    "dashboard": () => <Dashboard onNav={onNav} profile={profile} empresaAtual={empresaAtual} />,
    "crm": () => <CRMClientes onNav={onNav} empresaAtual={empresaAtual} />,
    "crm/clientes-finais": () => <CRMClientes onNav={onNav} empresaAtual={empresaAtual} />,
    "crm/saloes": () => <CRMSaloes onNav={onNav} empresaAtual={empresaAtual} />,
    "crm/distribuidores": () => <CRMDistribuidores onNav={onNav} empresaAtual={empresaAtual} />,
    "crm/representantes": () => <CRMRepresentantes onNav={onNav} />,
    "mensagens": () => <MensagensInbox />,
    "mensagens/inbox": () => <MensagensInbox />,
    "mensagens/conversas": () => <MensagensConversas />,
    "mensagens/canais": () => <MensagensCanais />,
    "mensagens/agentes": () => <MensagensAgentes />,
    "mensagens/templates": () => <MensagensTemplates />,
    "ia": () => <IAComercial />,
    "ia/comercial": () => <IAComercial />,
    "ia/sac": () => <IASac />,
    "ia/interna": () => <IAInterna />,
    "produtos": () => <ProdutosLista onNav={onNav} empresaAtual={empresaAtual} />,
    "produtos/lista": () => <ProdutosLista onNav={onNav} empresaAtual={empresaAtual} />,
    "produtos/linhas": () => <ProdutosLinhas onNav={onNav} />,
    "produtos/categorias": () => <ProdutosCategorias onNav={onNav} />,
    "produtos/tabelas-preco": () => <ProdutosTabelasPreco onNav={onNav} />,
    "produtos/estoque": () => <ProdutosEstoque onNav={onNav} />,
    "pedidos": () => <PedidosAbertos onNav={onNav} />,
    "pedidos/criar": () => <CriarPedido onNav={onNav} />,
    "pedidos/abertos": () => <PedidosAbertos onNav={onNav} />,
    "pedidos/faturados": () => <PedidosFaturados onNav={onNav} />,
    "pedidos/cancelados": () => <PedidosCancelados onNav={onNav} />,
    "pdv": () => <PDV />,
    "financeiro": () => <FinDashboard onNav={onNav} />,
    "financeiro/dashboard": () => <FinDashboard onNav={onNav} />,
    "financeiro/entradas": () => <Entradas onNav={onNav} />,
    "financeiro/saidas": () => <Saidas onNav={onNav} />,
    "financeiro/fluxo-caixa": () => <FluxoCaixa onNav={onNav} />,
    "financeiro/contas-pagar": () => <ContasPagar onNav={onNav} />,
    "financeiro/contas-receber": () => <ContasReceber onNav={onNav} />,
    "financeiro/dre": () => <DRESection onNav={onNav} />,
    "financeiro/extrato": () => <ExtratoConsolidado onNav={onNav} />,
    "relatorios": () => <RelVendas onNav={onNav} />,
    "relatorios/vendas": () => <RelVendas onNav={onNav} />,
    "relatorios/distribuidores": () => <RelDistribuidores onNav={onNav} />,
    "relatorios/clientes": () => <RelClientes onNav={onNav} />,
    "relatorios/financeiro": () => <RelFinanceiro onNav={onNav} />,
    "relatorios/insights": () => <RelInsights onNav={onNav} />,
    "relatorios/produtos": () => <RelProdutos onNav={onNav} />,
    "relatorios/curvaabc": () => <RelCurvaABC onNav={onNav} />,
    "relatorios/executivo": () => <RelExecutivo onNav={onNav} />,
    "formularios": () => <Formularios onNav={onNav} />,
    "formularios/lista": () => <Formularios onNav={onNav} />,
    "formularios/leads": () => <FormLeads onNav={onNav} />,
    "kanban": () => <Kanban />,
    "agenda": () => <Agenda />,
    "nf": () => <NFEmissao onNav={onNav} />,
    "nf/emissao": () => <NFEmissao onNav={onNav} />,
    "nf/historico": () => <NFHistorico onNav={onNav} />,
    "nf/empresas": () => <NFEmpresas onNav={onNav} />,
    "nf/importar": () => <NFImportarXml onNav={onNav} />,
    "nf/logs": () => <NFLogs onNav={onNav} />,
    "config": () => <ConfigPage which="perfil" onNav={onNav} profile={profile} />,
    "config/perfil": () => <ConfigPage which="perfil" onNav={onNav} profile={profile} />,
    "config/equipe": () => <ConfigPage which="equipe" onNav={onNav} profile={profile} />,
    "config/empresa": () => <ConfigPage which="empresa" onNav={onNav} profile={profile} />,
    "config/canais": () => <ConfigPage which="canais" onNav={onNav} profile={profile} />,
    "config/ia": () => <ConfigPage which="ia" onNav={onNav} profile={profile} />,
    "config/permissoes": () => <ConfigPage which="permissoes" onNav={onNav} profile={profile} />,
  };

  const rootModule = active.split('/')[0];
  const perms = profile?._permissoes;
  const hasAccess = !perms || perms[rootModule]?.ver !== false;
  const render = hasAccess
    ? (ROUTE[active] || ROUTE["dashboard"])
    : () => (
        <div className="canvas" style={{ display:'flex', alignItems:'center', justifyContent:'center', minHeight:'60vh' }}>
          <div style={{ textAlign:'center' }}>
            <Icon name="shield-off" size={44} className="muted" />
            <div style={{ marginTop:16, fontSize:17, fontWeight:500 }}>Acesso restrito</div>
            <div className="muted" style={{ fontSize:13, marginTop:6 }}>Você não tem permissão para acessar este módulo.</div>
            <div className="muted" style={{ fontSize:12, marginTop:4 }}>Fale com o administrador para solicitar acesso.</div>
          </div>
        </div>
      );

  const paletteOptions = Object.entries(PALETTES).map(([k, v]) => ({ value: k, label: v.label }));
  const displayOptions = Object.entries(DISPLAY_FONTS).map(([k, v]) => ({ value: k, label: v.label }));

  // ── Auth gates (after all hooks) ───────────────────────────────
  if (sessionLoading) return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--tm-bg-0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ textAlign: 'center' }}>
        <div style={{ fontFamily: 'var(--tm-font-display)', fontSize: 28, color: 'var(--tm-brand-champagne)', letterSpacing: '0.06em' }}>TopMix</div>
        <div style={{ fontSize: 11, letterSpacing: '0.2em', color: 'var(--tm-fg-3)', marginTop: 8, textTransform: 'uppercase' }}>Carregando…</div>
      </div>
    </div>
  );

  if (!authUser) return <LoginScreen />;

  if (profile && !profile.ativo) return (
    <div style={{ position: 'fixed', inset: 0, background: 'var(--tm-bg-0)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ textAlign: 'center' }}>
        <Icon name="user-x" size={40} className="muted" />
        <div style={{ marginTop: 16, fontSize: 16 }}>Acesso desativado</div>
        <div className="muted" style={{ fontSize: 13, marginTop: 6 }}>Entre em contato com o administrador.</div>
        <Button variant="ghost" style={{ marginTop: 16 }} onClick={() => window.tmSignOut()}>Sair</Button>
      </div>
    </div>
  );

  return (
    <div className="app">
      <Sidebar
        active={active}
        onNav={onNav}
        permissions={profile?._permissoes}
        empresas={empresas}
        empresaAtual={empresaAtual}
        setEmpresaAtual={setEmpresaAtual}
      />
      <div className="main-wrap">
        <Topbar
          active={active}
          theme={theme}
          setTheme={setTheme}
          profile={profile}
          empresaAtual={empresaAtual}
          onNav={onNav}
        />
        {render()}
      </div>
      <TweaksPanel title="Tweaks · TopMix">
        <TweakSection label="Acento da marca">
          <TweakColor
            label="Paleta"
            value={(PALETTES[t.palette] || PALETTES.champanhe).dark}
            options={Object.values(PALETTES).map(p => p.dark)}
            onChange={(hex) => {
              const key = Object.keys(PALETTES).find(k => PALETTES[k].dark === hex) || "champanhe";
              setTweak("palette", key);
            }}
          />
        </TweakSection>
        <TweakSection label="Tipografia display">
          <TweakRadio
            label="Estilo"
            value={t.display}
            options={displayOptions}
            onChange={(v) => setTweak("display", v)}
          />
        </TweakSection>
        <TweakSection label="Densidade da interface">
          <TweakRadio
            label="Espaçamento"
            value={t.density}
            options={[
              { value: "compacto", label: "Compacto" },
              { value: "padrao",   label: "Padrão"   },
              { value: "amplo",    label: "Amplo"    },
            ]}
            onChange={(v) => setTweak("density", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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