/* global React */
const { useState } = React;

function TweaksHost() {
  const app = useApp();
  // Use the starter <TweaksPanel> from window
  const { TweaksPanel, TweakSection, TweakRadio, TweakToggle } = window;
  if (!TweaksPanel) return null;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Theme">
        <TweakRadio label="Mode"  value={app.theme}   onChange={app.setTheme}   options={[{value:'light', label:'Light'}, {value:'dark', label:'Dark'}]}/>
        <TweakRadio label="Accent" value={app.accent} onChange={app.setAccent} options={[{value:'cyan', label:'Cyan'}, {value:'green', label:'Green'}, {value:'violet', label:'Violet'}, {value:'amber', label:'Amber'}, {value:'rose', label:'Rose'}]}/>
      </TweakSection>
      <TweakSection title="Layout">
        <TweakRadio label="Density" value={app.density} onChange={app.setDensity} options={[{value:'comfortable', label:'Comfy'}, {value:'compact', label:'Compact'}]}/>
      </TweakSection>
      <TweakSection title="User tier (for locked states)">
        <TweakRadio label="Tier" value={app.tier} onChange={app.setTier} options={[
          {value:'free', label:'Free'}, {value:'pro', label:'Pro'}, {value:'team', label:'Team'}, {value:'enterprise', label:'Enterprise'}
        ]}/>
      </TweakSection>
    </TweaksPanel>
  );
}
window.TweaksHost = TweaksHost;

/* =========================================================================
   Root router
   ========================================================================= */
function Root() {
  const { route, setRoute, isAuthed, user, hasBackend, quotaExceeded } = useApp();
  if (!isAuthed || route === 'login') return <><LoginScreen/><TweaksHost/></>;

  // Force the one-time profile form when the signed-in user has no name on
  // record. Skip is session-scoped (see ProfileSetup).
  const needsProfile = hasBackend && user && window.profileSetupNeeded?.(user);
  // Route guard: free-tier users at quota cannot enter the New chat screen,
  // even by typing `#new` in the URL bar. The backend enforces the same limit
  // (RateLimitError → 429), but bouncing the route up front avoids loading the
  // composer just to fail on send.
  let effectiveRoute = needsProfile && route !== 'profile' ? 'profile' : route;
  if (effectiveRoute === 'new' && quotaExceeded) {
    effectiveRoute = 'dashboard';
    if (window.location.hash.replace('#', '') === 'new') {
      // Sync the URL so a refresh doesn't re-trigger the bounce.
      window.location.hash = 'dashboard';
    }
  }

  return (
    <div className="app">
      <TopNav route={effectiveRoute} onNavigate={setRoute}/>
      <main style={{minHeight:0, overflow: effectiveRoute === 'new' ? 'hidden' : 'auto'}}>
        {effectiveRoute === 'profile'   && <ProfileSetup/>}
        {effectiveRoute === 'dashboard' && <Dashboard/>}
        {effectiveRoute === 'new'       && <NewAnalysis/>}
        {effectiveRoute === 'history'   && <HistoryScreen/>}
        {effectiveRoute === 'detail'    && <AnalysisDetail/>}
        {effectiveRoute === 'pricing'   && <PricingScreen/>}
        {effectiveRoute === 'account'   && <AccountScreen/>}
        {effectiveRoute === 'preferences' && <PreferencesScreen/>}
        {effectiveRoute === 'admin'       && <AdminScreen/>}
      </main>
      <TweaksHost/>
    </div>
  );
}

function App() {
  return (
    <AppProvider>
      <Root/>
    </AppProvider>
  );
}

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