/* global React, ReactDOM */
const { useState, useEffect, useRef, useCallback } = React;

/* ====================================================================
   NAV — sticky, with working dropdowns and route highlighting
   ==================================================================== */
function Nav({ current, onNavigate }) {
  const [openMenu, setOpenMenu] = useState(null);
  const closeTimer = useRef(null);

  const hover = (key) => {
    clearTimeout(closeTimer.current);
    setOpenMenu(key);
  };
  const leave = () => {
    closeTimer.current = setTimeout(() => setOpenMenu(null), 150);
  };

  const go = (page) => (e) => {
    if (e) e.preventDefault();
    setOpenMenu(null);
    onNavigate(page);
  };

  const items = [
    { key: 'about',      label: 'About' },
    { key: 'philosophy', label: 'Philosophy' },
    { key: 'analysis',   label: 'Analysis',
      menu: [
        { label: 'All written pieces', page: 'analysis' },
        { label: 'Arsenal 0–2 City · EFL Cup Final', page: 'analysis', piece: 'city' },
        { label: 'John Stones · CL Final 2023', page: 'analysis', piece: 'stones' },
      ]},
    { key: 'visuals',    label: 'Visuals' },
    { key: 'data',       label: 'Data' },
    { key: 'contact',    label: 'Contact',
      menu: [
        { label: 'Email',    href: 'mailto:jaydon.coombs-goodfellow@outlook.com' },
        { label: 'LinkedIn', href: 'https://www.linkedin.com/in/jaydoncoombsgoodfellow/' },
      ]},
  ];

  return (
    <header className="nav">
      <div className="nav-inner">
        <a className="nav-brand" href="#" onClick={go('home')}>
          <span className="nav-brand-mark"></span>
          Jaydon Coombs-Goodfellow
        </a>
        <ul className="nav-links">
          {items.map(it => {
            const hasMenu = !!it.menu;
            const isOpen = openMenu === it.key;
            const isCurrent = current === it.key;
            return (
              <li
                key={it.key}
                className={'nav-item ' + (hasMenu ? 'has-menu ' : '') + (isOpen ? 'is-open' : '')}
                onMouseEnter={hasMenu ? () => hover(it.key) : undefined}
                onMouseLeave={hasMenu ? leave : undefined}
              >
                <a
                  href={it.key === 'contact' ? '#' : '#'}
                  className={isCurrent ? 'is-current' : ''}
                  onClick={(e) => {
                    e.preventDefault();
                    if (it.key === 'contact') {
                      // Contact: toggle dropdown on click (tap), never navigate to a page
                      setOpenMenu(openMenu === it.key ? null : it.key);
                      return;
                    }
                    go(it.key)(e);
                  }}
                >
                  {it.label}{hasMenu ? <span className="caret-down"> ▾</span> : null}
                </a>
                {hasMenu && (
                  <div className="nav-dropdown">
                    {it.menu.map((m, i) => (
                      m.href ? (
                        <a
                          key={i}
                          href={m.href}
                          target={m.href.startsWith('http') ? '_blank' : undefined}
                          rel={m.href.startsWith('http') ? 'noopener noreferrer' : undefined}
                          className="nav-dropdown-item"
                          onClick={() => setOpenMenu(null)}
                        >{m.label}</a>
                      ) : (
                        <a key={i} href="#" className="nav-dropdown-item" onClick={(e)=>{e.preventDefault();setOpenMenu(null);onNavigate(m.page, {piece: m.piece});}}>{m.label}</a>
                      )
                    ))}
                  </div>
                )}
              </li>
            );
          })}
        </ul>
      </div>
    </header>
  );
}

/* ====================================================================
   HOME — Hero + section grid + featured preview
   ==================================================================== */
function Hero({ onNavigate }) {
  return (
    <section className="hero">
      <div className="hero-inner">
        <span className="hero-eyebrow" style={{ '--d': '0ms' }}>Football Analysis Portfolio</span>
        <h1 style={{ '--d': '80ms' }}>Where the <span className="accent">eye test</span> meets the data.</h1>
        <p className="hero-lead" style={{ '--d': '180ms' }}>Tactical and statistical analysis of Manchester City, built from free public data, clean pitch visuals, and a football-first reading of the game.</p>
        <div className="hero-cta" style={{ '--d': '260ms' }}>
          <a className="btn btn-primary" href="#" onClick={(e)=>{e.preventDefault();onNavigate('analysis');}}>View my work</a>
          <a className="btn btn-secondary" href="#" onClick={(e)=>{e.preventDefault();onNavigate('about');}}>About me</a>
        </div>
        <div className="hero-meta" style={{ '--d': '360ms' }}>
          <span className="hero-meta-item"><span className="dot-indicator"></span> Portfolio live</span>
          <span className="hero-meta-item"><strong>2</strong> match pieces</span>
          <span className="hero-meta-item"><strong>22</strong> custom visuals</span>
          <span className="hero-meta-item">Built in Python</span>
        </div>
      </div>
    </section>
  );
}

