const { useState, useEffect } = React;

function AppInner() {
  const [resorts, setResorts] = useState(null);
  const route = useRoute();
  const { lang, t } = useI18n();

  useEffect(() => { loadResorts().then(setResorts); }, []);

  // Compute view + active before any early return so the hook order is stable.
  let view = route.view;
  let active = null;
  if (resorts && view === 'detail') {
    active = resorts.find(r => r.id === route.id);
    if (!active) { replaceRoute(localizePath(lang, '/')); view = 'home'; }
  }

  // Resort-aware document title — declared before any early return.
  useEffect(() => {
    document.title = active ? t('meta.titleResort', { name: active.name }) : t('meta.title');
  }, [active, t]);

  if (!resorts) {
    return (
      <div className="app app--loading">
        <div className="loading-pill">{t('states.loading')}</div>
      </div>
    );
  }

  const handlePick = (id) => navigate(localizePath(lang, `/resorts/${id}`));
  const handleHome = () => navigate(localizePath(lang, '/'));
  const handleBack = () => navigate(localizePath(lang, '/'));
  const mobileView = view === 'detail' ? 'detail' : 'home';

  return (
    <div className={`app app--mobile-${mobileView}`}>
      <Header onBack={handleBack} onHome={handleHome}/>
      <div className="main">
        <Sidebar resorts={resorts} activeId={active?.id ?? null} onPick={handlePick}/>
        <div className="content">
          {view === 'home' ? (
            <section className="home">
              <h1 className="home__title">{t('home.title')}</h1>
              <p className="home__subtitle">{t('home.subtitle')}</p>
              <RegionMap resorts={resorts} activeId={null} onPick={handlePick}/>
            </section>
          ) : (
            <>
              <ResortHeader resort={active}/>
              <div className="grid-main">
                <PhotoCarousel src={active.photo}/>
                <ResortStatistics resort={active}/>
                <WebcamsWidget resort={active}/>
                <SkiInsuranceWidget/>
                <TrailMap image={`${ASSETS}/resorts/vall-de-nuria-trail-map.png`}/>
              </div>
              <div className="grid-maps">
                <Resort3DViewer resort={active}/>
                <RegionMap resorts={resorts} activeId={active.id} onPick={handlePick}/>
              </div>
              <SnowfallMap resort={active}/>
            </>
          )}
          <Footer/>
        </div>
      </div>
    </div>
  );
}

function App() {
  return (
    <I18nProvider>
      <window.PreferencesProvider>
        <AppInner/>
      </window.PreferencesProvider>
    </I18nProvider>
  );
}

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