/* AUREN — main app: hash router, auth gating, transitions */
const { useState: uS, useEffect: uE } = React;

const APP_ROUTES = ['dashboard', 'nodes', 'workloads', 'staking', 'wallet', 'explorer', 'governance', 'settings'];

function parseHash() {
  const h = (location.hash || '#landing').replace(/^#\/?/, '');
  return h || 'landing';
}

function AppFrame({ route, go, user, onLogout }) {
  const [menuOpen, setMenuOpen] = uS(false);
  uE(() => { document.querySelector('.app-scroll')?.scrollTo(0, 0); }, [route]);
  const Page = {
    dashboard: <Dashboard go={go} />,
    nodes: <Nodes />,
    workloads: <Workloads />,
    staking: <Staking />,
    wallet: <Wallet />,
    explorer: <Explorer />,
    governance: <Governance />,
    settings: <Settings user={user} onLogout={onLogout} />,
  }[route] || <Dashboard go={go} />;
  return (
    <div style={{ display: 'flex', minHeight: '100vh', background: 'var(--bg-0)' }}>
      <Sidebar route={route} go={go} user={user} onLogout={onLogout} open={menuOpen} setOpen={setMenuOpen} />
      <div className="app-scroll" style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
        <Topbar onMenu={() => setMenuOpen(true)} user={user} />
        <main style={{ flex: 1, padding: 'clamp(20px,3vw,34px)', maxWidth: 1320, width: '100%', margin: '0 auto' }}>
          <div key={route} className="route-in">{Page}</div>
        </main>
      </div>
    </div>
  );
}

function App() {
  const [route, setRoute] = uS(parseHash());
  const [user, setUser] = uS(() => {
    try { return JSON.parse(localStorage.getItem('auren_user') || 'null'); } catch { return null; }
  });
  const [transitioning, setTransitioning] = uS(false);

  uE(() => {
    const onHash = () => setRoute(parseHash());
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  function go(r) {
    if (r === route) return;
    setTransitioning(true);
    setTimeout(() => {
      location.hash = r;
      setRoute(r);
      window.scrollTo(0, 0);
      setTimeout(() => setTransitioning(false), 30);
    }, 220);
  }

  function onAuth(u) {
    localStorage.setItem('auren_user', JSON.stringify(u));
    setUser(u);
    go('dashboard');
  }
  function onLogout() {
    localStorage.removeItem('auren_user');
    setUser(null);
    go('landing');
  }

  // route resolution
  const isApp = APP_ROUTES.includes(route);
  const isAuth = route.startsWith('auth');

  // auth gating
  uE(() => {
    if (isApp && !user) { location.hash = 'auth-login'; setRoute('auth-login'); }
  }, [route, user]);

  let content;
  if (isAuth) {
    content = <Auth mode={route === 'auth-signup' ? 'signup' : 'login'} go={go} onAuth={onAuth} />;
  } else if (isApp) {
    content = user ? <AppFrame route={route} go={go} user={user} onLogout={onLogout} /> : null;
  } else {
    content = <Landing go={go} />;
  }

  return (
    <>
      {/* ambient bg only on landing */}
      {route === 'landing' && <AmbientBg />}
      <div style={{ position: 'relative', zIndex: 1, opacity: transitioning ? 0 : 1, transition: 'opacity .22s var(--ease)' }}>
        {content}
      </div>
    </>
  );
}

function AmbientBg() {
  const ref = useThreeScene((c) => window.AURENThree.ambientNetwork(c, { count: 80 }), []);
  return <div ref={ref} style={{ position: 'fixed', inset: 0, zIndex: 0, opacity: 0.55, pointerEvents: 'none' }} />;
}

(function mount() {
  const el = document.getElementById('root');
  if (!el) { setTimeout(mount, 30); return; }
  ReactDOM.createRoot(el).render(<App />);
})();
