// AdminApp.jsx — admin router shell. Hash routes to section components.
// Sections register themselves on window and are listed in ADMIN_SECTIONS below.

const { useState, useEffect } = React;

const ADMIN_SECTIONS = [
  { path: '',           label: 'Events',       component: 'EventsSection' },
  { path: 'posts',      label: 'Field Notes',  component: 'PostsSection' },
  { path: 'roster',     label: 'Roster',       component: 'RosterSection' },
  { path: 'features',   label: 'Features',     component: 'FeaturesSection' },
  { path: 'stats',      label: 'Stats Import', component: 'StatsImportSection' },
  { path: 'scorecards', label: 'Scorecards',   component: 'ScorecardImportSection' },
  { path: 'merch',      label: 'Merch',        component: 'MerchSection' },
];

const useRoute = () => {
  const [route, setRoute] = useState(() => (location.hash.replace('#/', '').replace('#', '') || ''));
  useEffect(() => {
    const onHash = () => {
      setRoute(location.hash.replace('#/', '').replace('#', '') || '');
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);
  return route;
};

const AdminHeader = ({ route }) => {
  const [email, setEmail] = useState('');
  useEffect(() => {
    // /whoami is a Pages Function; 404 locally and in non-Access deploys.
    fetch('/whoami', { headers: { Accept: 'application/json' } })
      .then(r => r.ok ? r.json() : null)
      .then(data => { if (data && data.email) setEmail(data.email); })
      .catch(() => {});
  }, []);
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 80,
      background: 'rgba(11,11,12,0.92)',
      backdropFilter: 'blur(8px)',
      borderBottom: '1px solid var(--border)',
    }}>
      <div className="wrap" style={{
        padding: '14px 24px',
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24, flexWrap: 'wrap',
      }}>
        <a href="#/" style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none' }}>
          <img src={`${window.ASSETS}brand/wordmark.png`} alt="Warped BBQ" style={{ height: 30 }} />
          <span style={{ fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.18em', color: 'var(--wbbq-slime)', border: '2px solid var(--wbbq-slime)', padding: '4px 10px' }}>ADMIN</span>
        </a>
        <nav className="admin-nav" style={{ display: 'flex', gap: 4, fontFamily: 'var(--font-display)', fontSize: 11, letterSpacing: '0.12em', textTransform: 'uppercase', flexWrap: 'wrap' }}>
          {ADMIN_SECTIONS.map((s) => {
            const active = route === s.path;
            return (
              <a key={s.path} href={`#/${s.path}`} style={{
                color: active ? 'var(--wbbq-black)' : 'var(--fg1)',
                background: active ? 'var(--wbbq-flame)' : 'transparent',
                textDecoration: 'none',
                padding: '8px 12px',
                border: '2px solid ' + (active ? 'var(--wbbq-flame)' : 'var(--border)'),
              }}>{s.label}</a>
            );
          })}
        </nav>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)' }}>
          <span>{email || 'Authenticated via Cloudflare'}</span>
          <span style={{ marginLeft: 10 }}>· <a href="https://compteam.warpedbbq.com" target="_blank" rel="noreferrer" style={{ color: 'var(--wbbq-blue)', textDecoration: 'none' }}>↗ public site</a></span>
        </div>
      </div>
    </header>
  );
};

const AdminFooter = () => (
  <footer style={{
    borderTop: '2px solid var(--border)',
    padding: '24px',
    marginTop: 60,
    fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)',
    textAlign: 'center',
  }}>
    WARPED BBQ · ADMIN v2 · ACCESS-GATED · Built by <a href="https://warpedtechnologies.io" target="_blank" rel="noreferrer" style={{ color: 'var(--wbbq-blue)', textDecoration: 'none' }}>Warped Technologies</a>
  </footer>
);

const AdminApp = () => {
  const route = useRoute();
  // Docs routes (e.g. #/docs/ADMIN_SETUP.md) still render via DocsPage when loaded.
  let SectionComponent;
  if (route.startsWith('docs/') && window.DocsPage) {
    SectionComponent = window.DocsPage;
  } else {
    const match = ADMIN_SECTIONS.find(s => s.path === route) || ADMIN_SECTIONS[0];
    SectionComponent = window[match.component];
  }

  const [banner, setBanner] = useState(null);

  // Pull store credentials from /api/config on first mount. The Pages Function
  // checks Cloudflare Access headers server-side, so this only succeeds for
  // allowlisted users. Sets each store's URL+password and kicks off a refresh.
  useEffect(() => {
    let cancelled = false;
    fetch('/api/config', { headers: { Accept: 'application/json' } })
      .then(r => r.ok ? r.json() : Promise.reject(new Error(`/api/config ${r.status}`)))
      .then(cfg => {
        if (cancelled || !cfg) return;
        if (cfg.events && window.EventsStore && cfg.events.url && cfg.events.password) {
          window.EventsStore.configure(cfg.events.url, cfg.events.password);
          window.EventsStore.refresh().catch(() => {});
        }
        if (cfg.posts && window.PostsStore && cfg.posts.password) {
          window.PostsStore.configure('', cfg.posts.password);
          window.PostsStore.refresh().catch(() => {});
        }
        if (cfg.roster && window.RosterStore && cfg.roster.url && cfg.roster.password) {
          window.RosterStore.configure(cfg.roster.url, cfg.roster.password);
          window.RosterStore.refresh().catch(() => {});
        }
      })
      .catch(() => { /* local dev / no function deployed — fall back to manual forms */ });
    return () => { cancelled = true; };
  }, []);

  if (!SectionComponent) {
    return (
      <>
        <AdminHeader route={route} />
        <main className="wrap" style={{ padding: '60px 24px', minHeight: '60vh' }}>
          <h1 style={{ fontFamily: 'var(--font-display)', color: 'var(--wbbq-flame)' }}>Section not loaded</h1>
          <p style={{ color: 'var(--fg2)' }}>Expected <code>{ADMIN_SECTIONS.find(s => s.path === route)?.component || route}</code> on window.</p>
        </main>
      </>
    );
  }

  return (
    <>
      <AdminHeader route={route} />
      <main style={{ minHeight: '70vh' }}>
        <section className="section">
          <div className="wrap" style={{ maxWidth: 960, paddingTop: 40 }}>
            <Banner banner={banner} onClose={() => setBanner(null)} />
            <SectionComponent onBanner={setBanner} />
          </div>
        </section>
      </main>
      <AdminFooter />
    </>
  );
};

window.AdminApp = AdminApp;
