/* App shell — hash-based routing + mobile-first responsive layout.
   Routes: home, predict, dashboard (public), admin (full-screen). */

function useHashRoute() {
  const get = () => {
    const h = (window.location.hash || '').replace(/^#\/?/, '');
    if (h === 'predict')   return 'predict';
    if (h === 'dashboard') return 'dashboard';
    if (h === 'admin' || h.startsWith('admin/')) return 'admin';
    return 'home';
  };
  const [route, setRoute] = useState(get());
  useEffect(() => {
    const fn = () => setRoute(get());
    window.addEventListener('hashchange', fn);
    return () => window.removeEventListener('hashchange', fn);
  }, []);
  const nav = (to) => {
    window.location.hash = `#/${to === 'home' ? '' : to}`;
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  return [route, nav];
}

function ResponsiveStyles() {
  return (
    <style>{`
      /* ── Grid breakpoints ── */
      @media (max-width: 920px) {
        .hero-grid       { grid-template-columns: 1fr !important; gap: 20px !important; }
        .step-grid       { grid-template-columns: repeat(2, 1fr) !important; }
        .dash-grid       { grid-template-columns: 1fr !important; }
        .topstats-grid   { grid-template-columns: repeat(2, 1fr) !important; }
        .open-matches    { display: flex !important; gap: 12px; overflow-x: auto; scroll-snap-type: x mandatory; padding: 4px 4px 16px; }
        .open-matches::-webkit-scrollbar { display: none; }
        .open-matches > * { flex: 0 0 84%; max-width: 320px; scroll-snap-align: start; }
        .admin-2col      { grid-template-columns: 1fr !important; }
      }
      @media (min-width: 921px) {
        .open-matches { display: grid !important; grid-template-columns: repeat(3, 1fr); gap: 18px; }
      }
      @media (max-width: 720px) {
        .step-grid       { grid-template-columns: 1fr 1fr !important; gap: 10px !important; }
        .rules-grid      { grid-template-columns: 1fr !important; }
        .form-grid       { grid-template-columns: 1fr !important; gap: 12px !important; }
        .pick-grid       { grid-template-columns: 1fr !important; gap: 10px !important; }
        .topstats-grid   { grid-template-columns: 1fr 1fr !important; gap: 10px !important; }
        .outlet-row      { grid-template-columns: 90px 1fr 48px !important; gap: 8px !important; }
        .match-row       { padding: 14px 12px 10px !important; }
        /* Compact page-band on mobile */
        .page-band-inner { padding: 20px 16px 16px !important; }
        /* Tighten section paddings */
        section          { padding-left: 0 !important; padding-right: 0 !important; }
      }
      @media (max-width: 480px) {
        .step-grid       { grid-template-columns: 1fr !important; gap: 10px !important; }
        .pick-grid       { grid-template-columns: repeat(3, 1fr) !important; }
        /* Hero title shrink */
        .hero-title      { font-size: 36px !important; }
      }

      /* ── Ticker compact on mobile ── */
      @media (max-width: 600px) {
        .ticker-track    { gap: 28px !important; animation-duration: 28s !important; }
      }

      /* ── Nav compact on mobile ── */
      @media (max-width: 720px) {
        .nav-inner       { padding-top: 10px !important; padding-bottom: 10px !important; }
      }

      /* ── Fix pick buttons on narrow mobile — keep 3-column ── */
      @media (max-width: 380px) {
        .pick-grid       { gap: 6px !important; }
      }

      /* ── Footer compact ── */
      @media (max-width: 720px) {
        footer           { margin-top: 40px !important; }
        .footer-inner    { flex-direction: column !important; gap: 12px !important; text-align: left !important; }
        .footer-links    { text-align: left !important; }
      }
    `}</style>
  );
}

function PublicShell({ route, nav, children }) {
  return (
    <div data-screen-label={
      route === 'predict' ? 'Predict' :
      route === 'dashboard' ? 'Live Stats' : 'Home'
    } className="has-bottom-nav-mobile" style={{ minHeight: '100vh' }}>
      <ResponsiveStyles />
      <style>{`
        @media (max-width: 720px) {
          .has-bottom-nav-mobile { padding-bottom: calc(60px + env(safe-area-inset-bottom)); }
        }
      `}</style>
      <MatchTicker matches={MATCHES} />
      <Nav route={route} onNav={nav} />
      {children}
      <Footer />
      <BottomNav route={route} onNav={nav} />
      {/* Floating admin link in the corner — discreet */}
      <button onClick={() => nav('admin')} title="Admin login" style={{
        position: 'fixed', right: 14, bottom: 78, zIndex: 35,
        background: 'var(--ink)', color: 'var(--orange)', border: 'none',
        padding: '10px 14px', fontSize: 11, letterSpacing: '0.16em', textTransform: 'uppercase', fontWeight: 800,
        fontFamily: "'Nunito', sans-serif",
        boxShadow: '0 4px 12px rgba(241,86,35,0.35)',
        borderRadius: 6,
        cursor: 'pointer',
      }}>Admin</button>
    </div>
  );
}

function useLiveMatches() {
  const [, forceUpdate] = React.useReducer(x => x + 1, 0);

  useEffect(() => {
    let active = true;

    async function refresh() {
      try {
        const res = await fetch('/api/matches');
        if (!res.ok || !active) return;
        const data = await res.json();
        if (!Array.isArray(data.matches) || data.matches.length === 0) return;

        // Rebuild match objects (kickoffAt must be a Date; API sends kickoffMs)
        const updated = data.matches.map(m => ({
          ...m,
          kickoffAt: new Date(m.kickoffMs),
        }));

        // Mutate the shared MATCHES array in-place — all components re-read it
        window.MATCHES.splice(0, window.MATCHES.length, ...updated);
        if (active) forceUpdate();
      } catch (_) { /* keep static data on network error */ }
    }

    refresh();
    const timer = setInterval(refresh, 5 * 60 * 1000); // re-fetch every 5 min
    return () => { active = false; clearInterval(timer); };
  }, []);
}

function App() {
  const [route, nav] = useHashRoute();
  useLiveMatches();

  if (route === 'admin') {
    return (
      <div data-screen-label="Admin">
        <AdminApp onLeave={() => nav('home')} />
      </div>
    );
  }

  return (
    <PublicShell route={route} nav={nav}>
      {route === 'home'      && <HomePage onNav={nav} />}
      {route === 'predict'   && <PredictPage />}
      {route === 'dashboard' && <DashboardPage />}
    </PublicShell>
  );
}

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