const { useState, useEffect, useMemo } = React;

function getInitialData() {
  return JSON.parse(JSON.stringify(window.ALBION_SEED_DATA));
}

function AlbionCrest({ className = "w-10 h-10", logoUrl = "https://www.albionsccolorado.org/_templates/Department/images/logo.png" }) {
  const [imgError, setImgError] = useState(false);

  if (!imgError && logoUrl) {
    return (
      <img
        src={logoUrl}
        alt="ALBION SC Colorado Crest"
        className={`${className} object-contain`}
        onError={() => setImgError(true)}
      />
    );
  }

  return (
    <svg viewBox="0 0 64 76" className={className} fill="none" xmlns="http://www.w3.org/2000/svg" aria-label="Albion SC Colorado Crest">
      <path d="M32 3L6 13V37C6 53.5 17.5 66.5 32 73C46.5 66.5 58 53.5 58 37V13L32 3Z" fill="#54585A" stroke="#C8102E" strokeWidth="3.5" />
      <path d="M32 9L12 17V36.5C12 49.5 21 60 32 65.5C43 60 52 49.5 52 36.5V17L32 9Z" fill="#FFFFFF" />
      <path d="M12 29H52V37H12V29Z" fill="#C8102E" />
      <text x="32" y="25" textAnchor="middle" fill="#111827" fontFamily="Oswald, sans-serif" fontWeight="700" fontSize="11">ALBION</text>
      <text x="32" y="35.5" textAnchor="middle" fill="#FFFFFF" fontFamily="Oswald, sans-serif" fontWeight="700" fontSize="7.5" letterSpacing="1">COLORADO</text>
      <circle cx="32" cy="50" r="8" fill="#54585A" />
      <path d="M32 42L34.5 47.5L40 48L36 52L37 57.5L32 54.8L27 57.5L28 52L24 48L29.5 47.5L32 42Z" fill="#FFFFFF" />
    </svg>
  );
}

function PartnerLogoPlaceholder({ partner, index }) {
  if (partner.logoUrl) {
    return (
      <img
        src={partner.logoUrl}
        alt={`${partner.name} logo`}
        className="w-14 h-14 object-contain shrink-0 rounded"
      />
    );
  }

  const icons = [
    // Healthcare cross + pulse
    <svg viewBox="0 0 48 48" className="w-8 h-8 text-albion-gray" fill="none" stroke="currentColor" strokeWidth="2.5">
      <rect x="6" y="6" width="36" height="36" rx="8" />
      <path d="M24 15v18M15 24h18" strokeLinecap="round" />
    </svg>,
    // Mountain / Credit Union
    <svg viewBox="0 0 48 48" className="w-8 h-8 text-albion-gray" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M6 36L18 16l8 12 6-8 10 16H6z" strokeLinejoin="round" />
    </svg>,
    // Craft Brewery / Hop / Pint
    <svg viewBox="0 0 48 48" className="w-8 h-8 text-albion-gray" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M14 14h16l-2 24H16L14 14z" strokeLinejoin="round" />
      <path d="M30 18h4a4 4 0 010 8h-4" />
      <path d="M12 14c0-3 3-5 6-4 2-3 8-3 10 0 3-1 6 1 6 4" strokeLinecap="round" />
    </svg>,
    // Pizza / Flame
    <svg viewBox="0 0 48 48" className="w-8 h-8 text-albion-gray" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M24 8L38 36H10L24 8z" strokeLinejoin="round" />
      <circle cx="24" cy="24" r="2.5" fill="currentColor" />
      <circle cx="20" cy="30" r="2" fill="currentColor" />
      <circle cx="28" cy="30" r="2" fill="currentColor" />
    </svg>,
    // Solar / Sun
    <svg viewBox="0 0 48 48" className="w-8 h-8 text-albion-gray" fill="none" stroke="currentColor" strokeWidth="2.5">
      <circle cx="24" cy="24" r="8" />
      <path d="M24 8v4M24 36v4M8 24h4M36 24h4M13 13l3 3M32 32l3 3M35 13l-3 3M16 32l-3 3" strokeLinecap="round" />
    </svg>,
    // Running / Fitness bolt
    <svg viewBox="0 0 48 48" className="w-8 h-8 text-albion-gray" fill="none" stroke="currentColor" strokeWidth="2.5">
      <path d="M26 8L14 26h10l-2 14 12-18H24l2-14z" strokeLinejoin="round" />
    </svg>,
  ];

  return (
    <div className="w-14 h-14 rounded-lg bg-white border border-gray-200 flex items-center justify-center shrink-0 shadow-xs">
      {icons[index % icons.length]}
    </div>
  );
}

