/* Home (marquee) + Create + Join + Lobby — wired to the real API. */

function ScoringChip() {
  return (
    <div className="row gap-3 wrap-flex" style={{ justifyContent: "inherit" }}>
      <span className="chip"><b className="num" style={{ color: "var(--fw)" }}>1.0</b>&nbsp;pt&nbsp;/&nbsp;goal</span>
      <span className="chip"><b className="num" style={{ color: "var(--df)" }}>0.5</b>&nbsp;pt&nbsp;/&nbsp;assist</span>
      <span className="chip"><b className="num" style={{ color: "var(--accent-2)" }}>+1</b>&nbsp;GWG&nbsp;bonus</span>
    </div>
  );
}

function HomeCTAs({ go, center }) {
  return (
    <div className="col gap-3" style={{ alignItems: center ? "center" : "flex-start" }}>
      <div className="row gap-3 wrap-flex" style={{ justifyContent: center ? "center" : "flex-start" }}>
        <button className="btn btn-primary" onClick={() => go("create")} style={{ fontSize: 19, padding: "16px 30px" }}>
          Create a league →
        </button>
        <button className="btn btn-ghost" onClick={() => go("join")} style={{ fontSize: 19, padding: "16px 30px" }}>
          Join with a code
        </button>
      </div>
      <button onClick={() => go("recover")} className="btn btn-soft btn-sm" style={{ color: "var(--muted)" }}>
        Lost access? Recover with your PIN
      </button>
    </div>
  );
}

const FEATURES = [
  ["01", "Draft", "Snake-draft real players from all 48 nations. No two managers share a star.", "var(--mf)"],
  ["02", "Score", "Every goal and assist your players rack up at the tournament banks you points.", "var(--accent-2)"],
  ["03", "Argue", "A live leaderboard settles who actually knows football. Group chat does the rest.", "var(--fw)"],
];

function FeatureRow() {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit,minmax(230px,1fr))", gap: 16 }}>
      {FEATURES.map(([n, t, d, c]) => (
        <div key={n} className="panel" style={{ padding: 22 }}>
          <div className="display num" style={{ fontSize: 15, color: c, letterSpacing: ".1em" }}>{n}</div>
          <div className="display" style={{ fontSize: 26, marginTop: 6 }}>{t}</div>
          <p style={{ margin: "8px 0 0", color: "var(--muted)", fontSize: 15.5, lineHeight: 1.45 }}>{d}</p>
        </div>
      ))}
    </div>
  );
}

/* Live top-scorer feed from the global player pool (no league required). */
function TopScorerList({ n = 6 }) {
  const [top, setTop] = React.useState(null);
  React.useEffect(() => {
    let cancelled = false;
    window.WC.api("/api/players?limit=" + n).then((res) => {
      if (cancelled) return;
      setTop((res.players || []).slice(0, n).map(window.WC.normPlayer));
    }).catch(() => { if (!cancelled) setTop([]); });
    return () => { cancelled = true; };
  }, [n]);

  if (top === null) {
    return <p style={{ color: "var(--faint)", fontSize: 14, margin: 0 }}>Loading scorers…</p>;
  }
  if (top.length === 0) {
    return <p style={{ color: "var(--faint)", fontSize: 14, margin: 0 }}>No goals scored yet — tournament hasn't kicked off.</p>;
  }
  return (
    <div className="col">
      {top.map((p, i) => (
        <div key={p.id} className="row between" style={{
          padding: "11px 4px", borderBottom: i < top.length - 1 ? "1px solid var(--line-soft)" : "none", gap: 12,
        }}>
          <div className="row gap-3" style={{ minWidth: 0 }}>
            <span className="display num" style={{ width: 22, color: "var(--faint)", fontSize: 17 }}>{i + 1}</span>
            <Flag country={p.country} size={18} />
            <span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</span>
            <PosPill pos={p.pos} />
          </div>
          <span className="display num" style={{ fontSize: 20, color: "var(--accent-2)" }}>{p.pts.toFixed(1)}</span>
        </div>
      ))}
    </div>
  );
}

function FlagStrip() {
  const cs = Object.keys(window.WC.FLAG).sort();
  return (
    <div className="row gap-2 wrap-flex" style={{ justifyContent: "center", opacity: .95 }}>
      {cs.map((c) => <Flag key={c} country={c} size={24} />)}
    </div>
  );
}

