/* JRN — App shell, navegação, controle de acesso e Tweaks */
const { useState: uS, useEffect } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "companyInteraction": "click",
  "sidebar": "navy",
  "showBrandBar": true
}/*EDITMODE-END*/;

/* Itens de navegação administrativos e a função que cada um exige */
const ADMIN_NAV = [
  { id: 'admin-dashboards', label: 'Dashboards', icon: 'chart', fn: 'dash_cadastro' },
  { id: 'admin-users', label: 'Usuários', icon: 'users', fn: 'user_edicao' },
  { id: 'admin-companies', label: 'Empresas', icon: 'building', fn: null },
  { id: 'admin-audit', label: 'Auditoria', icon: 'history', fn: 'auditoria' },
];

function canSee(user, fn) {
  if (!user) return false;
  if (user.perfil === 'admin') return true;
  if (!fn) return false;
  const fns = user.funcoes || [];
  return fns.includes('*') || fns.includes(fn);
}

function Sidebar({ user, view, onNav, tweaks, collapsed, onToggle, onLogout, mobile, mobileOpen }) {
  const dark = tweaks.sidebar === 'navy';
  const [userOpen, setUserOpen] = useState(false);
  const adminItems = ADMIN_NAV.filter(i => canSee(user, i.fn));
  const showExpanded = mobile ? true : !collapsed; // no mobile sempre expandida
  const C = {
    bg: dark ? 'linear-gradient(180deg,#15233f,#0d1730)' : '#fff',
    fg: dark ? '#fff' : 'var(--ink)',
    muted: dark ? '#8ea0c4' : 'var(--muted)',
    line: dark ? 'rgba(255,255,255,.1)' : 'var(--line)',
    activeBg: dark ? 'rgba(255,255,255,.12)' : 'var(--navy-100)',
    activeFg: dark ? '#fff' : 'var(--navy-800)',
    hover: dark ? 'rgba(255,255,255,.06)' : 'var(--navy-50)',
  };
  const NavItem = ({ id, label, icon }) => {
    const I = Icons[icon];
    const active = view === id || (id === 'portal' && (view === 'portal' || view === 'dashboard'));
    return (
      <button onClick={() => onNav(id)} title={!showExpanded ? label : undefined} style={{
        display: 'flex', alignItems: 'center', gap: 12, width: '100%', textAlign: 'left',
        padding: !showExpanded ? '11px 0' : '11px 13px', justifyContent: !showExpanded ? 'center' : 'flex-start',
        borderRadius: 9, border: 'none', cursor: 'pointer', fontSize: 14, fontWeight: 600,
        background: active ? C.activeBg : 'transparent', color: active ? C.activeFg : C.muted,
        transition: 'background .13s', fontFamily: 'var(--font-ui)', whiteSpace: 'nowrap', overflow: 'hidden',
      }}
        onMouseEnter={e => { if (!active) e.currentTarget.style.background = C.hover; }}
        onMouseLeave={e => { if (!active) e.currentTarget.style.background = 'transparent'; }}>
        <I size={18} />{showExpanded && label}
      </button>
    );
  };

  const mobileStyle = mobile ? {
    position: 'fixed', top: 0, left: 0, height: '100vh', zIndex: 55, overflowY: 'auto',
    width: 260, transform: mobileOpen ? 'translateX(0)' : 'translateX(-270px)',
    transition: 'transform .25s cubic-bezier(.4,0,.2,1)',
    boxShadow: mobileOpen ? 'var(--sh-lg)' : 'none',
  } : {
    width: collapsed ? 76 : 248,
    position: 'sticky', top: 0, height: '100vh',
    transition: 'width .22s ease, padding .22s ease',
    flexShrink: 0,
  };

  return (
    <aside style={{
      background: C.bg, borderRight: `1px solid ${C.line}`,
      display: 'flex', flexDirection: 'column',
      padding: !showExpanded ? '22px 12px' : '22px 16px',
      zIndex: 45,
      ...mobileStyle,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: !showExpanded ? 'center' : 'flex-start', gap: 11, padding: !showExpanded ? '0 0 18px' : '4px 4px 20px' }}>
        <img src="assets/logos/jrn.png" alt="JRN" style={{ height: !showExpanded ? 24 : 30, filter: dark ? 'brightness(0) invert(1)' : 'none' }} />
        {showExpanded && <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '.14em', color: C.muted, textTransform: 'uppercase', borderLeft: `1px solid ${C.line}`, paddingLeft: 11, lineHeight: 1.3 }}>Portal de<br />Indicadores</span>}
      </div>

      {/* Botão de colapso — oculto no mobile */}
      {!mobile && (
        <button onClick={onToggle} title={collapsed ? 'Expandir menu' : 'Recolher menu'} aria-label={collapsed ? 'Expandir menu' : 'Recolher menu'} style={{
          position: 'absolute', top: '50%', right: 0, transform: 'translateY(-50%)',
          width: 15, height: 52, padding: 0, border: 'none', cursor: 'pointer',
          borderRadius: '8px 0 0 8px',
          background: dark ? 'rgba(255,255,255,.07)' : 'var(--navy-50)',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3,
          transition: 'background .15s',
        }}
          onMouseEnter={e => e.currentTarget.style.background = dark ? 'rgba(255,255,255,.16)' : 'var(--navy-100)'}
          onMouseLeave={e => e.currentTarget.style.background = dark ? 'rgba(255,255,255,.07)' : 'var(--navy-50)'}>
          <span style={{ width: 2, height: 16, borderRadius: 2, background: dark ? '#aab7d2' : 'var(--muted)' }}></span>
          <span style={{ width: 2, height: 16, borderRadius: 2, background: dark ? '#aab7d2' : 'var(--muted)' }}></span>
        </button>
      )}

      {showExpanded && <div className="kicker" style={{ color: C.muted, padding: '6px 10px 8px' }}>Portal</div>}
      {!showExpanded && <div style={{ height: 8 }}></div>}
      <NavItem id="portal" label="Empresas" icon="grid" />

      {adminItems.length > 0 && (
        <React.Fragment>
          {showExpanded
            ? <div className="kicker" style={{ color: C.muted, padding: '22px 10px 8px' }}>Administração</div>
            : <div style={{ height: 1, background: C.line, margin: '16px 8px' }}></div>}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
            {adminItems.map(i => <NavItem key={i.id} {...i} />)}
          </div>
        </React.Fragment>
      )}

      <div style={{ marginTop: 'auto', paddingTop: 18, borderTop: `1px solid ${C.line}`, position: 'relative' }}>
        {userOpen && (
          <React.Fragment>
            <div onClick={() => setUserOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 49 }} />
            <div className="card fade-in" style={{
              position: 'absolute', bottom: 'calc(100% + 8px)', left: 0,
              width: 220, zIndex: 50, boxShadow: 'var(--sh-lg)', padding: 8,
            }}>
              <div style={{ padding: '10px 12px 12px', borderBottom: '1px solid var(--line-2)', marginBottom: 6 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.nome}</div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.email}</div>
              </div>
              <button onClick={() => { setUserOpen(false); onLogout(); }} style={{
                display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left',
                padding: '9px 12px', borderRadius: 8, border: 'none', cursor: 'pointer',
                background: 'transparent', fontSize: 13, fontWeight: 600, color: 'var(--danger)',
              }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--danger-soft)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                <Icons.logout size={15} /> Sair do portal
              </button>
            </div>
          </React.Fragment>
        )}

        <button onClick={() => setUserOpen(o => !o)} title={!showExpanded ? user.nome : undefined} style={{
          display: 'flex', alignItems: 'center', justifyContent: !showExpanded ? 'center' : 'flex-start',
          gap: 11, padding: !showExpanded ? '6px 0' : '6px 8px', width: '100%',
          border: 'none', borderRadius: 9, cursor: 'pointer', background: 'transparent',
          transition: 'background .13s',
        }}
          onMouseEnter={e => e.currentTarget.style.background = C.hover}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
          <span className="avatar" style={{ background: dark ? 'rgba(255,255,255,.14)' : 'var(--navy-100)', color: dark ? '#fff' : 'var(--navy-800)' }}>{user.avatar}</span>
          {showExpanded && (
            <div style={{ minWidth: 0, flex: 1, textAlign: 'left' }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: C.fg, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{user.nome}</div>
              <div style={{ fontSize: 11, color: C.muted }}>{user.perfil === 'admin' ? 'Administrador' : 'Usuário comum'}</div>
            </div>
          )}
        </button>
      </div>
    </aside>
  );
}

