/* global React, ReactDOM, Icon, Avatar,
   LoginScreen, SignupScreen, RecoverScreen,
   Dashboard, Jornada, LessonPlayer, Materiais, LivesScreen, Comunidade, Perfil,
   AdminPanel,
   TweaksPanel, useTweaks, TweakSection, TweakRadio, TweakSelect, TweakColor, TweakToggle,
   useHashRoute, useDB */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "navLayout": "sidebar",
  "cardStyle": "default",
  "fontHeading": "Archivo",
  "fontBody": "Manrope",
  "theme": "dark",
  "accent": "#2a6cff"
}/*EDITMODE-END*/;

const FONT_HEADING_OPTIONS = ['Archivo', 'Archivo Black', 'Manrope', 'Inter', 'Playfair Display', 'IBM Plex Serif'];
const FONT_BODY_OPTIONS = ['Manrope', 'Inter', 'IBM Plex Sans', 'Source Sans 3', 'Archivo'];

function App() {
  useDB(); // re-render on DB change
  const session = DB.getSession();
  const [user, setUser] = React.useState(session?.user || null);
  const { hash, nav } = useHashRoute();
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks to root
  React.useEffect(() => {
    const r = document.documentElement;
    r.setAttribute('data-theme', tweaks.theme);
    r.setAttribute('data-card-style', tweaks.cardStyle);
    r.style.setProperty('--font-heading', `'${tweaks.fontHeading}'`);
    r.style.setProperty('--font-body', `'${tweaks.fontBody}'`);
    r.style.setProperty('--blue', tweaks.accent);
  }, [tweaks.theme, tweaks.cardStyle, tweaks.fontHeading, tweaks.fontBody, tweaks.accent]);

  // Load fonts dynamically when changed
  React.useEffect(() => {
    const families = new Set([tweaks.fontHeading, tweaks.fontBody, 'Archivo', 'Manrope', 'Archivo Black']);
    const id = 'dynamic-fonts';
    let link = document.getElementById(id);
    const familyParam = [...families].map(f => `family=${f.replace(/ /g, '+')}:wght@300;400;500;600;700;800;900`).join('&');
    const href = `https://fonts.googleapis.com/css2?${familyParam}&display=swap`;
    if (!link) {
      link = document.createElement('link');
      link.id = id;
      link.rel = 'stylesheet';
      document.head.appendChild(link);
    }
    link.href = href;
  }, [tweaks.fontHeading, tweaks.fontBody]);

  // ---- public legal docs (accessible w/ or w/o session) ----
  // (returns moved below — must come after all useEffect calls)

  // ---- auth: redirect when no session ----
  React.useEffect(() => {
    if (!user) {
      const ok = ['/login', '/cadastro', '/recuperar', '/termos', '/privacidade'];
      if (!ok.some(p => hash.startsWith(p))) nav('/login');
    } else {
    if (hash === '/login' || hash === '/cadastro' || hash === '/recuperar' || hash === '/') {
        nav('/dashboard');
      }
    }
  }, [user, hash, nav]);

  // ---- public legal docs (must come AFTER all useEffect calls — hooks must run unconditionally) ----
  if (hash.startsWith('/termos')) {
    return <TermsPage nav={nav} user={user}/>;
  }
  if (hash.startsWith('/privacidade')) {
    return <PrivacyPage nav={nav} user={user}/>;
  }

  const onLogin = (u) => { setUser(u); nav('/dashboard'); };
  const onLogout = () => { DB.logout(); setUser(null); nav('/login'); };

  // ---- routes ----
  if (!user) {
    if (hash.startsWith('/cadastro')) return <SignupScreen onLogin={onLogin} nav={nav}/>;
    if (hash.startsWith('/recuperar')) return <RecoverScreen nav={nav}/>;
    return <LoginScreen onLogin={onLogin} nav={nav}/>;
  }

  // refresh user from DB (e.g. after profile edit)
  const liveUser = DB.userById(user.id) || user;

  let screen = null;
  if (hash.startsWith('/jornada/')) {
    const slug = hash.split('/jornada/')[1].split('/')[0];
    screen = <Jornada user={liveUser} phaseSlug={slug} nav={nav}/>;
  } else if (hash.startsWith('/jornada')) {
    screen = <Jornada user={liveUser} nav={nav}/>;
  } else if (hash.startsWith('/aula/')) {
    const id = hash.split('/aula/')[1];
    screen = <LessonPlayer user={liveUser} lessonId={id} nav={nav}/>;
  } else if (hash.startsWith('/materiais')) {
    screen = <Materiais user={liveUser} nav={nav}/>;
  } else if (hash.startsWith('/lives')) {
    screen = <LivesScreen nav={nav}/>;
  } else if (hash.startsWith('/comunidade')) {
    screen = <Comunidade user={liveUser}/>;
  } else if (hash.startsWith('/perfil')) {
    screen = <Perfil user={liveUser}/>;
  } else if (hash.startsWith('/admin')) {
    if (liveUser.role !== 'admin') {
      nav('/dashboard');
      return null;
    }
    screen = <AdminPanel user={liveUser} nav={nav}/>;
  } else {
    screen = <Dashboard user={liveUser} nav={nav}/>;
  }

  const isTopbar = tweaks.navLayout === 'topbar';

  return (
    <>
      <div className={`app-shell ${isTopbar ? 'topbar topbar-shell' : ''}`}>
        {isTopbar ? <TopBar user={liveUser} hash={hash} nav={nav} onLogout={onLogout}/> : <Sidebar user={liveUser} hash={hash} nav={nav} onLogout={onLogout}/>}
        {screen}
      </div>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Aparência">
          <TweakRadio label="Tema" value={tweaks.theme} onChange={(v)=>setTweak('theme', v)}
            options={[{value:'dark',label:'Escuro'},{value:'light',label:'Claro'}]}/>
          <TweakColor label="Cor de destaque" value={tweaks.accent} onChange={(v)=>setTweak('accent', v)}
            options={['#2a6cff', '#3d82ff', '#d4a55a', '#e85751', '#38b676', '#9a4ddf']}/>
        </TweakSection>

        <TweakSection label="Cards">
          <TweakSelect label="Estilo dos cards" value={tweaks.cardStyle} onChange={(v)=>setTweak('cardStyle', v)}
            options={['default', 'flat', 'glass', 'bordered']}/>
        </TweakSection>

        <TweakSection label="Navegação">
          <TweakRadio label="Layout" value={tweaks.navLayout} onChange={(v)=>setTweak('navLayout', v)}
            options={[{value:'sidebar',label:'Sidebar'},{value:'topbar',label:'Top bar'}]}/>
        </TweakSection>

        <TweakSection label="Tipografia">
          <TweakSelect label="Títulos" value={tweaks.fontHeading} onChange={(v)=>setTweak('fontHeading', v)} options={FONT_HEADING_OPTIONS}/>
          <TweakSelect label="Corpo" value={tweaks.fontBody} onChange={(v)=>setTweak('fontBody', v)} options={FONT_BODY_OPTIONS}/>
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

// ----- Sidebar nav -----
const NAV_ITEMS = [
  { path: '/dashboard', label: 'Dashboard', icon: 'home' },
  { path: '/jornada', label: 'Jornada', icon: 'journey' },
  { path: '/lives', label: 'Lives', icon: 'video' },
  { path: '/materiais', label: 'Materiais', icon: 'file' },
  { path: '/comunidade', label: 'Comunidade', icon: 'chat' }
];

function Sidebar({ user, hash, nav, onLogout }) {
  const isActive = (path) => hash === path || (path !== '/dashboard' && hash.startsWith(path));
  return (
    <aside className="sidebar">
      <div className="sidebar-logo">
        <img src="assets/logo-full.png" alt="Edson Lima"/>
      </div>
      <div className="sidebar-section">Programa</div>
      {NAV_ITEMS.map(it => (
        <div key={it.path} className={`nav-item ${isActive(it.path) ? 'active' : ''}`} onClick={()=>nav(it.path)}>
          <Icon name={it.icon} size={17}/>{it.label}
        </div>
      ))}
      <div className="sidebar-section">Conta</div>
      <div className={`nav-item ${isActive('/perfil') ? 'active' : ''}`} onClick={()=>nav('/perfil')}>
        <Icon name="user" size={17}/>Perfil
      </div>
      {user.role === 'admin' && (
        <div className={`nav-item ${isActive('/admin') ? 'active' : ''}`} onClick={()=>nav('/admin')}>
          <Icon name="settings" size={17}/>Painel Admin
          <span className="badge">ADMIN</span>
        </div>
      )}
      <div className="sidebar-spacer"/>
      <div className="sidebar-user">
        <Avatar user={user}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="name" style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{user.name}</div>
          <div className="role">{user.role === 'admin' ? 'Admin' : 'Mentorado'}</div>
        </div>
        <button className="btn-icon" onClick={onLogout} title="Sair">
          <Icon name="logout" size={14}/>
        </button>
      </div>
    </aside>
  );
}

function TopBar({ user, hash, nav, onLogout }) {
  const isActive = (path) => hash === path || (path !== '/dashboard' && hash.startsWith(path));
  return (
    <header className="topbar">
      <div className="logo"><img src="assets/logo-full.png" alt="Edson Lima"/></div>
      <nav className="top-nav">
        {NAV_ITEMS.map(it => (
          <div key={it.path} className={`nav-item ${isActive(it.path) ? 'active' : ''}`} onClick={()=>nav(it.path)}>
            <Icon name={it.icon} size={15}/>{it.label}
          </div>
        ))}
        {user.role === 'admin' && (
          <div className={`nav-item ${isActive('/admin') ? 'active' : ''}`} onClick={()=>nav('/admin')}>
            <Icon name="settings" size={15}/>Admin
          </div>
        )}
      </nav>
      <div className="top-right">
        <button className="btn-icon" title="Notificações"><Icon name="bell" size={16}/></button>
        <div className="hstack" style={{ gap: 10, padding: '4px 10px 4px 4px', border:'1px solid var(--line-dark)', borderRadius: 30 }}>
          <Avatar user={user}/>
          <div onClick={()=>nav('/perfil')} style={{ cursor:'pointer' }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-light)', lineHeight: 1.1 }}>{user.name.split(' ')[0]}</div>
            <div style={{ fontSize: 10.5, color: 'var(--text-muted)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>{user.role === 'admin' ? 'Admin' : 'Mentorado'}</div>
          </div>
          <button className="btn-icon" onClick={onLogout} title="Sair" style={{ marginLeft: 6 }}>
            <Icon name="logout" size={14}/>
          </button>
        </div>
      </div>
    </header>
  );
}

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