/* Shared components, marks, ticker, nav, footer, chart bg */
const { useState, useEffect, useRef, useMemo } = React;

/* ---------- Ambient stock chart background ---------- */
function ChartBackground({ seed = 7 }) {
  const path = useMemo(() => {
    const W = 1600, H = 600;
    let s = seed;
    const rnd = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    const pts = [];
    let y = H * 0.55;
    const N = 220;
    for (let i = 0; i < N; i++) {
      const x = (i / (N - 1)) * W;
      y += (rnd() - 0.48) * 18;
      y = Math.max(60, Math.min(H - 60, y));
      pts.push([x, y]);
    }
    let d = `M ${pts[0][0]} ${pts[0][1]}`;
    for (let i = 1; i < pts.length; i++) {
      const [x, y] = pts[i];
      const [px, py] = pts[i - 1];
      const cx = (px + x) / 2;
      d += ` Q ${cx} ${py} ${x} ${y}`;
    }
    return { d, last: pts[pts.length - 1], W, H, pts };
  }, [seed]);

  const accent = "#C9A84C";
  return (
    <div className="chart-bg" aria-hidden="true">
      <svg viewBox={`0 0 ${path.W} ${path.H}`} preserveAspectRatio="xMidYMid slice">
        <defs>
          <linearGradient id={`chartFill-${seed}`} x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor={accent} stopOpacity="0.10" />
            <stop offset="100%" stopColor={accent} stopOpacity="0" />
          </linearGradient>
          <linearGradient id={`chartStroke-${seed}`} x1="0" x2="1" y1="0" y2="0">
            <stop offset="0%" stopColor={accent} stopOpacity="0" />
            <stop offset="20%" stopColor={accent} stopOpacity="0.5" />
            <stop offset="80%" stopColor={accent} stopOpacity="0.5" />
            <stop offset="100%" stopColor={accent} stopOpacity="0" />
          </linearGradient>
          <pattern id={`grid-${seed}`} width="80" height="60" patternUnits="userSpaceOnUse">
            <path d="M 80 0 L 0 0 0 60" fill="none" stroke={accent} strokeWidth="0.4" strokeOpacity="0.07" />
          </pattern>
        </defs>
        <rect width={path.W} height={path.H} fill={`url(#grid-${seed})`} />
        {[0.2, 0.4, 0.6, 0.8].map((p, i) => (
          <line key={i} x1="0" x2={path.W} y1={path.H * p} y2={path.H * p} stroke={accent} strokeOpacity="0.05" strokeDasharray="2 6" />
        ))}
        <path d={`${path.d} L ${path.W} ${path.H} L 0 ${path.H} Z`} fill={`url(#chartFill-${seed})`} />
        <path d={path.d} fill="none" stroke={`url(#chartStroke-${seed})`} strokeWidth="1.4" />
        {path.pts.filter((_, i) => i % 11 === 0).map(([x, y], i) => (
          <line key={i} x1={x} x2={x} y1={y - 6} y2={y + 6} stroke={accent} strokeOpacity="0.18" strokeWidth="1" />
        ))}
        <circle cx={path.last[0] - 8} cy={path.last[1]} r="3" fill={accent} />
        <circle cx={path.last[0] - 8} cy={path.last[1]} r="8" fill="none" stroke={accent} strokeOpacity="0.4" />
      </svg>
    </div>
  );
}

