// VEXEL — Shared UI atoms + header + footer
// Loaded after data.js, before page files.

const { useState, useEffect, useRef, useMemo, Fragment } = React;

// ─── Logo (real artwork) ────────────────────────────────────────────────────
function Logo({ size = 28 }) {
  return (
    <img src="logo.png?v=3" alt="Clutchscan"
         width={size} height={size}
         style={{
           display: "block",
           width: size,
           height: size,
           objectFit: "contain",
           filter: "drop-shadow(0 0 8px rgba(0, 229, 255, 0.35))"
         }} />
  );
}

function Wordmark({ size = 22 }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <Logo size={size + 12} />
      <span className="t-display-tight" style={{ fontSize: size + 4, letterSpacing: "0.04em", color: "var(--white)" }}>VEXEL</span>
    </div>
  );
}

// ─── Game logo glyph (CSS only) ──────────────────────────────────────────────
function GameGlyph({ game, size = 32 }) {
  const g = typeof game === "string" ? gameById(game) : game;
  if (!g) return null;
  return (
    <div style={{
      width: size, height: size, borderRadius: 4,
      background: `linear-gradient(135deg, ${g.color} 0%, rgba(0,0,0,0.4) 100%)`,
      display: "flex", alignItems: "center", justifyContent: "center",
      fontFamily: "var(--font-display)", fontWeight: 900, fontSize: size * 0.5,
      color: "var(--white)", letterSpacing: "-0.02em",
      boxShadow: `inset 0 -2px 0 rgba(0,0,0,0.3)`,
      flexShrink: 0,
    }}>
      {g.icon}
    </div>
  );
}

// ─── Team logo glyph ─────────────────────────────────────────────────────────
function TeamLogo({ team, size = 40 }) {
  const t = typeof team === "string" ? teamById(team) : team;
  if (!t) return null;
  return (
    <div style={{
      width: size, height: size,
      background: t.color,
      clipPath: "polygon(0 0, 100% 0, 100% 78%, 50% 100%, 0 78%)",
      display: "flex", alignItems: "center", justifyContent: "center",
      fontFamily: "var(--font-display-tight)", fontSize: size * 0.32,
      color: t.color === "#FFFFFF" ? "#000" : "#fff",
      letterSpacing: "-0.02em",
      flexShrink: 0,
    }}>
      {t.tag.slice(0, 4)}
    </div>
  );
}

// ─── Flag glyph ──────────────────────────────────────────────────────────────
function Flag({ code, size = 16 }) {
  const f = REGION_FLAGS[code] || REGION_FLAGS.INT;
  return (
    <div style={{ width: size, height: size * 0.67, borderRadius: 1, overflow: "hidden", display: "inline-grid", gridTemplateColumns: "1fr 1fr", gridTemplateRows: "1fr 1fr", border: "1px solid rgba(255,255,255,0.1)", flexShrink: 0, verticalAlign: "middle" }}>
      <div style={{ background: f.c1 }} />
      <div style={{ background: f.c2 }} />
      <div style={{ background: f.c3 }} />
      <div style={{ background: f.c4 }} />
    </div>
  );
}

// ─── Live dot ────────────────────────────────────────────────────────────────
function LiveBadge({ children = "LIVE" }) {
  return (
    <span className="pill pill-live">
      <span className="dot-live" />
      {children}
    </span>
  );
}

// ─── Countdown timer ─────────────────────────────────────────────────────────
function Countdown({ targetDays = 7 }) {
  const [t, setT] = useState({ d: targetDays, h: 14, m: 22, s: 47 });
  useEffect(() => {
    const id = setInterval(() => {
      setT(prev => {
        let { d, h, m, s } = prev;
        s -= 1;
        if (s < 0) { s = 59; m -= 1; }
        if (m < 0) { m = 59; h -= 1; }
        if (h < 0) { h = 23; d -= 1; }
        if (d < 0) { d = 0; }
        return { d, h, m, s };
      });
    }, 1000);
    return () => clearInterval(id);
  }, []);
  const pad = (n) => String(n).padStart(2, "0");
  return (
    <div className="t-mono" style={{ display: "flex", gap: 16, fontVariantNumeric: "tabular-nums" }}>
      {[["DAYS", t.d], ["HRS", t.h], ["MIN", t.m], ["SEC", t.s]].map(([l, v]) => (
        <div key={l} style={{ textAlign: "center" }}>
          <div style={{ fontSize: 32, fontWeight: 700, color: "var(--cyan)", lineHeight: 1 }}>{pad(v)}</div>
          <div style={{ fontSize: 10, color: "var(--text-mute)", letterSpacing: "0.15em", marginTop: 4 }}>{l}</div>
        </div>
      ))}
    </div>
  );
}