function LeagueBadge({ team }) {
  const isWomen = team === "women";
  return (
    <div className="inline-flex items-center gap-2">
      <span
        className={`w-7 h-7 rounded flex items-center justify-center font-display font-bold text-white text-sm shadow-sm ${
          isWomen ? "bg-[#5B2C8D]" : "bg-[#C8102E]"
        }`}
        aria-hidden="true"
      >
        {isWomen ? "W" : "2"}
      </span>
      <span
        className={`text-[11px] font-bold uppercase tracking-wider px-2.5 py-0.5 rounded ${
          isWomen
            ? "bg-purple-50 text-[#5B2C8D] border border-purple-200"
            : "bg-red-50 text-[#C8102E] border border-red-200"
        }`}
      >
        {isWomen ? "USL W League" : "USL League Two"}
      </span>
    </div>
  );
}

function formatDate(dateStr) {
  if (!dateStr) return "";
  const [y, m, d] = dateStr.split("-").map(Number);
  const dt = new Date(y, m - 1, d);
  return dt.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });
}

function Navbar({ route, navigate, siteConfig }) {
  const [mobileOpen, setMobileOpen] = useState(false);

  const navItems = [
    { path: "/", label: "Home" },
    { path: "/men", label: "Men (USL2)" },
    { path: "/women", label: "Women (USLW)" },
    { path: "/schedule", label: "Schedule" },
    { path: "/news", label: "News" },
    { path: "/partners", label: "Partners" },
  ];

  const handleNav = (path) => {
    navigate(path);
    setMobileOpen(false);
  };

  return (
    <header className="sticky top-0 z-40 bg-white border-b border-gray-200 shadow-sm">
      {/* Main Navigation */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-16">
          <button
            onClick={() => handleNav("/")}
            className="flex items-center gap-3 text-left group"
          >
            <AlbionCrest className="w-10 h-11 transition-transform group-hover:scale-105" logoUrl={siteConfig.logoUrl} />
            <div>
              <div className="font-display text-xl font-bold tracking-tight text-albion-charcoal leading-none">
                {siteConfig.clubName}
              </div>
              <div className="text-[11px] font-semibold tracking-widest text-albion-gray uppercase mt-0.5">
                USL2 &amp; USLW
              </div>
            </div>
          </button>

          {/* Desktop Links */}
          <nav className="hidden lg:flex items-center gap-6">
            {navItems.map((item) => {
              const active = route === item.path;
              return (
                <button
                  key={item.path}
                  onClick={() => handleNav(item.path)}
                  className={`font-display uppercase tracking-wide text-sm font-semibold py-1 border-b-2 transition-colors ${
                    active
                      ? "border-albion-red text-albion-red"
                      : "border-transparent text-albion-charcoal hover:text-albion-red"
                  }`}
                >
                  {item.label}
                </button>
              );
            })}
          </nav>

          {/* Action CTAs: Tickets + Shop */}
          <div className="hidden lg:flex items-center gap-2.5">
            <a
              href={siteConfig.soccerComMerchUrl}
              target="_blank"
              rel="noreferrer"
              className="px-4 py-2 text-xs font-display font-bold uppercase tracking-wider border-2 border-albion-gray text-albion-gray rounded hover:bg-albion-gray hover:text-white transition-colors"
            >
              Shop
            </a>
            <a
              href={siteConfig.vivenuTicketUrl}
              target="_blank"
              rel="noreferrer"
              className="px-4 py-2 text-xs font-display font-bold uppercase tracking-wider bg-albion-red text-white rounded hover:bg-albion-redDark transition-colors shadow-sm"
            >
              Buy Tickets
            </a>
          </div>

          {/* Mobile Menu Button */}
          <button
            onClick={() => setMobileOpen(!mobileOpen)}
            className="lg:hidden p-2 rounded border border-gray-300 text-albion-charcoal"
            aria-label="Toggle Menu"
          >
            {mobileOpen ? "✕" : "☰"}
          </button>
        </div>
      </div>

      {/* Mobile Drawer */}
      {mobileOpen && (
        <div className="lg:hidden bg-white border-t border-gray-200 px-4 py-4 space-y-2">
          {navItems.map((item) => (
            <button
              key={item.path}
              onClick={() => handleNav(item.path)}
              className={`block w-full text-left font-display uppercase tracking-wide text-base font-semibold py-2 px-2 rounded ${
                route === item.path ? "bg-red-50 text-albion-red" : "text-albion-charcoal"
              }`}
            >
              {item.label}
            </button>
          ))}
          <div className="pt-2 flex flex-col gap-2">
            <a
              href={siteConfig.vivenuTicketUrl}
              target="_blank"
              rel="noreferrer"
              className="w-full text-center py-2.5 font-display font-bold uppercase tracking-wider bg-albion-red text-white rounded"
            >
              Buy Tickets
            </a>
            <a
              href={siteConfig.soccerComMerchUrl}
              target="_blank"
              rel="noreferrer"
              className="w-full text-center py-2.5 font-display font-bold uppercase tracking-wider border-2 border-albion-gray text-albion-gray rounded"
            >
              Shop
            </a>
          </div>
        </div>
      )}
    </header>
  );
}

function HeroVideoPlaceholder({ siteConfig, navigate }) {
  return (
    <section className="relative overflow-hidden bg-albion-charcoal text-white min-h-[500px] lg:min-h-[580px] flex items-center">
      {/* Real HTML5 Video tag if heroVideoUrl is set; otherwise animated pitch placeholder */}
      {siteConfig.heroVideoUrl ? (
        <video
          className="absolute inset-0 w-full h-full object-cover opacity-55"
          src={siteConfig.heroVideoUrl}
          autoPlay
          muted
          loop
          playsInline
        />
      ) : (
        <div className="absolute inset-0 animate-hero-loop">
          <div className="w-full h-full bg-gradient-to-br from-gray-900 via-albion-gray to-gray-900 opacity-95" />
          {/* Subtle animated stadium pitch lines SVG */}
          <svg className="absolute inset-0 w-full h-full opacity-15" viewBox="0 0 1200 600" preserveAspectRatio="xMidYMid slice">
            <rect x="60" y="50" width="1080" height="500" fill="none" stroke="#FFFFFF" strokeWidth="3" />
            <line x1="600" y1="50" x2="600" y2="550" stroke="#FFFFFF" strokeWidth="3" />
            <circle cx="600" cy="300" r="85" fill="none" stroke="#FFFFFF" strokeWidth="3" />
            <rect x="60" y="175" width="140" height="250" fill="none" stroke="#FFFFFF" strokeWidth="3" />
            <rect x="1000" y="175" width="140" height="250" fill="none" stroke="#FFFFFF" strokeWidth="3" />
          </svg>
        </div>
      )}

      {/* Dark scrim for crisp text legibility */}
      <div className="absolute inset-0 bg-gradient-to-r from-black/75 via-black/45 to-black/30" />

      <div className="relative z-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 w-full">
        <div className="max-w-2xl">
          <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/15 backdrop-blur-sm border border-white/25 text-xs font-semibold tracking-wider uppercase mb-5">
            <span className="w-2 h-2 rounded-full bg-albion-red animate-pulse" />
            {siteConfig.heroVideoUrl
              ? "Looping Matchday Video Active"
              : "Hero Video Loop Placeholder — Add .MP4 in CMS"}
          </div>

          <h1 className="font-display text-4xl sm:text-5xl lg:text-6xl font-bold uppercase tracking-tight leading-[1.05]">
            {siteConfig.heroHeadline}
          </h1>

          <p className="mt-4 text-base sm:text-lg text-gray-200 max-w-xl leading-relaxed">
            {siteConfig.heroSubheadline}
          </p>

          <div className="mt-8 flex flex-wrap items-center gap-4">
            <a
              href={siteConfig.vivenuTicketUrl}
              target="_blank"
              rel="noreferrer"
              className="px-7 py-3.5 bg-albion-red hover:bg-albion-redDark text-white font-display font-bold uppercase tracking-wider text-sm rounded shadow-lg transition-all"
            >
              Buy Tickets
            </a>
            <a
              href={siteConfig.soccerComMerchUrl}
              target="_blank"
              rel="noreferrer"
              className="px-7 py-3.5 bg-white text-albion-charcoal hover:bg-gray-100 font-display font-bold uppercase tracking-wider text-sm rounded shadow transition-all"
            >
              Shop
            </a>
            <button
              onClick={() => navigate("/schedule")}
              className="px-5 py-3.5 border border-white/50 text-white hover:bg-white/10 font-display font-semibold uppercase tracking-wider text-sm rounded transition-all"
            >
              2027 Schedule
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

function HomePage({ data, navigate, onSelectArticle, onSubscribe }) {
  const { siteConfig, schedule, news, partners } = data;
  const [email, setEmail] = useState("");
  const [subscribed, setSubscribed] = useState(false);

  const nextMen = schedule.find((m) => m.team === "men" && m.status === "Upcoming");
  const nextWomen = schedule.find((m) => m.team === "women" && m.status === "Upcoming");

  const handleEmailSubmit = (e) => {
    e.preventDefault();
    if (!email.trim()) return;
    onSubscribe(email.trim());
    setEmail("");
    setSubscribed(true);
  };

  return (
    <div>
      <HeroVideoPlaceholder siteConfig={siteConfig} navigate={navigate} />

      {/* 1. Upcoming Matches Dual-Team Strip (USLW + USL2) */}
      <section className="bg-albion-grayLight border-b border-gray-200 py-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-display text-2xl font-bold uppercase tracking-tight text-albion-charcoal">
              Upcoming Matches
            </h2>
            <button
              onClick={() => navigate("/schedule")}
              className="text-sm font-semibold text-albion-red hover:underline uppercase font-display tracking-wide"
            >
              Full Schedule →
            </button>
          </div>

          <div className="grid md:grid-cols-2 gap-5">
            {[
              { team: "women", match: nextWomen, teamPath: "/women" },
              { team: "men", match: nextMen, teamPath: "/men" },
            ].map(({ team, match, teamPath }) => (
              <div
                key={team}
                className={`bg-white rounded-lg border border-gray-200 border-l-4 ${
                  team === "women" ? "border-l-[#5B2C8D]" : "border-l-[#C8102E]"
                } p-5 shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-4`}
              >
                <div>
                  <LeagueBadge team={team} />
                  {match ? (
                    <>
                      <h3 className="font-display text-xl font-bold uppercase mt-2.5 text-albion-charcoal">
                        Albion {match.location === "Home" ? "vs." : "@"} {match.opponent}
                      </h3>
                      <p className="text-sm text-albion-gray mt-1">
                        {formatDate(match.date)} • {match.time} • {match.venue}
                      </p>
                    </>
                  ) : (
                    <p className="text-sm text-albion-gray mt-2">No upcoming matches scheduled.</p>
                  )}
                </div>

                <div className="flex sm:flex-col gap-2 shrink-0">
                  <a
                    href={siteConfig.vivenuTicketUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="px-4 py-2 bg-albion-red hover:bg-albion-redDark text-white font-display font-bold uppercase text-xs tracking-wider rounded text-center"
                  >
                    Buy Tickets
                  </a>
                  <button
                    onClick={() => navigate(teamPath)}
                    className="px-4 py-2 border border-gray-300 hover:border-albion-gray text-albion-gray font-display font-semibold uppercase text-xs tracking-wider rounded text-center"
                  >
                    Roster
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 2. Community Partners ("Powered by Boulder County") */}
      <section className="bg-white py-12 border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex flex-col sm:flex-row sm:items-end justify-between mb-7 gap-2">
            <div>
              <span className="text-xs font-bold uppercase tracking-widest text-albion-red">
                Powered by Boulder County
              </span>
              <h2 className="font-display text-3xl font-bold uppercase tracking-tight text-albion-charcoal mt-1">
                Community Partners
              </h2>
            </div>
            <button
              onClick={() => navigate("/partners")}
              className="text-sm font-semibold text-albion-red hover:underline uppercase font-display tracking-wide"
            >
              All Partners →
            </button>
          </div>

          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {partners.map((partner, idx) => (
              <div
                key={partner.id}
                className="rounded-lg border border-gray-200 p-5 bg-albion-grayLight/50 hover:border-albion-gray transition-colors flex items-center justify-between gap-4"
              >
                <div className="min-w-0">
                  <h3 className="font-display text-xl font-bold uppercase text-albion-charcoal leading-tight">
                    {partner.name}
                  </h3>
                  <p className="text-xs text-albion-gray mt-1.5">{partner.perk}</p>
                </div>
                <PartnerLogoPlaceholder partner={partner} index={idx} />
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* 3. Latest Club News (Bottom Section) */}
      <section className="bg-albion-grayLight py-12 border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between mb-7">
            <div>
              <span className="text-xs font-bold uppercase tracking-widest text-albion-red">
                Club Updates
              </span>
              <h2 className="font-display text-3xl font-bold uppercase tracking-tight text-albion-charcoal mt-1">
                Latest Albion News
              </h2>
            </div>
            <button
              onClick={() => navigate("/news")}
              className="text-sm font-semibold text-albion-red hover:underline uppercase font-display tracking-wide"
            >
              All News →
            </button>
          </div>

          <div className="grid md:grid-cols-3 gap-5">
            {news.slice(0, 3).map((article) => (
              <article
                key={article.id}
                onClick={() => onSelectArticle(article)}
                className="cursor-pointer bg-white rounded-lg border border-gray-200 p-5 shadow-sm hover:shadow-md transition-shadow flex flex-col justify-between"
              >
                <div>
                  <div className="flex items-center justify-end text-xs text-albion-gray mb-2">
                    <span>{formatDate(article.date)}</span>
                  </div>
                  <h3 className="font-display text-lg font-bold uppercase leading-snug text-albion-charcoal">
                    {article.title}
                  </h3>
                  <p className="text-sm text-albion-gray mt-2 line-clamp-2">
                    {article.summary}
                  </p>
                </div>
                <div className="mt-4 pt-3 border-t border-gray-100 flex items-center justify-end text-xs font-semibold text-albion-charcoal">
                  <span className="text-albion-red uppercase font-display">Read →</span>
                </div>
              </article>
            ))}
          </div>
        </div>
      </section>

      {/* 4. Bottom Split Banner: Email Signup + Buy Tickets CTA */}
      <section className="bg-white py-12">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="rounded-xl border border-gray-200 bg-albion-grayLight overflow-hidden grid lg:grid-cols-2">
            {/* Left: Email Signup */}
            <div className="p-8 sm:p-10 flex flex-col justify-center">
              <span className="text-xs font-bold uppercase tracking-widest text-albion-red">
                Stay in the Loop
              </span>
              <h2 className="font-display text-2xl sm:text-3xl font-bold uppercase text-albion-charcoal mt-1">
                Get Match &amp; Ticket Updates
              </h2>
              <p className="text-sm text-albion-gray mt-2">
                Schedule drops, roster news, and ticket alerts straight to your inbox.
              </p>

              {subscribed ? (
                <div className="mt-5 p-3 rounded bg-green-50 border border-green-200 text-sm font-medium text-green-800">
                  Thanks for signing up! You're on the Albion SC Colorado list.
                </div>
              ) : (
                <form onSubmit={handleEmailSubmit} className="mt-5 flex flex-col sm:flex-row gap-2.5">
                  <input
                    type="email"
                    required
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    placeholder="Enter your email address"
                    className="flex-1 px-4 py-3 rounded border border-gray-300 bg-white text-sm focus:outline-none focus:border-albion-red"
                  />
                  <button
                    type="submit"
                    className="px-6 py-3 bg-albion-charcoal hover:bg-black text-white font-display font-bold uppercase tracking-wider text-xs rounded transition-colors shrink-0"
                  >
                    Sign Up
                  </button>
                </form>
              )}
            </div>

            {/* Right: Buy Tickets CTA */}
            <div className="bg-albion-red text-white p-8 sm:p-10 flex flex-col justify-center items-start">
              <span className="text-xs font-bold uppercase tracking-widest text-red-100">
                2027 Season • {siteConfig.stadiumName}
              </span>
              <h2 className="font-display text-3xl font-bold uppercase mt-1">
                Join Us on Matchday
              </h2>
              <p className="text-sm text-red-100 mt-2 max-w-md">
                Grab single-match or season passes for both Men's USL2 and Women's USLW home games.
              </p>
              <a
                href={siteConfig.vivenuTicketUrl}
                target="_blank"
                rel="noreferrer"
                className="mt-6 px-7 py-3.5 bg-white text-albion-red hover:bg-gray-100 font-display font-bold uppercase tracking-wider text-sm rounded shadow transition-colors"
              >
                Buy Tickets
              </a>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function TeamPage({ team, data, navigate }) {
  const [posFilter, setPosFilter] = useState("ALL");
  const isMen = team === "men";
  const showRosters = Boolean(data.siteConfig.showRosters);
  const players = data.roster.filter((p) => p.team === team);
  const coaches = data.coaches.filter((c) => c.team === team);

  const filtered = posFilter === "ALL" ? players : players.filter((p) => p.position === posFilter);

  return (
    <div className="bg-white min-h-[70vh]">
      <div className="bg-albion-grayLight border-b border-gray-200 py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <LeagueBadge team={team} />
            <h1 className="font-display text-4xl font-bold uppercase tracking-tight text-albion-charcoal mt-3">
              {isMen ? "Men's First Team" : "Women's First Team"}
            </h1>
            <p className="text-sm text-albion-gray mt-2 max-w-2xl">
              {isMen
                ? "Representing Albion SC Colorado in USL League Two's Mountain Division."
                : "Representing Albion SC Colorado in the USL W League's Mountain Division."}
            </p>
          </div>
          <a
            href={data.siteConfig.vivenuTicketUrl}
            target="_blank"
            rel="noreferrer"
            className="px-5 py-2.5 bg-albion-red hover:bg-albion-redDark text-white font-display font-bold uppercase text-xs tracking-wider rounded self-start"
          >
            Buy Tickets
          </a>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        {!showRosters ? (
          <div className="max-w-2xl mx-auto my-8 rounded-xl border border-gray-200 bg-albion-grayLight/60 p-8 sm:p-10 text-center shadow-sm">
            <span className="inline-block text-xs font-bold uppercase tracking-widest text-albion-red mb-2">
              2027 Season
            </span>
            <h2 className="font-display text-3xl font-bold uppercase text-albion-charcoal">
              2027 Roster Coming Soon
            </h2>
            <p className="text-sm sm:text-base text-albion-gray mt-3 leading-relaxed">
              {data.siteConfig.rosterComingSoonMessage}
            </p>
            <div className="mt-6 flex flex-wrap items-center justify-center gap-3">
              <button
                onClick={() => navigate("/schedule")}
                className="px-5 py-2.5 bg-albion-charcoal hover:bg-black text-white font-display font-bold uppercase text-xs tracking-wider rounded"
              >
                View 2027 Schedule
              </button>
              <button
                onClick={() => navigate("/news")}
                className="px-5 py-2.5 border border-gray-300 bg-white hover:border-albion-gray text-albion-charcoal font-display font-bold uppercase text-xs tracking-wider rounded"
              >
                Club News
              </button>
            </div>
          </div>
        ) : (
          <>
            {/* Position Filter */}
            <div className="flex flex-wrap items-center gap-2 mb-8">
              {["ALL", "GK", "DEF", "MID", "FWD"].map((pos) => (
                <button
                  key={pos}
                  onClick={() => setPosFilter(pos)}
                  className={`px-4 py-1.5 rounded font-display font-bold uppercase text-xs tracking-wider transition-colors ${
                    posFilter === pos
                      ? "bg-albion-red text-white"
                      : "bg-gray-100 text-albion-gray hover:bg-gray-200"
                  }`}
                >
                  {pos}
                </button>
              ))}
            </div>

            {/* Player Grid */}
            <div className="grid sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-5">
              {filtered.map((player) => (
                <div
                  key={player.id}
                  className="rounded-lg border border-gray-200 overflow-hidden bg-white shadow-sm hover:shadow-md transition-shadow"
                >
                  <div className="h-36 bg-gradient-to-br from-gray-100 to-gray-200 relative flex items-center justify-center overflow-hidden">
                    {player.photoUrl ? (
                      <img
                        src={player.photoUrl}
                        alt={player.name}
                        className="w-full h-full object-cover object-top"
                      />
                    ) : (
                      <span className="font-display text-5xl font-bold text-gray-300 select-none">
                        #{player.number}
                      </span>
                    )}
                    <span className="absolute top-3 right-3 px-2 py-0.5 rounded bg-albion-charcoal text-white text-[11px] font-bold uppercase">
                      {player.position}
                    </span>
                  </div>
                  <div className="p-4">
                    <div className="flex items-baseline justify-between">
                      <h3 className="font-display text-lg font-bold uppercase text-albion-charcoal">
                        {player.name}
                      </h3>
                      <span className="font-display font-bold text-albion-red text-sm">
                        #{player.number}
                      </span>
                    </div>
                    <p className="text-xs text-albion-gray mt-1 font-medium">{player.college}</p>
                    <p className="text-[11px] text-gray-400 mt-0.5">Age {player.age}</p>
                  </div>
                </div>
              ))}
            </div>

            {/* Technical Staff */}
            <div className="mt-14 pt-10 border-t border-gray-200">
              <h2 className="font-display text-2xl font-bold uppercase text-albion-charcoal mb-5">
                Technical Staff
              </h2>
              <div className="grid sm:grid-cols-2 md:grid-cols-3 gap-5">
                {coaches.map((coach) => (
                  <div key={coach.id} className="p-4 rounded-lg border border-gray-200 bg-albion-grayLight/60">
                    <h3 className="font-display text-lg font-bold uppercase text-albion-charcoal">{coach.name}</h3>
                    <p className="text-xs text-albion-red font-semibold mt-1">{coach.role}</p>
                  </div>
                ))}
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function SchedulePage({ data }) {
  const [teamFilter, setTeamFilter] = useState("all");
  const [locFilter, setLocFilter] = useState("all");

  const filtered = useMemo(() => {
    return data.schedule
      .filter((m) => (teamFilter === "all" ? true : m.team === teamFilter))
      .filter((m) => (locFilter === "all" ? true : m.location.toLowerCase() === locFilter))
      .sort((a, b) => a.date.localeCompare(b.date));
  }, [data.schedule, teamFilter, locFilter]);

  return (
    <div className="bg-white min-h-[70vh]">
      <div className="bg-albion-grayLight border-b border-gray-200 py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <span className="text-xs font-bold uppercase tracking-widest text-albion-red">
            2027 Mountain Division
          </span>
          <h1 className="font-display text-4xl font-bold uppercase tracking-tight text-albion-charcoal mt-1">
            Match Schedule
          </h1>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Filters */}
        <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
          <div className="flex flex-wrap gap-2">
            {[
              { id: "all", label: "All Teams" },
              { id: "men", label: "Men (USL2)" },
              { id: "women", label: "Women (USLW)" },
            ].map((t) => (
              <button
                key={t.id}
                onClick={() => setTeamFilter(t.id)}
                className={`px-4 py-1.5 rounded font-display font-bold uppercase text-xs tracking-wider ${
                  teamFilter === t.id ? "bg-albion-red text-white" : "bg-gray-100 text-albion-gray"
                }`}
              >
                {t.label}
              </button>
            ))}
          </div>

          <div className="flex gap-2">
            {[
              { id: "all", label: "Home & Away" },
              { id: "home", label: "Home Only" },
            ].map((l) => (
              <button
                key={l.id}
                onClick={() => setLocFilter(l.id)}
                className={`px-3 py-1.5 rounded font-display font-semibold uppercase text-xs tracking-wider border ${
                  locFilter === l.id
                    ? "border-albion-charcoal bg-albion-charcoal text-white"
                    : "border-gray-300 text-albion-gray"
                }`}
              >
                {l.label}
              </button>
            ))}
          </div>
        </div>

        {/* Schedule List */}
        <div className="space-y-3">
          {filtered.map((match) => (
            <div
              key={match.id}
              className={`rounded-lg border border-gray-200 border-l-4 ${
                match.team === "women" ? "border-l-[#5B2C8D]" : "border-l-[#C8102E]"
              } p-5 bg-white flex flex-col md:flex-row md:items-center justify-between gap-4 shadow-sm`}
            >
              <div className="flex flex-col sm:flex-row sm:items-center gap-4">
                <div className="min-w-[130px]">
                  <div className="font-display text-lg font-bold text-albion-charcoal">
                    {formatDate(match.date)}
                  </div>
                  <div className="text-xs text-albion-gray">{match.time}</div>
                </div>
                <div>
                  <div className="flex flex-wrap items-center gap-2 mb-1.5">
                    <LeagueBadge team={match.team} />
                    <span
                      className={`text-[11px] font-bold uppercase px-2 py-0.5 rounded ${
                        match.location === "Home"
                          ? "bg-gray-100 text-albion-charcoal"
                          : "bg-gray-100 text-gray-500"
                      }`}
                    >
                      {match.location}
                    </span>
                  </div>
                  <h3 className="font-display text-xl font-bold uppercase text-albion-charcoal">
                    Albion SC Colorado {match.location === "Home" ? "vs." : "@"} {match.opponent}
                  </h3>
                  <p className="text-xs text-albion-gray mt-0.5">
                    {match.venue} {match.themeNight ? `• ★ ${match.themeNight}` : ""}
                  </p>
                </div>
              </div>

              <div className="flex items-center gap-3">
                {match.score ? (
                  <span className="font-display text-xl font-bold px-3 py-1 bg-gray-100 rounded">
                    {match.score}
                  </span>
                ) : match.location === "Home" ? (
                  <a
                    href={data.siteConfig.vivenuTicketUrl}
                    target="_blank"
                    rel="noreferrer"
                    className="px-4 py-2 bg-albion-red hover:bg-albion-redDark text-white font-display font-bold uppercase text-xs tracking-wider rounded"
                  >
                    Buy Tickets
                  </a>
                ) : (
                  <span className="text-xs font-semibold uppercase text-gray-400 px-3">Away Match</span>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function NewsPage({ data, onSelectArticle }) {
  const [cat, setCat] = useState("All");
  const categories = ["All", "Club News", "Roster", "Match Recap", "Community"];
  const items = cat === "All" ? data.news : data.news.filter((n) => n.category === cat);

  return (
    <div className="bg-white min-h-[70vh]">
      <div className="bg-albion-grayLight border-b border-gray-200 py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <span className="text-xs font-bold uppercase tracking-widest text-albion-red">
            Media &amp; Updates
          </span>
          <h1 className="font-display text-4xl font-bold uppercase tracking-tight text-albion-charcoal mt-1">
            Club News
          </h1>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex flex-wrap gap-2 mb-8">
          {categories.map((c) => (
            <button
              key={c}
              onClick={() => setCat(c)}
              className={`px-4 py-1.5 rounded font-display font-bold uppercase text-xs tracking-wider ${
                cat === c ? "bg-albion-red text-white" : "bg-gray-100 text-albion-gray"
              }`}
            >
              {c}
            </button>
          ))}
        </div>

        <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {items.map((article) => (
            <article
              key={article.id}
              onClick={() => onSelectArticle(article)}
              className="cursor-pointer rounded-lg border border-gray-200 p-6 bg-white shadow-sm hover:shadow-md transition-shadow flex flex-col justify-between"
            >
              <div>
                <div className="flex items-center justify-end text-xs text-albion-gray mb-3">
                  <span>{formatDate(article.date)}</span>
                </div>
                <h2 className="font-display text-xl font-bold uppercase text-albion-charcoal">
                  {article.title}
                </h2>
                <p className="text-sm text-albion-gray mt-3">{article.summary}</p>
              </div>
              <div className="mt-5 pt-4 border-t border-gray-100 flex items-center justify-end text-xs">
                <span className="text-albion-red font-display font-bold uppercase">Read →</span>
              </div>
            </article>
          ))}
        </div>
      </div>
    </div>
  );
}

function PartnersPage({ data }) {
  const tiers = ["Presenting Partner", "Official Matchday Partner", "Community Partner"];
  return (
    <div className="bg-white min-h-[70vh]">
      <div className="bg-albion-grayLight border-b border-gray-200 py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <span className="text-xs font-bold uppercase tracking-widest text-albion-red">
            Boulder County &amp; Front Range
          </span>
          <h1 className="font-display text-4xl font-bold uppercase tracking-tight text-albion-charcoal mt-1">
            Community Partners
          </h1>
          <p className="text-sm text-albion-gray mt-2 max-w-2xl">
            Local businesses, breweries, healthcare leaders, and community organizations powering Albion SC Colorado's USL2 &amp; USLW teams.
          </p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 space-y-12">
        {tiers.map((tier) => {
          const list = data.partners.filter((p) => p.tier === tier);
          if (list.length === 0) return null;
          return (
            <div key={tier}>
              <h2 className="font-display text-2xl font-bold uppercase text-albion-charcoal border-b border-gray-200 pb-2 mb-5">
                {tier}s
              </h2>
              <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-5">
                {list.map((p, idx) => (
                  <div
                    key={p.id}
                    className="rounded-lg border border-gray-200 p-6 bg-white shadow-sm flex items-center justify-between gap-4"
                  >
                    <div className="min-w-0">
                      <h3 className="font-display text-2xl font-bold uppercase text-albion-charcoal leading-tight">
                        {p.name}
                      </h3>
                      <p className="text-sm text-albion-gray mt-1.5">{p.perk}</p>
                    </div>
                    <PartnerLogoPlaceholder partner={p} index={idx} />
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function App() {
  const [data, setData] = useState(getInitialData);
  const [route, setRoute] = useState(() => window.location.pathname || "/");
  const [selectedArticle, setSelectedArticle] = useState(null);

  // Load live News, Schedule, and Roster from Google Sheets if configured
  useEffect(() => {
    const scriptUrl = data.siteConfig.googleAppsScriptUrl;
    if (!scriptUrl) return;

    fetch(scriptUrl)
      .then((res) => res.json())
      .then((remote) => {
        if (!remote || !remote.ok) return;
        setData((prev) => ({
          ...prev,
          news: Array.isArray(remote.news) && remote.news.length > 0 ? remote.news : prev.news,
          schedule: Array.isArray(remote.schedule) && remote.schedule.length > 0 ? remote.schedule : prev.schedule,
          roster: Array.isArray(remote.roster) && remote.roster.length > 0 ? remote.roster : prev.roster,
        }));
      })
      .catch(() => {
        // Keep fallback seed data if offline or script unavailable
      });
  }, []);

  useEffect(() => {
    const onPop = () => setRoute(window.location.pathname || "/");
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const navigate = (path) => {
    if (path !== route) {
      window.history.pushState({}, "", path);
      setRoute(path);
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  const handleSubscribe = async (email) => {
    const scriptUrl = data.siteConfig.googleAppsScriptUrl;
    if (scriptUrl) {
      try {
        await fetch(scriptUrl, {
          method: "POST",
          headers: { "Content-Type": "text/plain;charset=utf-8" },
          body: JSON.stringify({ email }),
        });
      } catch (e) {
        // Silently ignore network error in UI; form shows confirmation
      }
    }
  };

  return (
    <div className="min-h-screen flex flex-col bg-white">
      <Navbar
        route={route}
        navigate={navigate}
        siteConfig={data.siteConfig}
      />

      <main className="flex-1">
        {(route === "/" || route === "/admin") && (
          <HomePage
            data={data}
            navigate={navigate}
            onSelectArticle={setSelectedArticle}
            onSubscribe={handleSubscribe}
          />
        )}
        {route === "/men" && <TeamPage team="men" data={data} navigate={navigate} />}
        {route === "/women" && <TeamPage team="women" data={data} navigate={navigate} />}
        {route === "/schedule" && <SchedulePage data={data} />}
        {route === "/news" && <NewsPage data={data} onSelectArticle={setSelectedArticle} />}
        {route === "/partners" && <PartnersPage data={data} />}
      </main>

      <footer className="bg-albion-charcoal text-gray-300 py-10 border-t border-gray-800">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
          <div className="flex items-center gap-3">
            <AlbionCrest className="w-9 h-10" logoUrl={data.siteConfig.logoUrl} />
            <div>
              <div className="font-display text-lg font-bold uppercase text-white">
                {data.siteConfig.clubName}
              </div>
              <div className="text-xs text-gray-400">
                {data.siteConfig.stadiumName} • {data.siteConfig.stadiumCity}
              </div>
            </div>
          </div>

          <div className="flex flex-wrap gap-5 text-xs uppercase font-display tracking-wider">
            <button onClick={() => navigate("/men")} className="hover:text-white">Men (USL2)</button>
            <button onClick={() => navigate("/women")} className="hover:text-white">Women (USLW)</button>
            <button onClick={() => navigate("/schedule")} className="hover:text-white">Schedule</button>
            <button onClick={() => navigate("/news")} className="hover:text-white">News</button>
            <button onClick={() => navigate("/partners")} className="hover:text-white">Partners</button>
            <a href={data.siteConfig.vivenuTicketUrl} target="_blank" rel="noreferrer" className="text-albion-red font-bold">
              Buy Tickets
            </a>
            <a href={data.siteConfig.soccerComMerchUrl} target="_blank" rel="noreferrer" className="hover:text-white">
              Shop
            </a>
          </div>
        </div>
      </footer>

      {/* Article Reader Modal */}
      {selectedArticle && (
        <div className="fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4" onClick={() => setSelectedArticle(null)}>
          <div className="bg-white rounded-lg max-w-2xl w-full p-6 sm:p-8 shadow-2xl max-h-[85vh] overflow-y-auto" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between text-xs text-albion-gray mb-3">
              <span>{formatDate(selectedArticle.date)}</span>
              <button onClick={() => setSelectedArticle(null)} className="text-base font-bold text-albion-gray hover:text-black">✕</button>
            </div>
            {selectedArticle.imageUrl && (
              <img
                src={selectedArticle.imageUrl}
                alt={selectedArticle.title}
                className="w-full h-56 object-cover rounded-lg mb-4"
              />
            )}
            <h2 className="font-display text-2xl sm:text-3xl font-bold uppercase text-albion-charcoal mb-4">
              {selectedArticle.title}
            </h2>
            <p className="text-sm sm:text-base text-gray-700 leading-relaxed whitespace-pre-line">
              {selectedArticle.body}
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