function Home({ go }) {
  const kicker = "48 nations · 104 matches · one bragging-rights trophy";
  return (
    <div>
      <div style={{ background: "var(--pitch-img)", borderBottom: "1px solid var(--line)" }}>
        <div className="wrap" style={{ paddingTop: 70, paddingBottom: 58, textAlign: "center" }}>
          <span className="kicker">{kicker}</span>
          <h1 className="display pop" style={{ fontSize: "clamp(60px,11vw,168px)", margin: "16px 0 0", textShadow: "0 2px 0 color-mix(in oklch, var(--accent) 8%, transparent)" }}>
            Fantasy<br />World Cup <span style={{ color: "var(--accent-2)" }}>2026</span>
          </h1>
          <p style={{ fontSize: 24, color: "var(--muted)", margin: "20px auto 32px", maxWidth: 560 }}>
            Draft. Score. Argue with your friends.
          </p>
          <div style={{ marginBottom: 28 }}><HomeCTAs go={go} center /></div>
          <FlagStrip />
        </div>
      </div>
      <div className="wrap" style={{ paddingTop: 56, paddingBottom: 72 }}>
        <div className="home-marquee" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 40, alignItems: "start" }}>
          <FeatureRow />
          <div className="card" style={{ padding: 24 }}>
            <div className="row between" style={{ marginBottom: 12 }}>
              <span className="kicker">Golden Boot race</span>
              <span className="row gap-2" style={{ fontSize: 13, color: "var(--muted)" }}><span className="live-dot"></span>LIVE</span>
            </div>
            <TopScorerList n={6} />
          </div>
        </div>
      </div>
    </div>
  );
}

function PinField({ pin, setPin, label = "Recovery PIN (optional)", hint = "4–6 digits. Lets you recover access if you lose your device or clear your browser." }) {
  return (
    <>
      <label className="kicker" style={{ display: "block", margin: "22px 0 8px" }}>{label}</label>
      <input
        className="field num"
        type="text"
        inputMode="numeric"
        autoComplete="off"
        pattern="\d{4,6}"
        maxLength={6}
        value={pin}
        onChange={(e) => setPin(e.target.value.replace(/\D/g, "").slice(0, 6))}
        placeholder="e.g. 1234"
      />
      {hint && <p style={{ color: "var(--muted)", fontSize: 13, marginTop: 6 }}>{hint}</p>}
    </>
  );
}

