// Main app shell + routing
const App = () => {
  const [active, setActive] = useState('dashboard');
  const [windDown, setWindDown] = useState(false);
  const [connectModal, setConnectModal] = useState(false);
  const [connected, setConnected] = useState(true); // can toggle off to see empty state
  const auth = useAuth();

  const T = window.useTweaks ? window.useTweaks : null;
  const defaults = /*EDITMODE-BEGIN*/{
    "showMascot": true,
    "wearableConnected": true
  }/*EDITMODE-END*/;
  const [tweaks, setTweak] = T ? T(defaults) : [defaults, () => {}];

  useEffect(() => {
    setConnected(tweaks.wearableConnected);
  }, [tweaks.wearableConnected]);

  if (auth.isLoading) {
    return (
      <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#0a0816' }}>
        <div style={{ textAlign: 'center' }}>
          <Mascot score={87} size={120} mood="sleep"/>
          <p style={{ marginTop: 20, color: '#f4f1ff', fontSize: 14 }}>Initializing session...</p>
        </div>
      </div>
    );
  }

  if (auth.isRefreshing) {
    return (
      <div style={{ position: 'fixed', inset: 0, background: 'rgba(10, 8, 22, 0.95)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999 }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ width: 60, height: 60, margin: '0 auto 20px', borderRadius: '50%', border: '3px solid rgba(184, 169, 255, 0.2)', borderTopColor: 'rgba(184, 169, 255, 0.8)', animation: 'spin 1s linear infinite' }} />
          <p style={{ color: '#f4f1ff', fontSize: 14 }}>Refreshing session...</p>
        </div>
        <style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
      </div>
    );
  }

  if (!auth.isAuthenticated) {
    return <AuthModal onAuthSuccess={() => auth.initializeAuth()} />;
  }

  // Authenticated but no synced sleep for today — prompt to open the app instead of screens.
  if (window.needsSleepSync()) {
    return <window.SyncRequiredModal />;
  }

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

  const screen = (() => {
    if (!connected && active !== 'marketplace' && active !== 'community' && active !== 'rewards') {
      return <ConnectEmptyState onConnect={() => setConnectModal(true)} />;
    }
    switch (active) {
      case 'dashboard': return <Dashboard onNav={onNav} onWindDown={() => setWindDown(true)} showMascot={tweaks.showMascot} onLogout={auth.logout}/>;
      case 'agent': return <AIAgentScreen/>;
      case 'sleep': return <SleepScreen onNav={onNav}/>;
      case 'activity': return <ActivityScreen/>;
      case 'nutrition': return <NutritionScreen onNav={onNav}/>;
      case 'mind': return <MindBodyScreen onWindDown={() => setWindDown(true)}/>;
      case 'rewards': return <RewardsScreen/>;
      case 'marketplace': return <MarketplaceScreen/>;
      case 'community': return <CommunityScreen/>;
      default: return null;
    }
  })();

  const screenLabel = window.NAV.find(n => n.id === active)?.label || active;

  return (
    <window.ToastProvider>
      <div className="app">
        <Sidebar active={active} onNav={onNav} onLogout={auth.logout}/>
        <main className="main" data-screen-label={screenLabel}>
          {screen}
        </main>

        {windDown && <WindDownModal onClose={() => setWindDown(false)}/>}
        {connectModal && <ConnectWearableModal onClose={() => setConnectModal(false)} onConnect={(id) => { setConnectModal(false); setTweak('wearableConnected', true); }}/>}

        {window.TweaksPanel && (
          <window.TweaksPanel title="Tweaks">
            <window.TweakSection title="Display">
              <window.TweakToggle label="Show mascot" value={tweaks.showMascot} onChange={v => setTweak('showMascot', v)}/>
              <window.TweakToggle label="Wearable connected" value={tweaks.wearableConnected} onChange={v => setTweak('wearableConnected', v)}/>
            </window.TweakSection>
            <window.TweakSection title="Quick actions">
              <window.TweakButton label="Open wind-down check-in" onClick={() => setWindDown(true)}/>
              <window.TweakButton label="Open wearable picker" onClick={() => setConnectModal(true)}/>
            </window.TweakSection>
          </window.TweaksPanel>
        )}
      </div>
    </window.ToastProvider>
  );
};

// Single responsive tree — the layout adapts to the viewport via CSS (the sidebar
// collapses into a bottom tab bar on narrow screens), so we mount one app for all sizes.
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