// ─── Animated counter ────────────────────────────────────────────────────────
function NumberTicker({ value, prefix = "", suffix = "", duration = 1400 }) {
  const [n, setN] = useState(0);
  useEffect(() => {
    const start = performance.now();
    let raf;
    const tick = (now) => {
      const t = Math.min(1, (now - start) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setN(Math.round(eased * value));
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [value]);
  return <span className="t-mono">{prefix}{n.toLocaleString("en-US")}{suffix}</span>;
}

// ─── Search overlay ──────────────────────────────────────────────────────────
function SearchOverlay({ open, onClose, go }) {
  const [q, setQ] = useState("");
  const ref = useRef();
  useEffect(() => { if (open) setTimeout(() => ref.current && ref.current.focus(), 50); }, [open]);
  if (!open) return null;
  const ql = q.toLowerCase();
  const tournaments = TOURNAMENTS.filter(t => t.name.toLowerCase().includes(ql)).slice(0, 4);
  const teams = TEAMS.filter(t => t.name.toLowerCase().includes(ql) || t.tag.toLowerCase().includes(ql)).slice(0, 4);
  const players = PLAYERS.filter(p => p.handle.toLowerCase().includes(ql) || p.realName.toLowerCase().includes(ql)).slice(0, 4);
  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(10,10,15,0.85)", backdropFilter: "blur(12px)", zIndex: 100, padding: "80px 24px" }} onClick={onClose}>
      <div style={{ maxWidth: 720, margin: "0 auto" }} onClick={e => e.stopPropagation()}>
        <div style={{ position: "relative" }}>
          <input ref={ref} className="input" placeholder="Search tournaments, teams, players, news…" value={q} onChange={e => setQ(e.target.value)} style={{ padding: "20px 24px 20px 56px", fontSize: 18, background: "var(--surface)", borderColor: "var(--cyan)" }} />
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--cyan)" strokeWidth="2" style={{ position: "absolute", left: 20, top: "50%", transform: "translateY(-50%)" }}>
            <circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" />
          </svg>
          <button onClick={onClose} className="pill" style={{ position: "absolute", right: 16, top: "50%", transform: "translateY(-50%)", background: "var(--ink)", border: "1px solid var(--line)" }}>ESC</button>
        </div>
        {q && (
          <div style={{ marginTop: 16, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 8, padding: 8 }}>
            {[["Tournaments", tournaments, (t) => go("tournament", { id: t.id }), (t) => t.name],
              ["Teams", teams, (t) => go("team", { id: t.id }), (t) => t.name],
              ["Players", players, (p) => go("player", { id: p.id }), (p) => `${p.handle} · ${p.realName}`]
             ].map(([label, list, navFn, render]) => list.length ? (
              <div key={label} style={{ padding: "8px 4px" }}>
                <div className="t-eyebrow" style={{ padding: "4px 12px" }}>{label}</div>
                {list.map((it, i) => (
                  <div key={i} onClick={() => { navFn(it); onClose(); }} style={{ padding: "10px 12px", borderRadius: 4, cursor: "pointer", display: "flex", alignItems: "center", gap: 10 }} onMouseEnter={e => e.currentTarget.style.background = "var(--surface-3)"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <span>{render(it)}</span>
                  </div>
                ))}
              </div>
            ) : null)}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Social icons (SVG, no emojis) ──────────────────────────────────────────
function SocialIcon({ name, size = 16 }) {
  const props = { width: size, height: size, viewBox: "0 0 24 24", fill: "currentColor", style: { display: "block" } };
  if (name === "twitter")   return <svg {...props}><path d="M18.244 2H21.5l-7.39 8.45L23 22h-6.84l-5.36-7-6.13 7H1.5l7.91-9.04L1 2h7.02l4.83 6.4L18.24 2Zm-2.4 18.18h1.85L7.27 3.73H5.3L15.84 20.18Z"/></svg>;
  if (name === "discord")   return <svg {...props}><path d="M20.32 4.37A18.5 18.5 0 0 0 16 3l-.2.4a16.6 16.6 0 0 1 4 1.6 14.9 14.9 0 0 0-7.8 0 16.6 16.6 0 0 1 4-1.6L15.8 3a18.5 18.5 0 0 0-4.32 1.37C8 7.8 7.18 11.13 7.4 14.42a14.9 14.9 0 0 0 4.6 2.32c.4-.6.8-1.2 1.1-1.84a10 10 0 0 1-1.74-.84l.4-.32a13.4 13.4 0 0 0 8.48 0l.4.32a10 10 0 0 1-1.74.84c.3.64.7 1.24 1.1 1.84a14.9 14.9 0 0 0 4.6-2.32c.32-3.83-.66-7.13-3.18-10.05ZM10.78 12.7c-.7 0-1.28-.66-1.28-1.46 0-.8.56-1.46 1.28-1.46.7 0 1.28.66 1.28 1.46-.02.8-.58 1.46-1.28 1.46Zm6.44 0c-.7 0-1.28-.66-1.28-1.46 0-.8.56-1.46 1.28-1.46.7 0 1.28.66 1.28 1.46 0 .8-.56 1.46-1.28 1.46Z"/></svg>;
  if (name === "twitch")    return <svg {...props}><path d="M4.265 3 3 6.36v13.65h4.667V22h2.6l1.99-1.99h3.32L21 14.236V3H4.265Zm2.067 1.733h12.935v8.502l-3.32 3.32h-3.32l-1.99 1.99v-1.99h-4.305V4.733ZM9.41 7.99v4.667h1.733V7.99H9.41Zm4.667 0v4.667h1.733V7.99h-1.733Z"/></svg>;
  if (name === "youtube")   return <svg {...props}><path d="M23.5 6.2a3 3 0 0 0-2.1-2.1C19.6 3.6 12 3.6 12 3.6s-7.6 0-9.4.5A3 3 0 0 0 .5 6.2C0 8 0 12 0 12s0 4 .5 5.8a3 3 0 0 0 2.1 2.1c1.8.5 9.4.5 9.4.5s7.6 0 9.4-.5a3 3 0 0 0 2.1-2.1C24 16 24 12 24 12s0-4-.5-5.8ZM9.6 15.6V8.4l6.4 3.6-6.4 3.6Z"/></svg>;
  if (name === "instagram") return <svg {...props}><path d="M12 2.16c3.2 0 3.58 0 4.85.07a6.6 6.6 0 0 1 2.23.42 4 4 0 0 1 2.27 2.27 6.6 6.6 0 0 1 .42 2.23c.06 1.27.07 1.65.07 4.85s0 3.58-.07 4.85a6.6 6.6 0 0 1-.42 2.23 4 4 0 0 1-2.27 2.27 6.6 6.6 0 0 1-2.23.42c-1.27.06-1.65.07-4.85.07s-3.58 0-4.85-.07a6.6 6.6 0 0 1-2.23-.42 4 4 0 0 1-2.27-2.27 6.6 6.6 0 0 1-.42-2.23C2.17 15.58 2.16 15.2 2.16 12s0-3.58.07-4.85a6.6 6.6 0 0 1 .42-2.23 4 4 0 0 1 2.27-2.27 6.6 6.6 0 0 1 2.23-.42C8.42 2.17 8.8 2.16 12 2.16ZM12 6.84a5.16 5.16 0 1 0 0 10.32 5.16 5.16 0 0 0 0-10.32Zm0 8.51a3.35 3.35 0 1 1 0-6.7 3.35 3.35 0 0 1 0 6.7Zm6.56-8.72a1.2 1.2 0 1 1-2.4 0 1.2 1.2 0 0 1 2.4 0Z"/></svg>;
  if (name === "tiktok")    return <svg {...props}><path d="M19.32 6.69a5.45 5.45 0 0 1-3.18-1.02 5.45 5.45 0 0 1-2.13-3.5H10.7v11.96a3.3 3.3 0 0 1-3.3 3.3 3.3 3.3 0 0 1-3.3-3.3 3.3 3.3 0 0 1 3.3-3.3c.34 0 .67.05.98.15v-3.4a6.7 6.7 0 0 0-7.62 6.55A6.7 6.7 0 0 0 7.4 21a6.7 6.7 0 0 0 6.7-6.7v-5.94a8.85 8.85 0 0 0 5.22 1.7v-3.37Z"/></svg>;
  return null;
}

// ─── Newsletter form in footer ───────────────────────────────────────────────
function FooterNewsletter() {
  const [email, setEmail] = useState("");
  const [status, setStatus] = useState("idle"); // idle | sending | ok | err
  const [msg, setMsg] = useState("");
  const onSubmit = async (e) => {
    e.preventDefault();
    setStatus("sending");
    const r = await window.VexelAPI.newsletter(email, "footer");
    if (r.ok) { setStatus("ok"); setEmail(""); }
    else      { setStatus("err"); setMsg(r.error || "Please try again."); }
  };
  if (status === "ok") {
    return <div style={{ color: "var(--lime)", fontSize: 14 }}>You're on the list. First letter ships Friday.</div>;
  }
  return (
    <form onSubmit={onSubmit} style={{ display: "flex", gap: 0, alignItems: "stretch" }}>
      <input className="input" placeholder="your@email.com" required value={email} onChange={e => setEmail(e.target.value)}
             style={{ borderRadius: "4px 0 0 4px" }} />
      <button className="btn btn-primary" type="submit" disabled={status === "sending"}
              style={{ borderRadius: "0 4px 4px 0" }}>
        {status === "sending" ? "..." : "Subscribe"}
      </button>
      {status === "err" && <div style={{ color: "var(--red)", fontSize: 12, marginLeft: 8 }}>{msg}</div>}
    </form>
  );
}

// ─── Header ──────────────────────────────────────────────────────────────────
function Header({ route, go, signedIn, setSignedIn, lang, setLang, currency, setCurrency }) {
  const [searchOpen, setSearchOpen] = useState(false);
  const [menu, setMenu] = useState(false);
  const liveCount = TOURNAMENTS.filter(t => t.status === "live").length;
  const liveTickers = TOURNAMENTS.filter(t => t.status === "live").map(t => `${t.name} · ${gameById(t.game).name} · ${fmtAED(t.prize)}`);
  const tickers = [...liveTickers, ...liveTickers, ...liveTickers];

  const navLinks = [
    ["Tournaments", "tournaments"],
    ["Live", "live"],
    ["Teams", "teams"],
    ["Players", "players"],
    ["News", "news"],
    ["Store", "store"],
    ["Partners", "partners"],
  ];

  return (
    <header style={{ position: "sticky", top: 0, zIndex: 50, background: "rgba(10,10,15,0.92)", backdropFilter: "blur(8px)", borderBottom: "1px solid var(--line)" }}>
      {/* Top utility strip */}
      <div style={{ height: "var(--strip-h)", borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", overflow: "hidden", position: "relative", background: "var(--ink-2)" }}>
        <div style={{ flexShrink: 0, padding: "0 16px", display: "flex", alignItems: "center", gap: 8, borderRight: "1px solid var(--line)", height: "100%", background: "var(--ink)" }}>
          <span className="dot-live" />
          <span className="t-mono" style={{ fontSize: 11, color: "var(--orange)", letterSpacing: "0.12em" }}>LIVE NOW · {liveCount} MATCHES</span>
        </div>
        <div style={{ flex: 1, overflow: "hidden" }}>
          <div className="marquee-track" style={{ animationDuration: "60s" }}>
            {tickers.map((t, i) => (
              <span key={i} className="t-mono" style={{ fontSize: 11, color: "var(--text-dim)", letterSpacing: "0.1em", whiteSpace: "nowrap" }}>
                <span style={{ color: "var(--magenta)", marginRight: 8 }}>◆</span>{t}
              </span>
            ))}
          </div>
        </div>
      </div>

      {/* Main nav */}
      <div style={{ height: "var(--nav-h)", display: "flex", alignItems: "center", padding: "0 var(--gutter)", gap: 32 }}>
        <a onClick={() => go("home")} style={{ cursor: "pointer" }}><Wordmark /></a>
        <nav style={{ display: "flex", gap: 4, flex: 1 }}>
          {navLinks.map(([label, key]) => {
            const active = route.name === key || (key === "tournaments" && route.name === "tournament") || (key === "teams" && route.name === "team") || (key === "players" && route.name === "player") || (key === "news" && route.name === "article");
            return (
              <a key={key} onClick={() => go(key)} style={{
                cursor: "pointer",
                padding: "8px 14px",
                fontSize: 13,
                fontWeight: 600,
                letterSpacing: "0.06em",
                textTransform: "uppercase",
                color: active ? "var(--cyan)" : "var(--text)",
                position: "relative",
              }}>
                {label}
                {active && <span style={{ position: "absolute", bottom: -22, left: "50%", transform: "translateX(-50%)", width: 32, height: 2, background: "var(--cyan)", boxShadow: "0 0 8px var(--cyan)" }} />}
              </a>
            );
          })}
        </nav>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <button onClick={() => setSearchOpen(true)} aria-label="Search" style={{ display: "flex", alignItems: "center", color: "var(--text-dim)" }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7" /><path d="M21 21l-4.3-4.3" /></svg>
          </button>
          {/* lang */}
          <div style={{ display: "flex", border: "1px solid var(--line)", borderRadius: 4, overflow: "hidden" }}>
            {["EN", "AR"].map(l => (
              <button key={l} onClick={() => setLang(l)} style={{ padding: "4px 8px", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.08em", background: lang === l ? "var(--cyan)" : "transparent", color: lang === l ? "var(--ink)" : "var(--text-dim)" }}>{l}</button>
            ))}
          </div>
          {/* currency */}
          <div style={{ display: "flex", border: "1px solid var(--line)", borderRadius: 4, overflow: "hidden" }}>
            {["AED", "USD"].map(c => (
              <button key={c} onClick={() => setCurrency(c)} style={{ padding: "4px 8px", fontSize: 11, fontFamily: "var(--font-mono)", letterSpacing: "0.08em", background: currency === c ? "var(--cyan)" : "transparent", color: currency === c ? "var(--ink)" : "var(--text-dim)" }}>{c}</button>
            ))}
          </div>

          {signedIn ? (
            <>
              <button aria-label="Cart" style={{ color: "var(--text-dim)" }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="9" cy="21" r="1" /><circle cx="20" cy="21" r="1" /><path d="M1 1h4l2.7 13.4a2 2 0 0 0 2 1.6h9.7a2 2 0 0 0 2-1.6L23 6H6" /></svg>
              </button>
              <button onClick={() => go("dashboard")} style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 4px 4px 12px", border: "1px solid var(--line)", borderRadius: 999 }}>
                <span style={{ fontSize: 12, fontWeight: 600 }}>sandstorm</span>
                <div style={{ width: 28, height: 28, borderRadius: "50%", background: `linear-gradient(135deg, var(--cyan), var(--magenta))`, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 700, color: "var(--ink)" }}>S</div>
              </button>
            </>
          ) : (
            <>
              <button onClick={() => go("signin")} className="btn btn-ghost btn-sm">Sign in</button>
              <button onClick={() => go("signin", { register: true })} className="btn btn-primary btn-sm">Register</button>
            </>
          )}
        </div>
      </div>
      <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)} go={go} />
    </header>
  );
}

// ─── Footer ──────────────────────────────────────────────────────────────────
function Footer({ go }) {
  const cols = [
    ["Platform", [["Tournaments", "tournaments"], ["Live matches", "live"], ["Teams", "teams"], ["Rankings", "players"], ["Store", "store"]]],
    ["Community", [
      ["The Drop (News)", "news"],
      ["Partners", "partners"],
      ["Discord",   { url: "https://discord.gg/vexel" }],
      ["X / Twitter", { url: "https://x.com/vexel" }],
      ["Twitch",    { url: "https://twitch.tv/vexel" }]
    ]],
    ["Company", [
      ["About", "about"], ["Careers", "careers"], ["Contact", "contact"],
      ["Press kit", "press"],
      ["Trade licence", "about"]
    ]],
    ["Help", [
      ["FAQ", "faq"],
      ["Anti-cheat policy", "anticheat"],
      ["Code of conduct", "conduct"],
      ["Privacy", "privacy"],
      ["Terms", "terms"]
    ]],
  ];

  return (
    <footer style={{ background: "var(--ink-2)", borderTop: "1px solid var(--line)", marginTop: 80 }}>
      {/* Newsletter strip */}
      <div className="bg-grid" style={{ borderBottom: "1px solid var(--line)", padding: "48px var(--gutter)" }}>
        <div style={{ maxWidth: "var(--max)", margin: "0 auto", display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 48, alignItems: "center" }}>
          <div>
            <div className="t-eyebrow" style={{ color: "var(--cyan)" }}>The Weekly Drop</div>
            <h3 className="t-display" style={{ fontSize: 44, marginTop: 8 }}>One newsletter. <span className="italic-accent">Every Friday.</span></h3>
            <p style={{ color: "var(--text-dim)", marginTop: 10, maxWidth: 520 }}>Tournament recaps, regional rankings, locker-room interviews, and the meta moves that matter — straight from the Gulf.</p>
          </div>
          <FooterNewsletter />
        </div>
      </div>

      {/* Partner publishers strip */}
      <div style={{ borderBottom: "1px solid var(--line)", padding: "24px var(--gutter)", overflow: "hidden" }}>
        <div style={{ maxWidth: "var(--max)", margin: "0 auto", display: "flex", flexWrap: "wrap", gap: 32, alignItems: "center", justifyContent: "space-between" }}>
          <span className="t-eyebrow">Partner Publishers</span>
          <div style={{ display: "flex", gap: 32, flexWrap: "wrap", color: "var(--text-mute)", fontFamily: "var(--font-display-tight)", letterSpacing: "-0.02em", fontSize: 18 }}>
            {["RIOT GAMES", "VALVE", "EA SPORTS", "BANDAI NAMCO", "TENCENT", "ACTIVISION", "GARENA", "MOONTON"].map(p => (
              <span key={p} style={{ transition: "color 0.15s" }} onMouseEnter={e => e.currentTarget.style.color = "var(--cyan)"} onMouseLeave={e => e.currentTarget.style.color = "var(--text-mute)"}>{p}</span>
            ))}
          </div>
        </div>
      </div>

      <div style={{ padding: "56px var(--gutter)" }}>
        <div style={{ maxWidth: "var(--max)", margin: "0 auto", display: "grid", gridTemplateColumns: "1.4fr repeat(4, 1fr)", gap: 48 }}>
          <div>
            <Wordmark size={28} />
            <p style={{ color: "var(--text-dim)", marginTop: 16, maxWidth: 320, fontSize: 14 }}>Where the Gulf plays. Tournaments, teams, rankings and live broadcasts — built in Dubai, played across the region.</p>
            <div style={{ display: "flex", gap: 10, marginTop: 20 }}>
              {[
                ["twitter",   "https://x.com/vexel",         "Twitter / X"],
                ["discord",   "https://discord.gg/vexel",    "Discord"],
                ["twitch",    "https://twitch.tv/vexel",     "Twitch"],
                ["youtube",   "https://youtube.com/@vexel",  "YouTube"],
                ["instagram", "https://instagram.com/vexel", "Instagram"],
                ["tiktok",    "https://tiktok.com/@vexel",   "TikTok"]
              ].map(([icon, url, lbl]) => (
                <a key={lbl} href={url} target="_blank" rel="noopener" aria-label={lbl}
                   style={{ width: 36, height: 36, border: "1px solid var(--line)", borderRadius: 4, display: "flex", alignItems: "center", justifyContent: "center", color: "var(--text-dim)", cursor: "pointer", transition: "all 0.15s", textDecoration: "none" }}
                   onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--cyan)"; e.currentTarget.style.color = "var(--cyan)"; }}
                   onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.color = "var(--text-dim)"; }}>
                  <SocialIcon name={icon} />
                </a>
              ))}
            </div>
          </div>
          {cols.map(([title, items]) => (
            <div key={title}>
              <div className="t-eyebrow" style={{ color: "var(--white)", marginBottom: 14 }}>{title}</div>
              <ul style={{ listStyle: "none", display: "flex", flexDirection: "column", gap: 10 }}>
                {items.map(([l, k]) => {
                  // k can be: a string (internal route), an object {url} (external), or null/undefined
                  const isExternal = k && typeof k === "object" && k.url;
                  if (isExternal) {
                    return <li key={l}><a href={k.url} target="_blank" rel="noopener" style={{ color: "var(--text-dim)", fontSize: 13, cursor: "pointer", transition: "color 0.15s" }} onMouseEnter={e => e.currentTarget.style.color = "var(--cyan)"} onMouseLeave={e => e.currentTarget.style.color = "var(--text-dim)"}>{l}</a></li>;
                  }
                  return <li key={l}><a onClick={() => typeof k === "string" && go(k)} style={{ color: "var(--text-dim)", fontSize: 13, cursor: typeof k === "string" ? "pointer" : "default", transition: "color 0.15s" }} onMouseEnter={e => e.currentTarget.style.color = "var(--cyan)"} onMouseLeave={e => e.currentTarget.style.color = "var(--text-dim)"}>{l}</a></li>;
                })}
              </ul>
            </div>
          ))}
        </div>

        {/* Legal strip */}
        <div style={{ maxWidth: "var(--max)", margin: "48px auto 0", paddingTop: 24, borderTop: "1px solid var(--line)", display: "flex", flexWrap: "wrap", justifyContent: "space-between", gap: 16, fontSize: 12, color: "var(--text-mute)", fontFamily: "var(--font-mono)" }}>
          <div>© 2026 Wakefield Project Management · Trade Licence No. 1167116 · Owner: Ibrahim Hussain Ahli · Dubai, UAE</div>
          <div style={{ display: "flex", gap: 20 }}>
            <a onClick={() => go("privacy")}   style={{ cursor: "pointer" }}>Privacy</a>
            <a onClick={() => go("terms")}     style={{ cursor: "pointer" }}>Terms</a>
            <a onClick={() => go("conduct")}   style={{ cursor: "pointer" }}>Code of Conduct</a>
            <a onClick={() => go("anticheat")} style={{ cursor: "pointer" }}>Anti-cheat</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// ─── Cookie banner ───────────────────────────────────────────────────────────
function CookieBanner() {
  const [open, setOpen] = useState(() => !localStorage.getItem("vexel-cookies"));
  if (!open) return null;
  const dismiss = () => { localStorage.setItem("vexel-cookies", "1"); setOpen(false); };
  return (
    <div style={{ position: "fixed", left: 24, bottom: 24, right: 24, maxWidth: 520, zIndex: 60, background: "var(--surface)", border: "1px solid var(--line-2)", borderRadius: 8, padding: 20, boxShadow: "0 20px 60px rgba(0,0,0,0.6)" }}>
      <div style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
        <div style={{ width: 32, height: 32, borderRadius: 6, background: "var(--cyan)", color: "var(--ink)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2a10 10 0 1 0 10 10c-3.8 0-7-3.2-7-7 0-1-.2-2-.5-3 .07-.005-1.7-.005-2.5-.005Zm-1.5 5a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Zm7 5a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Zm-9 4a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z"/></svg>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 6 }}>Cookies. Probably not the kind you want.</div>
          <p style={{ fontSize: 13, color: "var(--text-dim)", marginBottom: 14 }}>We use them to keep matches in sync, remember your favourite teams, and learn what the GCC scene actually watches.</p>
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={dismiss} className="btn btn-primary btn-sm">Accept all</button>
            <button onClick={dismiss} className="btn btn-dark btn-sm">Only essential</button>
            <button onClick={dismiss} className="btn btn-dark btn-sm" style={{ marginLeft: "auto" }}>Customise</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Logo, Wordmark, GameGlyph, TeamLogo, Flag, LiveBadge, Countdown, NumberTicker, Header, Footer, CookieBanner });