/* ---------------- Create league ---------------- */
function CreateLeague({ go, onCreated }) {
  const [name, setName] = React.useState("Sunday League");
  const [myName, setMyName] = React.useState("");
  const [pin, setPin] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async () => {
    setErr(null);
    if (!myName.trim()) { setErr("Enter your name so your friends know who's drafting."); return; }
    if (pin && !/^\d{4,6}$/.test(pin)) { setErr("PIN must be 4–6 digits (or leave blank)."); return; }
    setBusy(true);
    try {
      const body = { name: name.trim(), creator_name: myName.trim() };
      if (pin) body.creator_pin = pin;
      const res = await window.WC.api("/api/leagues", { method: "POST", body: JSON.stringify(body) });
      window.WC.STORE.setMember(res.league_id, res.member_id);
      window.WC.STORE.setCurrentLeague(res.league_id);
      onCreated(res.league_id);
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  return (
    <div className="wrap" style={{ maxWidth: 560, paddingTop: 48, paddingBottom: 72 }}>
      <button className="btn btn-soft btn-sm" onClick={() => go("home")} style={{ marginBottom: 20 }}>← Back</button>
      <SectionTitle kicker="New league" title="Create a league" />
      <div className="card" style={{ padding: 28 }}>
        <label className="kicker" style={{ display: "block", marginBottom: 8 }}>Your name</label>
        <input className="field" value={myName} onChange={(e) => setMyName(e.target.value)} placeholder="e.g. Zayd" autoFocus />

        <label className="kicker" style={{ display: "block", margin: "22px 0 8px" }}>League name</label>
        <input className="field" value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. The Office Cup" />

        <PinField pin={pin} setPin={setPin} />

        <p style={{ color: "var(--muted)", fontSize: 14.5, marginTop: 12 }}>
          You'll get a share link to send your friends. Choose roster size in the lobby before the draft starts.
        </p>
        {err && <p style={{ color: "var(--fw)", fontSize: 14, margin: "12px 0 0" }}>{err}</p>}
        <button className="btn btn-primary" style={{ width: "100%", marginTop: 22, justifyContent: "center", fontSize: 19, padding: 16 }}
          disabled={busy} onClick={submit}>
          {busy ? "Creating…" : "Create league & open lobby →"}
        </button>
      </div>
    </div>
  );
}

/* ---------------- Join league ---------------- */
function JoinLeague({ go, prefillCode, onJoined }) {
  const [code, setCode] = React.useState(prefillCode || "");
  const [myName, setMyName] = React.useState("");
  const [pin, setPin] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async () => {
    setErr(null);
    const c = code.trim().split("/").pop().split("?")[0].toLowerCase();
    if (!c) { setErr("Paste your invite link or league code."); return; }
    if (!myName.trim()) { setErr("Enter your name."); return; }
    if (pin && !/^\d{4,6}$/.test(pin)) { setErr("PIN must be 4–6 digits (or leave blank)."); return; }
    setBusy(true);
    try {
      const body = { display_name: myName.trim() };
      if (pin) body.pin = pin;
      const res = await window.WC.api("/api/leagues/" + encodeURIComponent(c) + "/join", { method: "POST", body: JSON.stringify(body) });
      window.WC.STORE.setMember(c, res.member_id);
      window.WC.STORE.setCurrentLeague(c);
      onJoined(c);
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  return (
    <div className="wrap" style={{ maxWidth: 560, paddingTop: 48, paddingBottom: 72 }}>
      <button className="btn btn-soft btn-sm" onClick={() => go("home")} style={{ marginBottom: 20 }}>← Back</button>
      <SectionTitle kicker="Got an invite?" title="Join a league" />
      <div className="card" style={{ padding: 28 }}>
        <label className="kicker" style={{ display: "block", marginBottom: 8 }}>League code or link</label>
        <input className="field" value={code} onChange={(e) => setCode(e.target.value)} placeholder="paste link or enter code" />

        <label className="kicker" style={{ display: "block", margin: "22px 0 8px" }}>Your name</label>
        <input className="field" value={myName} onChange={(e) => setMyName(e.target.value)} placeholder="e.g. Diego" />

        <PinField pin={pin} setPin={setPin} />

        {err && <p style={{ color: "var(--fw)", fontSize: 14, margin: "12px 0 0" }}>{err}</p>}
        <button className="btn btn-primary" style={{ width: "100%", marginTop: 18, justifyContent: "center", fontSize: 19, padding: 16 }}
          disabled={busy} onClick={submit}>
          {busy ? "Joining…" : "Join lobby →"}
        </button>
      </div>
    </div>
  );
}

/* ---------------- Recover access ---------------- */
function RecoverAccess({ go, onRecovered }) {
  const [code, setCode] = React.useState("");
  const [myName, setMyName] = React.useState("");
  const [pin, setPin] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);

  const submit = async () => {
    setErr(null);
    const c = code.trim().split("/").pop().split("?")[0].toLowerCase();
    if (!c) { setErr("Enter your league code."); return; }
    if (!myName.trim()) { setErr("Enter your manager name (as you set when joining)."); return; }
    if (!/^\d{4,6}$/.test(pin)) { setErr("Enter your 4–6 digit PIN."); return; }
    setBusy(true);
    try {
      const res = await window.WC.api("/api/leagues/" + encodeURIComponent(c) + "/recover", {
        method: "POST",
        body: JSON.stringify({ display_name: myName.trim(), pin }),
      });
      window.WC.STORE.setMember(c, res.member_id);
      window.WC.STORE.setCurrentLeague(c);
      onRecovered(c);
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  return (
    <div className="wrap" style={{ maxWidth: 560, paddingTop: 48, paddingBottom: 72 }}>
      <button className="btn btn-soft btn-sm" onClick={() => go("home")} style={{ marginBottom: 20 }}>← Back</button>
      <SectionTitle kicker="Lost access?" title="Recover with PIN" />
      <div className="card" style={{ padding: 28 }}>
        <p style={{ color: "var(--muted)", fontSize: 14.5, marginBottom: 18 }}>
          If you set a PIN when joining, enter your league code, name, and PIN to get back in.
          No PIN set? Ask whoever invited you to share your personal access link.
        </p>

        <label className="kicker" style={{ display: "block", marginBottom: 8 }}>League code</label>
        <input className="field" value={code} onChange={(e) => setCode(e.target.value)} placeholder="e.g. dkqnzk" />

        <label className="kicker" style={{ display: "block", margin: "22px 0 8px" }}>Your manager name</label>
        <input className="field" value={myName} onChange={(e) => setMyName(e.target.value)} placeholder="exactly as you set it" />

        <PinField pin={pin} setPin={setPin} label="Your PIN" hint="" />

        {err && <p style={{ color: "var(--fw)", fontSize: 14, margin: "12px 0 0" }}>{err}</p>}
        <button className="btn btn-primary" style={{ width: "100%", marginTop: 18, justifyContent: "center", fontSize: 19, padding: 16 }}
          disabled={busy} onClick={submit}>
          {busy ? "Checking…" : "Recover access →"}
        </button>
      </div>
    </div>
  );
}

/* ---------------- Lobby ---------------- */
function Lobby({ league, members, myMemberId, go, onStart, onReset }) {
  const [copied, setCopied] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [rosterSize, setRosterSize] = React.useState(league.roster_size || 5);

  const ms = members.map((m) => window.WC.normMember(m, myMemberId));
  const isHost = ms.length > 0 && ms[0].id === myMemberId;
  const slots = Math.max(ms.length + 1, 4);
  const link = location.origin + "/?join=" + league.id;
  const copy = () => { try { navigator.clipboard.writeText(link); } catch (e) {} setCopied(true); setTimeout(() => setCopied(false), 1600); };

  const start = async () => {
    setErr(null); setBusy(true);
    try { await onStart(rosterSize); } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  const reset = async () => {
    setErr(null);
    try { await onReset("full"); } catch (e) { setErr(e.message); }
  };

  return (
    <div className="wrap" style={{ maxWidth: 760, paddingTop: 48, paddingBottom: 72 }}>
      <SectionTitle kicker={league.name + " · lobby"} title="Waiting for managers" />
      <div className="card" style={{ padding: 24, marginBottom: 22 }}>
        <span className="kicker" style={{ display: "block", marginBottom: 10 }}>Invite link</span>
        <div className="row gap-3 wrap-flex">
          <div className="field num" style={{ flex: 1, minWidth: 220, display: "flex", alignItems: "center", color: "var(--muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{link}</div>
          <button className="btn btn-gold" onClick={copy}>{copied ? "Copied ✓" : "Copy link"}</button>
        </div>
      </div>

      <div className="card" style={{ padding: 24 }}>
        <div className="row between" style={{ marginBottom: 16 }}>
          <span className="display" style={{ fontSize: 24 }}>Managers <span style={{ color: "var(--muted)" }}>({ms.length})</span></span>
          <span className="chip"><span className="live-dot"></span>{ms.length} ready</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(150px,1fr))", gap: 12 }}>
          {ms.map((m, i) => (
            <div key={m.id} className="row gap-3 panel" style={{ padding: "12px 14px" }}>
              <ManagerDot m={m} size={34} />
              <div className="col" style={{ gap: 1, minWidth: 0 }}>
                <b style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.name}</b>
                <span style={{ fontSize: 12, color: "var(--accent)" }}>{i === 0 ? "host" : "ready"}</span>
              </div>
            </div>
          ))}
          {Array.from({ length: Math.max(0, slots - ms.length) }).map((_, i) => (
            <div key={i} className="row gap-3" style={{ padding: "12px 14px", borderRadius: 14, border: "1.5px dashed var(--line)", color: "var(--faint)" }}>
              <div style={{ width: 34, height: 34, borderRadius: "50%", border: "1.5px dashed var(--line)" }}></div>
              <span style={{ fontSize: 13 }}>empty seat</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 20, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
          <span className="kicker" style={{ display: "block", marginBottom: 10 }}>Players per team</span>
          <div className="row gap-2 wrap-flex">
            {[3, 4, 5, 6, 7, 8, 10, 12].map((n) => (
              <button key={n} onClick={() => setRosterSize(n)} className="display"
                style={{
                  width: 52, height: 52, borderRadius: 12, cursor: "pointer", fontSize: 22,
                  border: "1.5px solid " + (rosterSize === n ? "var(--accent)" : "var(--line)"),
                  background: rosterSize === n ? "var(--accent)" : "var(--surface-2)",
                  color: rosterSize === n ? "var(--accent-ink)" : "var(--text)",
                }}>{n}</button>
            ))}
          </div>
        </div>

        {err && <p style={{ color: "var(--fw)", fontSize: 14, margin: "14px 0 0" }}>{err}</p>}
        <button className="btn btn-primary" style={{ width: "100%", marginTop: 18, justifyContent: "center", fontSize: 17, padding: 16 }}
          disabled={busy || ms.length < 2} onClick={start}>
          {busy ? "Starting…" : ms.length < 2 ? "Need at least 2 managers" : `Randomize & start draft →`}
        </button>

        {isHost && onReset && (
          <button className="btn btn-soft btn-sm" style={{ marginTop: 12, color: "var(--fw)" }} onClick={reset}>
            ⚠ Reset & clear all picks
          </button>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Home, CreateLeague, JoinLeague, RecoverAccess, Lobby });