/* ---------- School marks ---------- */
const SchoolMark = ({ kind, size = 56 }) => {
  const c = "#C9A84C";
  const stroke = { stroke: c, strokeWidth: 1.4, fill: "none" };
  const w = size, h = size;
  switch (kind) {
    case "crossroads":
      return (
        <svg width={w} height={h} viewBox="0 0 56 56">
          <circle cx="28" cy="28" r="24" {...stroke} />
          <path d="M10 28 H46 M28 10 V46" {...stroke} />
          <circle cx="28" cy="28" r="6" fill={c} />
        </svg>
      );
    case "brentwood":
      return (
        <svg width={w} height={h} viewBox="0 0 56 56">
          <rect x="8" y="8" width="40" height="40" {...stroke} />
          <rect x="16" y="16" width="24" height="24" {...stroke} />
          <path d="M22 22 L34 34 M34 22 L22 34" {...stroke} />
        </svg>
      );
    case "windward":
      return (
        <svg width={w} height={h} viewBox="0 0 56 56">
          <path d="M28 6 L50 50 L6 50 Z" {...stroke} />
          <path d="M28 18 L42 46 L14 46 Z" fill={c} fillOpacity="0.18" {...stroke} />
          <line x1="28" y1="6" x2="28" y2="50" {...stroke} />
        </svg>
      );
    case "marlborough":
      return (
        <svg width={w} height={h} viewBox="0 0 56 56">
          <circle cx="28" cy="28" r="22" {...stroke} />
          <path d="M16 36 Q28 20 40 36" {...stroke} />
          <path d="M16 28 Q28 12 40 28" strokeOpacity="0.5" {...stroke} />
          <circle cx="28" cy="28" r="2" fill={c} />
        </svg>
      );
  }
};

/* ---------- Status bar (registration window + pricing) ---------- */
function StatusBar() {
  return (
    <div className="statusbar">
      <div className="sb-half left">
        <span className="sb-label">Registration Opens</span>
        <span className="sb-price-when">Aug 1 · 12:00 AM PST</span>
      </div>
      <div className="sb-divider" />
      <div className="sb-half right">
        <div className="sb-pricing">
          <span className="sb-tier"><b>$25</b> Early Bird</span>
          <span className="sb-tier alt"><b>$35</b> from September</span>
        </div>
      </div>
    </div>
  );
}

/* ---------- Nav ---------- */
function Nav({ current = "home" }) {
  const [open, setOpen] = useState(false);
  const links = [
    { id: "competition", href: "/competition", label: "Competition" },
    { id: "register", href: "/register", label: "Register" },
    { id: "resources", href: "/resources", label: "Resources" },
    { id: "hosts", href: "/hosts", label: "Hosts" },
    { id: "about", href: "/about", label: "About" },
  ];
  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <a className="brand" href="/">
          <img className="brand-logo" src="/favicon.svg" alt="LASPC" />
          <div className="brand-text">
            LASPC
            <small>EST · 2026</small>
          </div>
        </a>
        <div className="nav-links">
          {links.map((l) => (
            <a key={l.id} href={l.href} className={current === l.id ? "active" : ""}>{l.label}</a>
          ))}
          <a className="nav-cta" href="/register">Register →</a>
        </div>
        <button className={`nav-hamburger${open ? " is-open" : ""}`} onClick={() => setOpen(!open)} aria-label="Toggle menu">
          <span /><span /><span />
        </button>
      </div>
      {open && (
        <div className="nav-mobile">
          {links.map((l) => (
            <a key={l.id} href={l.href} className={current === l.id ? "active" : ""} onClick={() => setOpen(false)}>{l.label}</a>
          ))}
          <a className="nav-cta nav-mobile-cta" href="/register" onClick={() => setOpen(false)}>Register →</a>
        </div>
      )}
    </nav>
  );
}

/* ---------- Footer ---------- */
function Footer() {
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot-grid">
          <div className="foot-col">
            <a className="brand" href="/" style={{ marginBottom: 18 }}>
              <img className="brand-logo" src="/favicon.svg" alt="LASPC" />
              <div className="brand-text">LASPC<small>EST · 2026</small></div>
            </a>
            <p style={{ maxWidth: 320, marginTop: 18 }}>
              The LA Stock Pitch Competition is a student-led, faculty-supervised tournament hosted at Crossroads School for Arts &amp; Sciences in Santa Monica, California.
            </p>
          </div>
          <div className="foot-col">
            <h5>Event</h5>
            <a href="/competition">Competition</a>
            <a href="/register">Register</a>
            <a href="/resources">Resources</a>
          </div>
          <div className="foot-col">
            <h5>Hosts</h5>
            {SCHOOLS.map(s => (
              <a key={s.kind} href={s.website} target="_blank" rel="noopener noreferrer">{s.name}</a>
            ))}
          </div>
          <div className="foot-col">
            <h5>Contact</h5>
            <a href="mailto:contact@laspc.org">contact@laspc.org</a>
            <p>Crossroads School<br />1714 21st Street<br />Santa Monica, CA</p>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 · LA Stock Pitch Competition</span>
          <span>Inaugural Year</span>
          <span>Sunday · October 18 · 2026</span>
        </div>
      </div>
    </footer>
  );
}

