// Main app — page state + composition
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "primaryHue": 25,
  "displayCaps": true,
  "stripeMotif": true,
  "tickerOn": true
}/*EDITMODE-END*/;

const App = () => {
  const [page, setPage] = React.useState('home');
  const [team, setTeam] = React.useState('mens');
  const [scrolled, setScrolled] = React.useState(false);
  const [selectedFixture, setSelectedFixture] = React.useState(null);

  const navigate = (p) => { setSelectedFixture(null); setPage(p); };
  const openFixture = (f) => { setSelectedFixture(f); setPage('match'); };
  const [tweaks, setTweak] = useTweaks ? useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];
  const t = Array.isArray(tweaks) ? tweaks[0] : tweaks;
  const setT = Array.isArray(tweaks) ? tweaks[1] : setTweak;

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' });
  }, [page, selectedFixture]);

  // Apply tweaks to CSS vars
  React.useEffect(() => {
    if (t.primaryHue === 25) {
      // Default — use the literal brand crimson
      document.documentElement.style.setProperty('--red', '#C8102E');
      document.documentElement.style.setProperty('--red-deep', '#9B0B22');
    } else {
      document.documentElement.style.setProperty('--red', `oklch(0.55 0.18 ${t.primaryHue})`);
      document.documentElement.style.setProperty('--red-deep', `oklch(0.45 0.18 ${t.primaryHue})`);
    }
  }, [t.primaryHue]);

  const renderPage = () => {
    switch (page) {
      case 'home':
        return (
          <>
            <Hero setPage={navigate} />
            <FixturesSection onSelectFixture={openFixture} />
            <FormationSection />
            <TeamsSection team={team} setTeam={(id) => { setTeam(id); navigate('teams'); }} />
            <GallerySection />
            <SponsorsSection />
          </>
        );
      case 'fixtures':
        return (
          <>
            <PageHeader kicker="2025/26 Season" title="Fixtures, Results & Form" />
            <FixturesSection onSelectFixture={openFixture} />
            <MatchCentre />
          </>
        );
      case 'match':
        return <MatchDetail fixture={selectedFixture} onBack={() => navigate('fixtures')} />;
      case 'teams':
        return (
          <>
            <PageHeader kicker="Our Teams" title={team === 'mens' ? "Men's First Team" : team === 'womens' ? "Women's First Team" : "Junior Section"} />
            <TeamsSection team={team} setTeam={setTeam} />
            {team === 'juniors' ? <JuniorGrid /> : <SquadGrid team={team} />}
          </>
        );
      case 'matchcentre':
        return (
          <>
            <PageHeader kicker="Match Centre" title="Reports, Stats & Photos" />
            <MatchCentre />
            <GallerySection />
          </>
        );
      case 'community':
        return (
          <>
            <PageHeader kicker="Join Us" title="Players, Parents, Coaches, Volunteers." />
            <CommunitySection />
            <JuniorGrid />
          </>
        );
      case 'sponsors':
        return (
          <>
            <PageHeader kicker="Backed By" title="Sponsors of Blackpool Wren Rovers FC" />
            <SponsorsSection />
          </>
        );
      default: return null;
    }
  };

  return (
    <div data-screen-label={page}>
      {t.tickerOn && <Ticker />}
      <Nav page={page} setPage={navigate} scrolled={scrolled} />
      <main>{renderPage()}</main>
      <Footer setPage={navigate} />

      {/* Tweaks panel */}
      {typeof TweaksPanel !== 'undefined' && (
        <TweaksPanel title="Tweaks">
          <TweakSection title="Identity">
            <TweakSlider label="Primary hue" value={t.primaryHue} min={0} max={360} step={1}
              onChange={(v) => setT('primaryHue', v)} />
          </TweakSection>
          <TweakSection title="Chrome">
            <TweakToggle label="Show news ticker" value={t.tickerOn} onChange={(v) => setT('tickerOn', v)} />
            <TweakToggle label="Stripe dividers" value={t.stripeMotif} onChange={(v) => setT('stripeMotif', v)} />
          </TweakSection>
          <TweakSection title="Quick jump">
            <TweakButton onClick={() => setPage('home')}>Home</TweakButton>
            <TweakButton onClick={() => { setTeam('mens'); setPage('teams'); }}>Men's Squad</TweakButton>
            <TweakButton onClick={() => { setTeam('womens'); setPage('teams'); }}>Women's Squad</TweakButton>
            <TweakButton onClick={() => { setTeam('juniors'); setPage('teams'); }}>Juniors</TweakButton>
            <TweakButton onClick={() => setPage('matchcentre')}>Match Centre</TweakButton>
            <TweakButton onClick={() => setPage('community')}>Join Us</TweakButton>
            <TweakButton onClick={() => setPage('sponsors')}>Sponsors</TweakButton>
          </TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
};

const PageHeader = ({ kicker, title }) => {
  // Pick a few players to show as photo strip
  const showcase = (title.toLowerCase().includes("women") ? WOMENS_SQUAD : MENS_SQUAD).slice(0, 6);
  return (
  <section style={{
    background: 'var(--ink)', color: '#fff', padding: '64px 0 0',
    position: 'relative', overflow: 'hidden',
  }}>
    <div style={{
      position: 'absolute', right: -80, top: -80, width: 320, height: 320,
      background: 'var(--red)', transform: 'rotate(45deg)', opacity: 0.5,
    }} />
    <div className="container" style={{ position: 'relative' }}>
      <div className="mono" style={{ fontSize: 11, letterSpacing: '0.22em', color: 'var(--red)', fontWeight: 700 }}>
        ▸ {kicker.toUpperCase()}
      </div>
      <h1 data-page-head-h1 className="display" style={{
        fontSize: 'clamp(40px, 8vw, 120px)', margin: '12px 0 24px', lineHeight: 0.92, textTransform: 'uppercase',
      }}>{title}</h1>

      {/* Player photo strip — only on Teams pages */}
      {kicker.toLowerCase().includes("our teams") && (
        <div data-page-header-strip style={{
          display: 'grid', gridTemplateColumns: `repeat(${showcase.length}, 1fr)`, gap: 0,
          marginTop: 28, position: 'relative', zIndex: 2,
        }}>
          {showcase.map((p, i) => (
            <div key={p.no} style={{
              position: 'relative', aspectRatio: '3/4',
              transform: `translateY(${i % 2 === 0 ? 12 : 0}px)`,
              filter: 'drop-shadow(0 -10px 20px rgba(0,0,0,0.5))',
            }}>
              <div style={{
                position: 'absolute', inset: 0,
                clipPath: 'polygon(0 0, 100% 0, 100% 88%, 50% 100%, 0 88%)',
                background: 'linear-gradient(180deg, #1A0608 0%, #0E0F12 100%)',
                overflow: 'hidden',
              }}>
                <PlayerPortrait player={p} team={title.toLowerCase().includes("women") ? "womens" : "mens"} size={260} />
                <div style={{
                  position: 'absolute', inset: 0,
                  background: 'linear-gradient(180deg, transparent 50%, rgba(14,15,18,0.85) 100%)',
                }} />
                <div style={{
                  position: 'absolute', bottom: 18, left: 0, right: 0, textAlign: 'center',
                }}>
                  <div className="display" style={{ fontSize: 28, color: '#fff', lineHeight: 0.9 }}>
                    {p.name.split(' ').slice(-1)[0].toUpperCase()}
                  </div>
                  <div className="mono" style={{ fontSize: 9.5, letterSpacing: '0.2em', color: 'var(--red)', marginTop: 4, fontWeight: 700 }}>
                    #{p.no} · {p.pos}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
    <StripeRule height={5} />
  </section>
  );
};

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