/* Shared UI primitives */

function Flag({ country, size = 20 }) {
  const f = (window.WC.FLAG || {})[country] || "🏳";
  return <span className="flag" style={{ fontSize: size }}>{f}</span>;
}

function PosPill({ pos }) {
  return <span className={"pos " + pos}>{pos}</span>;
}

function PlayerAvatar({ player, size = 40 }) {
  const initials = player.name.split(" ").map((w) => w[0]).slice(0, 2).join("");
  const tint = { GK: "var(--gk)", DF: "var(--df)", MF: "var(--mf)", FW: "var(--fw)" }[player.pos];
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%", flex: "none",
      display: "flex", alignItems: "center", justifyContent: "center",
      background: `color-mix(in oklch, ${tint} 22%, var(--surface-2))`,
      border: `1.5px solid color-mix(in oklch, ${tint} 45%, transparent)`,
      fontFamily: "var(--font-display)", fontWeight: 800,
      fontSize: size * 0.38, color: tint, letterSpacing: "-.02em",
    }}>{initials}</div>
  );
}

function ManagerDot({ m, size = 26, ring = false }) {
  const initials = m.you ? "★" : (m.name[0] || "?").toUpperCase();
  return (
    <div title={m.name} style={{
      width: size, height: size, borderRadius: "50%", flex: "none",
      display: "flex", alignItems: "center", justifyContent: "center",
      background: m.color, color: "#fff",
      fontFamily: "var(--font-display)", fontWeight: 800, fontSize: size * 0.46,
      boxShadow: ring ? `0 0 0 3px color-mix(in oklch, ${m.color} 30%, transparent)` : "none",
    }}>{initials}</div>
  );
}

function Crest({ size = 32 }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: "9px 9px 11px 11px",
      background: "var(--accent)", display: "flex", alignItems: "center", justifyContent: "center",
      boxShadow: "0 4px 10px -4px var(--accent)", flex: "none",
    }}>
      <div style={{ width: size * 0.42, height: size * 0.42, borderRadius: "50%", border: `${Math.max(2, size * 0.09)}px solid var(--accent-ink)` }}></div>
    </div>
  );
}

function StatBlock({ label, value, accent }) {
  return (
    <div className="col" style={{ gap: 2 }}>
      <span className="display num" style={{ fontSize: 30, color: accent || "var(--text)" }}>{value}</span>
      <span className="kicker" style={{ fontSize: 11 }}>{label}</span>
    </div>
  );
}

function SectionTitle({ kicker, title, right }) {
  return (
    <div className="row between" style={{ marginBottom: 18, alignItems: "flex-end", flexWrap: "wrap", gap: 12 }}>
      <div className="col" style={{ gap: 9 }}>
        {kicker && <span className="kicker" style={{ lineHeight: 1.2 }}>{kicker}</span>}
        <h2 className="display" style={{ fontSize: 34, lineHeight: 1.05 }}>{title}</h2>
      </div>
      {right}
    </div>
  );
}

function TopBar({ screen, go, league, theme, setTheme, onLeave }) {
  const tabs = [
    ["draft", "Draft"],
    ["leaderboard", "Table"],
    ["teams", "Squads"],
    ["players", "Players"],
  ];
  const inLeague = !!league;
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 40,
      background: "color-mix(in oklch, var(--bg) 86%, transparent)",
      backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
      borderBottom: "1px solid var(--line)",
    }}>
      <div className="wrap row between" style={{ height: 64, gap: 16 }}>
        <button onClick={() => go("home")} className="row gap-2" style={{ background: "none", border: "none", cursor: "pointer", padding: 0 }}>
          <Crest size={30} />
          <span className="display" style={{ fontSize: 22, color: "var(--text)" }}>
            FWC<span style={{ color: "var(--accent)" }}>26</span>
          </span>
        </button>

        {inLeague && (
          <nav className="row nav-tabs" style={{ flex: 1, justifyContent: "center", gap: 26 }}>
            {tabs.map(([id, label]) => (
              <button key={id} onClick={() => go(id)} className="display nav-tab"
                style={{
                  background: "none", border: "none", cursor: "pointer",
                  fontSize: 17, letterSpacing: ".03em", textTransform: "uppercase",
                  padding: "8px 4px", color: screen === id ? "var(--text)" : "var(--muted)",
                  borderBottom: screen === id ? "3px solid var(--accent)" : "3px solid transparent",
                }}>{label}</button>
            ))}
          </nav>
        )}

        <div className="row gap-3">
          {inLeague && (
            <div className="chip" title="Leave league" onClick={onLeave} style={{ borderColor: "var(--accent)", color: "var(--text)", whiteSpace: "nowrap", cursor: onLeave ? "pointer" : "default" }}>
              <span className="dot" style={{ background: "var(--accent)" }}></span>
              {league.name}
            </div>
          )}
          <button
            onClick={() => setTheme(theme === "light" ? "dark" : theme === "dark" ? "system" : "light")}
            className="btn btn-soft btn-sm"
            title={"Theme: " + theme + " — click to cycle (light → dark → system)"}
            style={{ padding: "9px 12px" }}
          >
            {theme === "light" ? "☀" : theme === "dark" ? "☾" : "🖥"}
          </button>
        </div>
      </div>
    </header>
  );
}

function MobileNav({ screen, go }) {
  const tabs = [["draft", "Draft"], ["leaderboard", "Table"], ["teams", "Squads"], ["players", "Players"]];
  return (
    <nav className="mobile-nav" style={{
      position: "fixed", bottom: 0, left: 0, right: 0, zIndex: 45,
      background: "color-mix(in oklch, var(--bg) 92%, transparent)",
      backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)",
      borderTop: "1px solid var(--line)", padding: "8px 10px calc(8px + env(safe-area-inset-bottom))",
    }}>
      <div className="row" style={{ justifyContent: "space-around" }}>
        {tabs.map(([id, label]) => (
          <button key={id} onClick={() => go(id)} className="display" style={{
            background: "none", border: "none", cursor: "pointer", flex: 1,
            fontSize: 14, textTransform: "uppercase", letterSpacing: ".03em", padding: "10px 4px",
            color: screen === id ? "var(--accent)" : "var(--muted)", minHeight: 44,
          }}>{label}</button>
        ))}
      </div>
    </nav>
  );
}

function Spinner({ label }) {
  return (
    <div className="wrap col" style={{ paddingTop: 120, paddingBottom: 120, alignItems: "center", gap: 16 }}>
      <Crest size={48} />
      <span className="kicker">{label || "Loading…"}</span>
    </div>
  );
}

function ErrorBanner({ msg, onDismiss }) {
  if (!msg) return null;
  return (
    <div className="wrap" style={{ paddingTop: 16 }}>
      <div className="panel row between" style={{ padding: "12px 16px", borderColor: "var(--fw)", background: "color-mix(in oklch, var(--fw) 12%, var(--surface))" }}>
        <span style={{ color: "var(--text)" }}>{msg}</span>
        {onDismiss && <button className="btn btn-soft btn-sm" onClick={onDismiss}>Dismiss</button>}
      </div>
    </div>
  );
}

Object.assign(window, { Flag, PosPill, PlayerAvatar, ManagerDot, TopBar, MobileNav, Crest, StatBlock, SectionTitle, Spinner, ErrorBanner });