function Topbar({ user, onLogout, onOpenMenu, isMobile }) {
  return (
    <header className="topbar" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '0 30px', height: 64, borderBottom: '1px solid var(--line)', background: 'rgba(255,255,255,.85)', backdropFilter: 'blur(8px)', position: 'sticky', top: 0, zIndex: 40, flexShrink: 0 }}>
      {isMobile && (
        <button onClick={onOpenMenu} title="Menu" className="btn btn-ghost btn-sm" style={{ border: '1px solid var(--line)', padding: 8, flexShrink: 0 }}>
          <Icons.menu size={17} />
        </button>
      )}
      <div className="topbar-search" style={{ position: 'relative', flex: 1, maxWidth: 380 }}>
        <Icons.search size={16} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: 'var(--muted)' }} />
        <input className="input" style={{ paddingLeft: 36, background: 'var(--surface-2)' }} placeholder="Buscar empresa ou painel…" />
      </div>
      <div style={{ flex: 1 }}></div>
      <button onClick={onLogout} title="Sair" className="btn btn-ghost btn-sm" style={{ border: '1px solid var(--line)', padding: 8 }}>
        <Icons.logout size={17} />
      </button>
    </header>
  );
}

/* Tela de carregamento enquanto verifica a sessão */
function LoadingScreen() {
  return (
    <div style={{ minHeight: '100vh', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, background: 'var(--bg)' }}>
      <img src="assets/logos/jrn.png" alt="JRN" style={{ height: 40, opacity: .5 }} />
      <Icons.refresh className="spin" size={22} style={{ color: 'var(--muted)' }} />
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [session, setSession] = useState(null);
  const [loadingSession, setLoadingSession] = useState(true);
  const [empresas, setEmpresas] = useState([]);
  const [view, setView] = useState('portal');
  const isMobile = useMediaQuery('(max-width: 640px)');
  const isTablet = useMediaQuery('(max-width: 1100px)');
  const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
  const [collapsed, setCollapsed] = useState(() => {
    const saved = localStorage.getItem('jrn-sidebar');
    if (saved !== null) return saved === '1';
    return window.innerWidth <= 1100; // recolhido por padrão em telas menores
  });
  const toggleSidebar = () => setCollapsed(c => { localStorage.setItem('jrn-sidebar', c ? '0' : '1'); return !c; });
  const [openDash, setOpenDash] = useState(null);
  const [toastNode, toast] = useToast();

  // Verifica sessão existente ao carregar a página
  useEffect(() => {
    apiMe()
      .then(({ user, empresas: emp }) => {
        setSession(user);
        setEmpresas(emp);
      })
      .catch(() => {})
      .finally(() => setLoadingSession(false));
  }, []);

  // Navega e fecha sidebar no mobile
  const handleNav = (v) => {
    setView(v);
    setOpenDash(null);
    if (isMobile) setMobileSidebarOpen(false);
  };

  // Chamado após apiLogin() bem-sucedido
  const doLogin = async () => {
    const { user, empresas: emp } = await apiMe();
    setSession(user);
    setEmpresas(emp);
    setView('portal');
    setOpenDash(null);
  };

  const logout = async () => {
    try { await apiLogout(); } catch (_) {}
    setSession(null);
    setEmpresas([]);
    setView('portal');
    setOpenDash(null);
  };

  if (loadingSession) return <LoadingScreen />;

  if (!session) return (
    <React.Fragment>
      <LoginScreen onLogin={doLogin} />
      <TweaksHost t={t} setTweak={setTweak} />
    </React.Fragment>
  );

  let content;
  if (view === 'dashboard' && openDash) {
    content = <DashboardViewer dashboard={openDash} user={session} empresas={empresas} onBack={() => { setView('portal'); setOpenDash(null); }} />;
  } else if (view === 'admin-users' && canSee(session, 'user_edicao')) {
    content = <UsersAdmin empresas={empresas} toast={toast} />;
  } else if (view === 'admin-dashboards' && canSee(session, 'dash_cadastro')) {
    content = <DashboardsAdmin empresas={empresas} toast={toast} />;
  } else if (view === 'admin-companies' && session.perfil === 'admin') {
    content = <CompaniesAdmin />;
  } else if (view === 'admin-audit' && canSee(session, 'auditoria')) {
    content = <AuditAdmin />;
  } else {
    content = <PortalHome user={session} empresas={empresas} mode={t.companyInteraction} onOpen={(d) => { setOpenDash(d); setView('dashboard'); }} />;
  }

  const mainPad = isMobile ? '18px 16px 40px' : isTablet ? '26px 28px 56px' : '34px 40px 60px';

  return (
    <div style={{ display: 'flex', minHeight: '100vh' }}>
      {/* Backdrop para fechar sidebar no mobile */}
      {isMobile && mobileSidebarOpen && (
        <div className="sb-backdrop" onClick={() => setMobileSidebarOpen(false)} />
      )}
      <Sidebar
        user={session} view={view} onNav={handleNav} tweaks={t}
        collapsed={collapsed} onToggle={toggleSidebar} onLogout={logout}
        mobile={isMobile} mobileOpen={mobileSidebarOpen}
      />
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <Topbar user={session} onLogout={logout} tweaks={t} isMobile={isMobile} onOpenMenu={() => setMobileSidebarOpen(true)} />
        <main className="page-main" style={{ flex: 1, padding: mainPad, maxWidth: 1320, width: '100%', margin: '0 auto' }}>{content}</main>
      </div>
      {toastNode}
      <TweaksHost t={t} setTweak={setTweak} />
    </div>
  );
}

function TweaksHost({ t, setTweak }) {
  return (
    <TweaksPanel>
      <TweakSection label="Interação com empresas" />
      <TweakRadio label="Revelar painéis ao" value={t.companyInteraction}
        options={['hover', 'click']}
        onChange={(v) => setTweak('companyInteraction', v)} />
      <TweakSection label="Aparência" />
      <TweakRadio label="Menu lateral" value={t.sidebar}
        options={['navy', 'claro']}
        onChange={(v) => setTweak('sidebar', v)} />
    </TweaksPanel>
  );
}

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