/* ---------- Page header (non-home) ---------- */
function PageHead({ crumb, title, lede, seed = 4 }) {
  return (
    <header className="page-head">
      <ChartBackground seed={seed} />
      <div className="wrap">
        <div className="crumb">{crumb}</div>
        <h1 dangerouslySetInnerHTML={{ __html: title }} />
        {lede && <p className="lede">{lede}</p>}
      </div>
    </header>
  );
}

/* ---------- Shared data ---------- */
const SCHOOLS = [
  { kind: "crossroads", name: "Crossroads School", role: "Host Campus", full: "Crossroads School for Arts & Sciences", website: "https://www.xrds.org", logo: "images/crossroads.png" },
  { kind: "marlborough",name: "Marlborough School", role: "Co-host", full: "Marlborough School", website: "https://www.marlborough.org", logo: "images/marlborough.jpg" },
];

const SCHEDULE = [
  { time: "8:15 – 9:00 AM", title: "Check-In", sub: "Photo ID required. Pick up your room assignment.", meta: "REGISTRATION DESK" },
  { time: "9:10 – 9:20 AM", title: "Welcome & Announcements", sub: "Opening remarks from the host committee and introduction of the day's format.", meta: "MAIN HALL" },
  { time: "9:30 – 11:54 AM", title: "Round 1 · Field of 80", sub: "All 80 teams pitch concurrently. 14 minutes per team (10 pitch + 4 Q&A).", meta: "10 ROOMS · 144 MIN", feature: true },
  { time: "12:00 – 12:45 PM", title: "Lunch", sub: "Food truck on campus.", meta: "FOOD TRUCK" },
  { time: "12:45 – 12:50 PM", title: "Top 20 Announced", sub: "Round 1 results posted. Advancing teams proceed to assigned rooms for Round 2.", meta: "MAIN HALL" },
  { time: "1:00 – 2:12 PM", title: "Round 2 · Top 20", sub: "Twenty advancing teams pitch across 5 rooms. Same 14-minute format.", meta: "5 ROOMS · 72 MIN", feature: true },
  { time: "2:12 – 2:25 PM", title: "Judges Deliberate", sub: "Judges determine the five finalists.", meta: "PRIVATE" },
  { time: "2:25 – 2:30 PM", title: "Final 5 Announced", sub: "Five finalists announced in the main hall.", meta: "MAIN HALL" },
  { time: "2:40 – 4:10 PM", title: "Finals · Top 5", sub: "Five finalists pitch consecutively before the full judging panel. 14 minutes per team.", meta: "MAIN HALL · 90 MIN", feature: true },
  { time: "4:10 – 4:25 PM", title: "Judges Confer", sub: "Final deliberation.", meta: "PRIVATE" },
  { time: "4:30 – 5:00 PM", title: "Winners Announced & Prizes Awarded", sub: "Awards presentation, prize distribution, and closing remarks.", meta: "MAIN HALL", feature: true },
];

const KEY_DATES = [
  { date: "AUG 01", year: "2026", title: "Registration Opens", body: "Sign-ups go live at 12:00 AM PST. $25 early-bird entry through August; $35 from September. The field is capped at 80 teams, first-come.", state: "upcoming" },
  { date: "OCT 03", year: "2026", title: "Registration Closes", body: "Final cutoff for entries, or sooner if the 80-team cap fills. All registered teams must then submit a pitch deck by October 10.", state: "upcoming" },
  { date: "OCT 10", year: "2026", title: "Pitch Decks Due", body: "Email your deck as a PDF or .pptx by the deadline. Late decks disqualify the team.", state: "upcoming" },
  { date: "OCT 18", year: "2026", title: "Competition Day", body: "All three rounds run on Sunday at Crossroads School. Doors at 8:15 AM, opening remarks at 9:10 AM.", state: "upcoming" },
];

/* expose globals for other scripts */
Object.assign(window, { ChartBackground, SchoolMark, StatusBar, Nav, Footer, PageHead, SCHOOLS, SCHEDULE, KEY_DATES });
