// app.jsx — top-level App shell, view router, mount.

function LoadingScreen() {
  return (
    <div className="ctx-fadeIn" style={{
      width: '100%', minHeight: '100dvh',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      gap: 18, padding: 40, background: VI.bg,
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 99,
        border: `1px solid ${VI.border}`,
        borderTopColor: VI.accent,
        animation: 'school-spin 1s linear infinite',
      }}/>
      <Wordmark size={9}/>
      <div style={{
        fontFamily: VI.fontMono, fontSize: 9, color: VI.textMute,
        letterSpacing: '0.18em', textTransform: 'uppercase',
      }}>Loading the field guide…</div>
      <style>{`
        @keyframes school-spin { to { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

function ErrorScreen({ message, onRetry }) {
  return (
    <div style={{
      width: '100%', minHeight: '100dvh',
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      gap: 12, padding: 40, background: VI.bg,
      textAlign: 'center',
    }}>
      <div style={{
        fontFamily: VI.fontDisp, fontStyle: 'italic', fontWeight: 300,
        fontSize: 22, color: VI.text,
      }}>The guide is unreachable.</div>
      <div style={{
        fontFamily: VI.fontMono, fontSize: 10, color: VI.textMute,
        letterSpacing: '0.12em', maxWidth: 280,
      }}>{message}</div>
      <button className="ctx-btn" onClick={onRetry} style={{
        marginTop: 12, padding: '10px 18px',
        background: VI.text, color: VI.bg, border: 0, borderRadius: 2,
        fontFamily: VI.fontMono, fontSize: 10,
        letterSpacing: '0.16em', textTransform: 'uppercase',
      }}>Retry</button>
    </div>
  );
}

function Shell() {
  const [species, setSpecies] = React.useState(null);
  const [loadError, setLoadError] = React.useState(null);

  // view: home | search | collection | detail | dive
  const [view, setView] = React.useState('home');
  // The previous tab so back-from-detail returns to the right place
  const [tab, setTab] = React.useState('home');
  const [fish, setFish] = React.useState(null);
  const [searchInitialWater, setSearchInitialWater] = React.useState(null);

  const facets = React.useMemo(() => species ? computeFacets(species) : null, [species]);

  const load = React.useCallback(() => {
    setLoadError(null);
    setSpecies(null);
    fetchSpecies()
      .then(setSpecies)
      .catch((e) => setLoadError(e.message));
  }, []);

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

  if (loadError) return <ErrorScreen message={loadError} onRetry={load}/>;
  if (!species) return <LoadingScreen/>;

  const open = (f) => { setFish(f); setView('detail'); };
  const onTab = (k) => {
    setTab(k);
    setView(k);
  };

  const showTabBar = view === 'home' || view === 'collection';

  return (
    <>
      <div style={{
        width: '100%', minHeight: '100dvh',
        position: 'relative',
      }}>
        {view === 'home' && (
          <AHome
            species={species}
            facets={facets}
            onOpen={open}
            onSearch={() => setView('search')}
            onBrowseWater={(water) => { setSearchInitialWater(water); setView('search'); }}
            onDive={() => setView('dive')}
          />
        )}
        {view === 'search' && (
          <ASearch
            species={species}
            facets={facets}
            initialWater={searchInitialWater}
            onClose={() => { setSearchInitialWater(null); setView(tab); }}
            onOpen={open}
          />
        )}
        {view === 'collection' && (
          <ACollection
            species={species}
            onOpen={open}
            onBrowse={() => { setTab('home'); setView('home'); }}
          />
        )}
        {view === 'detail' && fish && (
          <ADetail
            fish={fish}
            species={species}
            onBack={() => setView(tab)}
            onOpen={open}
          />
        )}
        {showTabBar && <ATabBar active={tab} onChange={onTab} />}
      </div>
      {view === 'dive' && (
        <DiveIn
          species={species}
          intensity="strong"
          onClose={() => setView(tab)}
          onOpen={open}
        />
      )}
    </>
  );
}

function App() {
  return (
    <div className="school-app">
      <SaveProvider>
        <Shell/>
      </SaveProvider>
    </div>
  );
}

function mount() {
  if (!window.AHome || !window.ASearch || !window.ADetail || !window.ACollection ||
      !window.DiveIn || !window.SaveProvider || !window.fetchSpecies) {
    setTimeout(mount, 30);
    return;
  }
  ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
}
mount();
