/* global React */
// Shared FEA components — Header, Footer, Hero, Placeholder, Cards, CTA strip.
// Components export to window so other Babel-transpiled files can use them.

const { useState, useEffect } = React;

// ---------- Router helpers (hash-based) ----------
function parseHash() {
  const raw = (window.location.hash || "#/").replace(/^#/, "");
  // Split path parts from the query string so e.g. "/apply?section=jpl"
  // resolves first === "apply" (the query is still available via `raw`).
  const path = raw.split("?")[0];
  const parts = path.split("/").filter(Boolean);
  return { parts, raw };
}
function go(path) {
  window.location.hash = path.startsWith("#") ? path : "#" + (path.startsWith("/") ? path : "/" + path);
  window.scrollTo({ top: 0, behavior: "instant" });
}
function useRoute() {
  const [route, setRoute] = useState(parseHash());
  useEffect(() => {
    const on = () => {setRoute(parseHash()); window.scrollTo({ top: 0, behavior: "instant" });};
    window.addEventListener("hashchange", on);
    return () => window.removeEventListener("hashchange", on);
  }, []);
  return route;
}

// ---------- Placeholder image with shot brief ----------
function Placeholder({ brief, aspect = "16/9", tag = "PHOTO", style }) {
  return (
    <div className="ph" style={{ aspectRatio: aspect, ...style }}>
      <div className="ph-corner">{tag}</div>
      <div className="ph-label">
        <span className="pin">SHOT BRIEF</span>
        <span>{brief}</span>
      </div>
    </div>);

}

// ---------- Header with top nav ----------
function Header({ sections, currentSectionId }) {
  const [open, setOpen] = useState(false);
  const route = useRoute();
  const first = route.parts[0] || "";
  useEffect(() => {
    const close = () => setOpen(false);
    window.addEventListener("hashchange", close);
    return () => window.removeEventListener("hashchange", close);
  }, []);
  const currentSection = currentSectionId ? sections.find((s) => s.id === currentSectionId) : null;
  return (
    <header className="site-header">
      <div className="container header-row">
        <a href="#/" className="brand" aria-label="FEA Sports Group home">
          <img src="assets/logo-fea-tiger.webp" alt="Holbeach United FEA" className="brand-badge brand-crest" />
          <div className="brand-wordmark brand-stack">
            <span className="bw-1">Holbeach United</span>
            <span className="bw-2">FEA</span>
          </div>
        </a>

        <nav className={"nav" + (open ? " nav-open" : "")} onClick={(e) => { if (e.target.closest("a")) setOpen(false); }}>
          <a href="#/" className={"nav-link" + (first === "" ? " is-active" : "")}>Home</a>
          <a href="#/about" className={"nav-link" + (first === "about" ? " is-active" : "")}>About</a>
          {sections.filter((s) => s.id !== "scholarship").map((s) =>
          s.id === "college" ?
          <div className="nav-item" key={s.id}>
              <a
              href={"#/" + s.id}
              className={"nav-link" + (["college", "scholarship", "internships", "run-sport"].includes(first) ? " is-active" : "")}>
              
                {s.nav}
                <svg className="caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M6 9l6 6 6-6" /></svg>
              </a>
              <div className="nav-drop">
                <a href="#/scholarship" className={first === "scholarship" ? "is-active" : ""} style={{ ["--nd"]: "#F2A23C" }}><span className="nd-dot" aria-hidden="true"></span>Scholarship</a>
                <a href="#/internships" className={first === "internships" ? "is-active" : ""} style={{ ["--nd"]: "#1F6FE0" }}><span className="nd-dot" aria-hidden="true"></span>Sports Industry Internships</a>
                <a href="#/run-sport" className={first === "run-sport" ? "is-active" : ""} style={{ ["--nd"]: "#34A853" }}><span className="nd-dot" aria-hidden="true"></span>Sports Business</a>
              </div>
            </div> :
          <a
            key={s.id}
            href={"#/" + s.id}
            className={"nav-link" + (first === s.id ? " is-active" : "")}>
            
              {s.nav}
            </a>
          )}
          <a href="#/compete" className={"nav-link" + (first === "compete" ? " is-active" : "")}>Compete</a>
          <a href="#/stories" className={"nav-link" + (first === "stories" ? " is-active" : "")}>Success Stories</a>
          <a href="#/contact" className={"nav-link" + (first === "contact" ? " is-active" : "")}>Contact</a>
        </nav>

        <div className="header-cta">
          <a href="https://forms.gle/qhQPuDfyevaFHpQW7" target="_blank" rel="noopener" className="btn btn-primary">
            Apply Now
            <span className="arrow">→</span>
          </a>
          <button className="menu-toggle" aria-label="Menu" onClick={() => setOpen((v) => !v)}>
            <span className="menu-icon"><span></span></span>
          </button>
        </div>
      </div>
    </header>);

}

// ---------- Section-identity strip ----------
function IdStrip({ section }) {
  if (!section) return null;
  return (
    <div className="id-strip">
      <div className="container id-strip-row">
        {section.logo && <img src={section.logo} className="id-strip-logo" alt="" aria-hidden="true" />}
        <span className="swatch"></span>
        <span>FEA Sports Group</span>
        <span style={{ opacity: 0.4 }}>/</span>
        <span className="now">{section.label}</span>
        {section.sub &&
        <>
            <span style={{ opacity: 0.4 }}>·</span>
            <span style={{ opacity: 0.7 }}>{section.sub}</span>
          </>
        }
        <span style={{ marginLeft: "auto", letterSpacing: "0.2em" }}>{section.num} / 06</span>
      </div>
    </div>);

}

// ---------- Sub-nav under header (when inside a section) ----------
function SubNav({ section, currentPageId }) {
  if (!section || !section.pages || section.pages.length === 0) return null;
  return (
    <div className="subnav">
      <div className="container subnav-row">
        <a
          href={"#/" + section.id}
          className={"subnav-link" + (!currentPageId ? " is-active" : "")}>
          
          Overview
        </a>
        {section.pages.map((p) =>
        <a
          key={p.id}
          href={"#/" + section.id + "/" + p.id}
          className={"subnav-link" + (currentPageId === p.id ? " is-active" : "")}>
          
            {p.label}
          </a>
        )}
      </div>
    </div>);

}

// ---------- Hero ----------
function Hero({ eyebrowNum, eyebrowLabel, title, titleAccent, sub, brief, image, imageFit, stats, primaryCta, secondaryCta }) {
  const cutout = imageFit === "cutout";
  return (
    <section className={"hero" + (cutout ? " hero-cutout" : "")}>
      <div className="hero-media">
        {image ? (
          <img src={image} alt="" className={"hero-img" + (cutout ? " is-cutout" : "")} />
        ) : (
          <Placeholder brief={brief} aspect="auto" style={{ width: "100%", height: "100%" }} tag="HERO" />
        )}
      </div>
      <div className="hero-shade"></div>
      <div className="container hero-inner">
        <div className="hero-eyebrow">
          <span className="dot"></span>
          <span className="eyebrow">
            <span className="num">{eyebrowNum}</span>
            {eyebrowLabel}
          </span>
        </div>
        <h1 className="hero-title">
          {title} {titleAccent && <span className="accent">{titleAccent}</span>}
        </h1>
        {sub && <p className="hero-sub">{sub}</p>}
        {(primaryCta || secondaryCta) &&
        <div className="hero-actions">
            {primaryCta &&
          <a href={primaryCta.href} target={primaryCta.href.startsWith("http")?"_blank":undefined} rel={primaryCta.href.startsWith("http")?"noopener":undefined} className="btn btn-primary">
                {primaryCta.label}
                <span className="arrow">→</span>
              </a>
          }
            {secondaryCta &&
          <a href={secondaryCta.href} className="btn btn-ghost">
                {secondaryCta.label}
              </a>
          }
          </div>
        }
        {stats && stats.length > 0 &&
        <div className="hero-meta">
            {stats.map((s, i) =>
          <div className="stat" key={i}>
                <div className="k">{s.k}</div>
                <div className="v">{s.v}</div>
              </div>
          )}
          </div>
        }
      </div>
    </section>);

}

// ---------- Doorway picture card (homepage) ----------
function Doorway({ section }) {
  return (
    <a
      href={"#/" + section.id}
      className="doorway"
      style={{ ["--accent"]: section.accent, ["--accent-ink"]: section.accentInk }}>

      <img className="doorway-img" src={section.image} alt="" />
      <span className="doorway-scrim" aria-hidden="true"></span>
      <div className="doorway-overlay">
        <div className="doorway-num">/ {section.num}</div>
        <div>
          <div className="doorway-title">{section.label}</div>
          {section.sub && <div className="doorway-sub">{section.sub}</div>}
          <div className="doorway-meta">
            <span>{section.pages.length > 0 ? section.pages.length + " programmes" : "View section"}</span>
            <span className="go">Explore <span className="arrow">→</span></span>
          </div>
        </div>
      </div>
    </a>);

}

// ---------- Sub-page card (section landing) ----------
function SubCard({ section, page, idx }) {
  return (
    <a
      href={"#/" + section.id + "/" + page.id}
      className="subcard">
      
      <div>
        <div className="num">{(idx + 1).toString().padStart(2, "0")}</div>
        <div className="t">{page.label}</div>
        <div className="d">{page.tagline}</div>
      </div>
      <div className="go">Read more <span>→</span></div>
    </a>);

}

// ---------- CTA Strip ----------
function CtaStrip({ heading, body, primary, secondary }) {
  return (
    <section className="cta-strip">
      <div className="container">
        <div className="row">
          <div>
            <h3>{heading}</h3>
            <p style={{ marginTop: 16 }}>{body}</p>
          </div>
          <div className="actions">
            {primary &&
            <a href={primary.href} target={primary.href.startsWith("http")?"_blank":undefined} rel={primary.href.startsWith("http")?"noopener":undefined} className="btn btn-on-light">
                {primary.label} <span className="arrow">→</span>
              </a>
            }
            {secondary &&
            <a href={secondary.href} target={secondary.href.startsWith("http")?"_blank":undefined} rel={secondary.href.startsWith("http")?"noopener":undefined} className="btn btn-ghost" style={{ borderColor: "rgba(0,0,0,0.4)", color: "inherit" }}>
                {secondary.label}
              </a>
            }
          </div>
        </div>
      </div>
    </section>);

}

// ---------- Open Evenings strip ----------
function OpenEvenings() {
  const C = window.FEA_DATA.CONTACT;
  return (
    <section className="open-evenings">
      <div className="container">
        <div className="oe-head">
          <span className="eyebrow"><span className="num">VISIT US</span>Open Evenings · {C.intake} intake</span>
          <h2>Come and see it for yourself.</h2>
          <p className="lede">Limited places available. Book onto an open evening, meet the staff and tour the facilities.</p>
        </div>
        <div className="oe-dates">
          {C.openEvenings.map((e, i) => (
            <div className="oe-date" key={i}>
              <div className="d">{e.day}</div>
              <div className="t">{e.time}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- Footer ----------
function Footer({ sections }) {
  const C = window.FEA_DATA.CONTACT;
  return (
    <footer className="site-footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-lockup">
              HOLBEACH UNITED <span style={{ color: "var(--accent)" }}>FEA</span>
              <span className="sub">FOOTBALL &amp; EDUCATION ACADEMY</span>
            </div>
            <p style={{ marginTop: 16, fontSize: 13.5, color: "var(--ink-soft)", maxWidth: 36 + "ch" }}>
              Sport-led education, scholarship and development across the East of England. Operating from Highbury Drive, Holbeach.
            </p>
          </div>
          <div className="footer-col">
            <h4>Programmes</h4>
            <ul>
              <li><a href="#/college">Sports College — Post-16</a></li>
              <li><a href="#/scholarship">Football Scholarship</a></li>
              <li><a href="#/internships">Sports Industry Internships</a></li>
              <li><a href="#/run-sport">Sport Business Studies</a></li>
              <li><a href="#/university">University Progression</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Pathways</h4>
            <ul>
              <li><a href="#/jpl">Holbeach Utd JPL</a></li>
              <li><a href="#/compete">Compete</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Group</h4>
            <ul>
              <li><a href="#/about">About</a></li>
              <li><a href="#/stories">Success Stories</a></li>
              <li><a href="https://forms.gle/qhQPuDfyevaFHpQW7" target="_blank" rel="noopener">Apply / Register</a></li>
              <li><a href="#/contact">Contact</a></li>
              <li><a href="#/safeguarding">Safeguarding</a></li>
            </ul>
          </div>
          <div className="footer-col">
            <h4>Get in touch</h4>
            <ul>
              {C.addressLines.map((l, i) => <li key={i}>{l}</li>)}
              {C.directors.map((d, i) => (
                <li key={"d" + i} className="footer-contact" style={{ marginTop: i === 0 ? 10 : 6 }}>
                  <span>{d.name}</span>
                  <a href={"mailto:" + d.email}>{d.email}</a>
                  <a href={"tel:" + d.phone.replace(/\s/g, "")}>{d.phone}</a>
                </li>
              ))}
              <li><a href={C.webHref} target="_blank" rel="noreferrer">{C.instagram}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© {new Date().getFullYear()} FEA Sports Group</span>
          <span>Holbeach United FEA · Football Scholarship · JPL Academy</span>
        </div>
      </div>
    </footer>);

}

// ---------- Expose ----------
Object.assign(window, {
  Header, Footer, Hero, Placeholder, Doorway, SubCard, CtaStrip, IdStrip, SubNav, OpenEvenings,
  useRoute, parseHash, go
});