function SectionGrid({ onNavigate }) {
  const sections = [
    ['01 · About',      'about',      'About me',             'Who I am, what I do, and what I am looking for next.'],
    ['02 · Philosophy', 'philosophy', 'Football philosophy',  'The football I find most interesting, and the principles I look for when I watch a team.'],
    ['03 · Analysis',   'analysis',   'Written pieces',       'Full match analyses, grounded in data and tactical reading.'],
    ['04 · Visuals',    'visuals',    'Visual work',          'Featured charts and the full library of 22 visuals across two matches.'],
    ['05 · Data',       'data',       'Data methodology',     'Where the numbers come from, and how I process them.'],
  ];
  return (
    <section className="block">
      <div className="block-inner">
        <span className="eyebrow">Explore</span>
        <h2 className="section-h2">Pick a section.</h2>
        <p className="section-lead">The portfolio is organised into five sections. Start wherever you like.</p>
        <div className="section-grid">
          {sections.map(([e, page, t, p], i) => (
            <a className="section-card reveal" style={{ '--d': `${i * 70}ms` }} key={e}
               href="#" onClick={(ev)=>{ev.preventDefault();onNavigate(page);}}>
              <span className="eyebrow-sm">{e}</span>
              <h3>{t}</h3>
              <p>{p}</p>
              <span className="card-arrow">→</span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

function HomePiecesPreview({ onNavigate }) {
  return (
    <section className="block" style={{ background: 'linear-gradient(180deg,#111A2E 0%,#0B1426 100%)' }}>
      <div className="block-inner">
        <span className="eyebrow">Latest Analysis</span>
        <h2 className="section-h2">Two match pieces so far.</h2>
        <div className="pieces-grid">
          <a className="piece-card reveal" style={{ '--d': '0ms' }} href="#" onClick={(e)=>{e.preventDefault();onNavigate('analysis');}}>
            <div className="piece-card-image"><img src="./assets/visuals/city/05_avg_positions_both.png" alt="" /></div>
            <div className="piece-card-content">
              <div className="piece-card-meta"><span>Match analysis</span><span>22 Mar 2026</span></div>
              <h3>Arsenal 0–2 Manchester City · EFL Cup Final</h3>
              <p>How a 4-2-4 block made Arsenal's build-up impossible, why Hincapié was always the target, and the left-back who scored twice by not playing like one.</p>
              <span className="piece-card-cta">Read the full piece →</span>
            </div>
          </a>
          <a className="piece-card reveal" style={{ '--d': '120ms' }} href="#" onClick={(e)=>{e.preventDefault();onNavigate('analysis');}}>
            <div className="piece-card-image"><img src="./assets/visuals/stones/04_stones_xt_zones.png" alt="" /></div>
            <div className="piece-card-content">
              <div className="piece-card-meta"><span>Match analysis</span><span>10 Jun 2023</span></div>
              <h3>John Stones · Champions League Final · Inter vs Manchester City</h3>
              <p>The centre-back who played as a midfielder for 82 minutes. How Guardiola's 3-2-4-1 overload was engineered.</p>
              <span className="piece-card-cta">Read the full piece →</span>
            </div>
          </a>
        </div>
      </div>
    </section>
  );
}

/* ====================================================================
   FOOTER
   ==================================================================== */
function Footer({ onNavigate }) {
  return (
    <footer className="site-footer">
      <div className="site-footer-inner">
        <div>
          <h3>Jaydon Coombs-Goodfellow</h3>
          <p>Football analysis portfolio. Open to conversations about coaching, performance analysis, scouting, and anything else inside the game.</p>
          <div className="footer-links">
            <a href="#" onClick={(e)=>{e.preventDefault();onNavigate('about');}}>About</a>
            <a href="#" onClick={(e)=>{e.preventDefault();onNavigate('philosophy');}}>Philosophy</a>
            <a href="#" onClick={(e)=>{e.preventDefault();onNavigate('analysis');}}>Analysis</a>
            <a href="#" onClick={(e)=>{e.preventDefault();onNavigate('visuals');}}>Visuals</a>
            <a href="#" onClick={(e)=>{e.preventDefault();onNavigate('data');}}>Data</a>
          </div>
        </div>
        <div className="site-footer-cta">
          <span className="eyebrow-sm" style={{ display: 'block', marginBottom: '0.7rem' }}>Get in touch</span>
          <div style={{ display: 'flex', gap: '0.7rem', justifyContent: 'flex-end' }}>
            <a className="btn btn-primary" href="mailto:jaydon.coombs-goodfellow@outlook.com">Email me</a>
            <a className="btn btn-secondary" href="https://www.linkedin.com/in/jaydoncoombsgoodfellow/" target="_blank" rel="noopener noreferrer">LinkedIn</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ====================================================================
   APP — SPA router with per-page intros
   ==================================================================== */
function App() {
  // Read initial route from URL hash (supports reloads on specific pages)
  const readHash = () => {
    const h = (window.location.hash || '').replace(/^#\/?/, '');
    const valid = ['home','about','philosophy','analysis','visuals','data'];
    return valid.includes(h) ? h : 'home';
  };
  const [page, setPage] = useState(readHash());
  const [introDone, setIntroDone] = useState(false);
  const [introKey, setIntroKey] = useState(0); // bump to replay
  const [navPayload, setNavPayload] = useState(null);
  const firstLoad = useRef(true);

  // On route change: reset intro, scroll to top, update hash
  const navigate = useCallback((newPage, payload) => {
    setNavPayload(payload || null);
    if (newPage === page) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
      // still tell the page a payload came in
      window.dispatchEvent(new CustomEvent('jcg:nav', { detail: { page: newPage, payload } }));
      return;
    }
    setPage(newPage);
    setIntroDone(false);
    setIntroKey((k) => k + 1);
    window.scrollTo({ top: 0, behavior: 'auto' });
    window.location.hash = '#/' + newPage;
  }, [page]);

  // Wire navigate globally so Pages.jsx can call window.navigate
  useEffect(() => {
    window.navigate = navigate;
  }, [navigate]);

  // Handle back/forward
  useEffect(() => {
    const onHash = () => {
      const h = readHash();
      if (h !== page) {
        setPage(h);
        setIntroDone(false);
        setIntroKey((k) => k + 1);
        window.scrollTo({ top: 0, behavior: 'auto' });
      }
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, [page]);

  // Keyboard: R replays the intro for the current page
  useEffect(() => {
    const onKey = (e) => {
      if ((e.key === 'r' || e.key === 'R') && !e.metaKey && !e.ctrlKey && !e.altKey) {
        const tag = (e.target && e.target.tagName) || '';
        if (tag === 'INPUT' || tag === 'TEXTAREA') return;
        setIntroDone(false);
        setIntroKey((k) => k + 1);
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  // Pick the right intro + page content
  const IntroForPage = {
    home:       window.PitchIntro,
    about:      window.AboutIntro,
    philosophy: window.PhilosophyIntro,
    analysis:   window.AnalysisIntro,
    visuals:    window.VisualsIntro,
    data:       window.DataIntro,
  }[page] || window.PitchIntro;

  // Safety: if for any reason the intro component is missing, skip straight to content
  useEffect(() => {
    if (!introDone && !IntroForPage) {
      const t = setTimeout(() => setIntroDone(true), 50);
      return () => clearTimeout(t);
    }
  }, [introDone, IntroForPage]);

  const PageContent = {
    home:       HomeContent,
    about:      window.AboutPage,
    philosophy: window.PhilosophyPage,
    analysis:   window.AnalysisPage,
    visuals:    window.VisualsPage,
    data:       window.DataPage,
  }[page] || HomeContent;

  // After first intro, mark firstLoad false
  useEffect(() => {
    if (introDone) firstLoad.current = false;
  }, [introDone]);

  return (
    <>
      {!introDone && IntroForPage && (
        <IntroForPage key={introKey} onDone={() => setIntroDone(true)} />
      )}
      {!introDone && (
        <button className="intro-skip" onClick={() => setIntroDone(true)}>Skip intro →</button>
      )}
      <div className={introDone ? 'site site-in' : 'site site-out'}>
        <Nav current={page} onNavigate={navigate} />
        <main key={page} className="page-fade">
          <PageContent onNavigate={navigate} payload={navPayload} />
        </main>
        <Footer onNavigate={navigate} />
        <div className="replay-hint">Press <kbd>R</kbd> to replay intro</div>
      </div>
    </>
  );
}

/* Home content wrapper so <PageContent> is uniform */
function HomeContent({ onNavigate }) {
  return (
    <>
      <Hero onNavigate={onNavigate} />
      <SectionGrid onNavigate={onNavigate} />
      <HomePiecesPreview onNavigate={onNavigate} />
    </>
  );
}

Object.assign(window, { App, Nav, Hero, SectionGrid, HomePiecesPreview, Footer });
