// App shell — auth gate + page routing
const { useState: useStateA, useEffect: useEffectA } = React;

function App() {
  const [page, setPage] = useStateA(() => localStorage.getItem('kyoudai.page') || 'dashboard');
  const [authState, setAuthState] = useStateA('loading');  // 'loading' | 'unauthenticated' | 'authenticated'
  const [dataReady, setDataReady] = useStateA(false);
  const [dataError, setDataError] = useStateA('');

  useEffectA(() => {
    localStorage.setItem('kyoudai.page', page);
  }, [page]);

  useEffectA(() => {
    // Demo mode: no Supabase — try to load live products from Shopify if configured
    if (!window.SUPABASE) {
      setAuthState('authenticated');
      window.loadShopifyProducts()
        .catch(() => {})  // silently fall back to mock products on error
        .finally(() => setDataReady(true));
      return;
    }

    async function boot(session) {
      if (!session?.user) {
        setAuthState('unauthenticated');
        return;
      }
      setAuthState('authenticated');
      setDataReady(false);
      setDataError('');
      try {
        await window.loadKyoudaiData(session.user.id);
        setDataReady(true);
      } catch (err) {
        setDataError(err.message || 'Failed to load data');
      }
    }

    // Check current session first
    window.SUPABASE.auth.getSession().then(({ data: { session } }) => boot(session));

    // Then listen for sign-in / sign-out
    const { data: { subscription } } = window.SUPABASE.auth.onAuthStateChange(
      async (event, session) => {
        if (event === 'SIGNED_IN')  await boot(session);
        if (event === 'SIGNED_OUT') { setAuthState('unauthenticated'); setDataReady(false); }
      }
    );

    return () => subscription.unsubscribe();
  }, []);

  window.kyoudaiNav = setPage;

  const PageComponent = {
    dashboard: <DashboardPage goToProducts={() => setPage('products')}/>,
    products:  <ProductsPage/>,
    earnings:  <EarningsPage/>,
    content:   <ContentPage/>,
    links:     <LinksPage/>,
    profile:   <ProfilePage/>,
    admin:     <AdminPage/>,
  }[page];

  if (authState === 'loading') return <BootSkeleton/>;
  if (authState === 'unauthenticated') return <AuthPage/>;
  if (!dataReady && !dataError) return <BootSkeleton/>;
  if (dataError) return <DataErrorPage message={dataError}/>;

  return (
    <div style={{ display:'flex', height:'100vh', position:'relative' }}>
      <Sidebar page={page} setPage={setPage}/>
      <main style={{ flex:1, overflow:'auto', position:'relative' }} data-screen-label={`Kyoudai — ${page}`}>
        <Topbar page={page}/>
        {PageComponent}
      </main>
      <ToastHost/>
    </div>
  );
}

function BootSkeleton() {
  return (
    <div style={{ padding:'26px 32px' }}>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:16, marginBottom:16 }}>
        {[0,1,2,3].map(i => (
          <div key={i} className="glass" style={{ padding:20 }}>
            <div className="skel" style={{ width:80, height:12, marginBottom:16 }}/>
            <div className="skel" style={{ width:140, height:28, marginBottom:14 }}/>
            <div className="skel" style={{ width:'100%', height:30 }}/>
          </div>
        ))}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:16 }}>
        <div className="glass" style={{ padding:24, height:360 }}>
          <div className="skel" style={{ width:180, height:14, marginBottom:10 }}/>
          <div className="skel" style={{ width:260, height:10, marginBottom:24 }}/>
          <div className="skel" style={{ width:'100%', height:260 }}/>
        </div>
        <div className="glass" style={{ padding:24, height:360 }}>
          <div className="skel" style={{ width:160, height:10, marginBottom:14 }}/>
          <div className="skel" style={{ width:'100%', height:24, marginBottom:20 }}/>
          <div className="skel" style={{ width:'100%', height:200 }}/>
        </div>
      </div>
    </div>
  );
}

function DataErrorPage({ message }) {
  async function handleSignOut() {
    if (window.SUPABASE) await window.SUPABASE.auth.signOut();
  }
  return (
    <div style={{ height:'100vh', display:'flex', alignItems:'center', justifyContent:'center', flexDirection:'column', gap:16 }}>
      <div style={{ fontSize:32, marginBottom:8 }}>⚠️</div>
      <div style={{ fontSize:16, fontWeight:600 }}>Failed to load account data</div>
      <div style={{ fontSize:13, color:'var(--sub)', maxWidth:400, textAlign:'center', lineHeight:1.5 }}>{message}</div>
      <button className="btn btn-primary" onClick={handleSignOut} style={{ marginTop:8 }}>Sign out and retry</button>
    </div>
  );
}

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