// Main app — fetches data via window.API, then renders the right shell.
//
// Flow:
//   mount → loading splash
//     → API.fetchAll() →
//       • { authenticated: false } → NotAuthenticated (Landing, login hint)
//       • { authenticated: true, hasPair: false } → Landing with create/join
//       • { authenticated: true, hasPair: true }  → full shell with screens
//
// Each screen receives a `reload` callback so its write actions can re-fetch.

function LoadingSplash() {
  return (
    <div style={{minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 40}}>
      <div style={{textAlign: 'center'}}>
        <div style={{fontSize: 48, marginBottom: 14, animation: 'heart-beat 2s infinite'}}>💕</div>
        <div style={{fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18}}>Вопрос дня</div>
        <div style={{color: 'var(--text-3)', marginTop: 6, fontSize: 13}}>Загружаем…</div>
      </div>
    </div>
  );
}

function NotAuthenticated() {
  return (
    <div style={{minHeight: '100vh', display: 'flex', flexDirection: 'column'}}>
      <window.TopBar screen="landing" state="landing" data={null}/>
      <main className="main main--bleed main--full" style={{flex: 1}}>
        <div className="main__inner">
          <window.LandingScreen data={{ authenticated: false, botUsername: 'DailyQuestionLove_bot' }}/>
          <div className="surface" style={{maxWidth: 560, margin: '30px auto 0', padding: '18px 20px', textAlign: 'center', fontSize: 13, color: 'var(--text-3)'}}>
            Чтобы начать играть, сначала войдите через{' '}
            <a href="https://tgplay.ru" style={{color: 'var(--brand-hi)', fontWeight: 600}}>tgplay.ru</a>.
          </div>
        </div>
      </main>
    </div>
  );
}

function ErrorScreen({ message, onRetry }) {
  return (
    <div style={{minHeight: '100vh', display: 'grid', placeItems: 'center', padding: 40}}>
      <div style={{textAlign: 'center', maxWidth: 420}}>
        <div style={{fontSize: 42, marginBottom: 14}}>⚠️</div>
        <div style={{fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, marginBottom: 8}}>Не удалось загрузить</div>
        <div style={{color: 'var(--text-3)', marginBottom: 20, fontSize: 13, lineHeight: 1.5}}>{message}</div>
        <button className="btn-primary" onClick={onRetry}><window.Icon name="arrow" size={14}/> Повторить</button>
      </div>
    </div>
  );
}

function App() {
  const { useState, useEffect, useCallback } = React;
  const [screen, setScreen] = useState('today');
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const load = useCallback(async () => {
    try {
      const d = await window.API.fetchAll();
      setData(d);
      setError(null);
    } catch (e) {
      setError(e.message || 'Неизвестная ошибка');
    } finally {
      setLoading(false);
    }
  }, []);

  // Wrapped reload: doesn't toggle the loading splash (used by write actions)
  const reload = useCallback(async () => {
    try {
      const d = await window.API.fetchAll();
      setData(d);
    } catch (e) {
      // Swallow — keep current data visible, the originating action will surface the error
      console.warn('reload failed', e);
    }
  }, []);

  useEffect(() => { load(); }, [load]);

  if (loading) return <LoadingSplash/>;
  if (error) return <ErrorScreen message={error} onRetry={() => { setLoading(true); load(); }}/>;
  if (!data || !data.authenticated) return <NotAuthenticated/>;

  // Logged in but no pair: show Landing full-bleed with topbar, no sidebar.
  if (!data.hasPair) {
    return (
      <div className="app" style={{gridTemplateColumns: '1fr', gridTemplateAreas: '"top" "main"'}}>
        <window.TopBar screen="landing" state="landing" data={data}/>
        <main className="main main--bleed main--full">
          <div className="main__inner">
            <window.LandingScreen data={data} reload={reload}/>
          </div>
        </main>
      </div>
    );
  }

  const state = data.state;

  function renderScreen() {
    const props = { state, setScreen, data, reload };
    switch (screen) {
      case 'today':    return <window.TodayScreen    {...props}/>;
      case 'reveal':   return <window.RevealScreen   {...props}/>;
      case 'archive':  return <window.ArchiveScreen  {...props}/>;
      case 'stats':    return <window.StatsScreen    {...props}/>;
      case 'capsule':  return <window.CapsuleScreen  {...props}/>;
      case 'settings': return <window.SettingsScreen {...props}/>;
      case 'onboarding': return <window.OnboardingScreen {...props}/>;
      case 'landing':    return <window.LandingScreen    {...props}/>;
      default:         return <window.TodayScreen    {...props}/>;
    }
  }

  return (
    <div className="app" data-screen-label={`tgplay · ${screen}`}>
      <window.TopBar screen={screen} state={state} data={data}/>
      <window.Sidebar screen={screen} setScreen={setScreen} state={state} data={data}/>
      <main className="main">
        <div className="main__inner">{renderScreen()}</div>
      </main>
      <window.MobileTabs screen={screen} setScreen={setScreen} state={state}/>
    </div>
  );
}

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