/* screens-setup.jsx — unified setup for all game types. */
const { useState: useSetup } = React;

function Setup({ account, nav, onCreate, lang, setLang, gameId }) {
  const catEntry = (window.CATALOG && window.CATALOG.byId(gameId)) || { setup: { type: "players", minPlayers: 2, maxPlayers: 8 } };
  const setupCfg = catEntry.setup || { type: "players", minPlayers: 2, maxPlayers: 8 };
  const sType = setupCfg.type; // "wp"|"tfb"|"racket"|"dart"|"kniffel"|"bowling"|"players"

  const isWP = sType === "wp";
  const isTFB = sType === "tfb";
  const isRacket = sType === "racket";
  const isDart = sType === "dart";

  const defaultCount = setupCfg.minPlayers || 2;
  const maxCount = isRacket ? 2 : (setupCfg.maxPlayers || 8);
  const minCount = setupCfg.minPlayers || 1;
  const fixedCount = minCount === maxCount;

  const [step, setStep] = useSetup(0);
  const [columns, setColumns] = useSetup(2);
  const [bestOf, setBestOf] = useSetup(setupCfg.defaultBestOf || 3);
  const [startScore, setStartScore] = useSetup(setupCfg.defaultStart || 501);
  const [count, setCount] = useSetup(defaultCount);
  const [names, setNames] = useSetup(Array(defaultCount).fill(""));

  const tfbSplit = count <= 2 ? 1 : 2;
  const teamA = names.slice(0, tfbSplit);
  const teamB = names.slice(tfbSplit);
  const teamAName = teamA.filter(Boolean).join(" & ") || "Team 1";
  const teamBName = teamB.filter(Boolean).join(" & ") || "Team 2";

  function setCountSafe(n) {
    setCount(n);
    setNames((prev) => { const next = prev.slice(0, n); while (next.length < n) next.push(""); return next; });
  }

  function start() { onCreate({ game: gameId, columns, bestOf, startScore, players: names }); }

  const gameNameKey = "game." + gameId + ".name";
  const gameIcon = catEntry.icon || "dice";

  return (
    <div className="app">
      <AppHeader account={account} nav={nav} onSignOut={() => {}} crumb={t("setup.crumb")} lang={lang} setLang={setLang} />
      <main className="wrap" style={{ flex: 1, display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "30px 24px 60px" }}>
        <div style={{ width: "100%", maxWidth: 520 }}>
          <button className="btn ghost sm" onClick={() => step === 0 ? nav("#/") : setStep(0)} style={{ marginBottom: 14, paddingLeft: 6 }}>
            <Icon name="back" size={16} />{step === 0 ? t("nav.dashboard") : t("nav.back")}
          </button>

          <div className="card" style={{ padding: 30 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 4 }}>
              <div className="game-icon" style={{ width: 44, height: 44, color: "var(--accent)" }}>
                <Icon name={gameIcon} size={22} />
              </div>
              <div>
                <h2 style={{ fontSize: 22 }}>{t(gameNameKey)}</h2>
                <span className="muted" style={{ fontSize: 13.5 }}>{step === 0 ? (isTFB ? t("setup.step0tfb") : t("setup.step0")) : t("setup.step1")}</span>
              </div>
              <span className="steps-dots" style={{ marginLeft: "auto" }}>
                <i className={step === 0 ? "on" : ""}></i>
                <i className={step === 1 ? "on" : ""}></i>
              </span>
            </div>

            <div className="divider" style={{ margin: "20px 0" }}></div>

            {step === 0 ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
                {/* WP columns */}
                {isWP && (
                  <SetupRow icon="grid" title={t("setup.columns")} sub={t("setup.columnsDesc")}>
                    <Stepper value={columns} min={1} max={6} onChange={setColumns} />
                  </SetupRow>
                )}
                {/* Racket: best-of */}
                {isRacket && (
                  <SetupRow icon="trophy" title={t("setup.bestof")} sub="">
                    <div style={{ display: "flex", gap: 8 }}>
                      {(setupCfg.bestOfOptions || [3, 5]).map((v) => (
                        <button key={v} className={"btn sm" + (bestOf === v ? " primary" : "")} onClick={() => setBestOf(v)}>{v}</button>
                      ))}
                    </div>
                  </SetupRow>
                )}
                {/* Dart: start score */}
                {isDart && (
                  <SetupRow icon="dart" title={t("setup.startScore")} sub="">
                    <div style={{ display: "flex", gap: 8 }}>
                      {(setupCfg.startOptions || [301, 501, 701]).map((v) => (
                        <button key={v} className={"btn sm" + (startScore === v ? " primary" : "")} onClick={() => setStartScore(v)}>{v}</button>
                      ))}
                    </div>
                  </SetupRow>
                )}
                {/* Player count */}
                {!isRacket && (
                  <SetupRow icon="users" title={t("setup.players")} sub={isTFB ? t("setup.teamHint") : fixedCount ? t("setup.playersFixed", { n: minCount }) : t("setup.playersDesc")}>
                    {fixedCount
                      ? <div className="round-pill">{minCount}</div>
                      : <Stepper value={count} min={minCount} max={maxCount} onChange={setCountSafe} />}
                  </SetupRow>
                )}
                {/* WP: cells info */}
                {isWP && (
                  <div style={{ background: "var(--surface-2)", borderRadius: 12, padding: "14px 16px", display: "flex", gap: 10, alignItems: "center", border: "1px solid var(--line)" }}>
                    <Icon name="info" size={18} />
                    <span className="muted" style={{ fontSize: 13.5 }}>{t("setup.cells", { n: columns * 10, c: columns })}</span>
                  </div>
                )}
                {/* TFB: team split preview */}
                {isTFB && count > 2 && (
                  <div style={{ display: "flex", alignItems: "center", gap: 12, fontSize: 14, fontWeight: 600, padding: "8px 0" }}>
                    <span style={{ color: "var(--accent)" }}>Team 1: {Array.from({ length: tfbSplit }, (_, i) => i + 1).join(" + ")}</span>
                    <span className="muted">vs</span>
                    <span style={{ color: "var(--accent)" }}>Team 2: {Array.from({ length: count - tfbSplit }, (_, i) => i + tfbSplit + 1).join(" + ")}</span>
                  </div>
                )}
                <button className="btn primary lg block" onClick={() => setStep(1)}>{t("setup.continue")}<Icon name="arrow" /></button>
              </div>
            ) : isTFB ? (
              /* TFB: team-grouped names */
              <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
                {[{ team: teamA, offset: 0, label: t("setup.team1") }, { team: teamB, offset: tfbSplit, label: t("setup.team2") }].map(({ team, offset, label }) => (
                  <div key={label}>
                    <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 10 }}>
                      <span style={{ width: 8, height: 8, borderRadius: 50, background: "var(--accent)", flexShrink: 0 }}></span>
                      <span style={{ fontWeight: 700, fontSize: 13, color: "var(--accent)", whiteSpace: "nowrap" }}>{label}</span>
                    </div>
                    {team.map((nm, j) => {
                      const i = offset + j;
                      return (
                        <div key={i} style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 10 }}>
                          <Avatar name={nm || String(i + 1)} idx={i} />
                          <input className="input" placeholder={t("setup.playerPh", { n: i + 1 })} value={nm} autoFocus={i === 0}
                            onChange={(e) => setNames((p) => p.map((x, k) => k === i ? e.target.value : x))}
                            onKeyDown={(e) => { if (e.key === "Enter") { const els = e.target.closest(".card").querySelectorAll("input"); if (els[i + 1]) els[i + 1].focus(); else start(); } }} />
                        </div>
                      );
                    })}
                  </div>
                ))}
                <div style={{ background: "var(--accent-50)", border: "1px solid var(--accent-100)", borderRadius: "var(--r)", padding: "11px 14px", display: "flex", alignItems: "center", justifyContent: "center", gap: 16, fontSize: 14 }}>
                  <span style={{ fontWeight: 700 }}>{teamAName}</span>
                  <span className="muted">vs</span>
                  <span style={{ fontWeight: 700 }}>{teamBName}</span>
                </div>
                <button className="btn primary lg block" onClick={start}><Icon name="play" />{t("setup.start")}</button>
              </div>
            ) : (
              /* All other games: plain name list */
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                {names.map((nm, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <Avatar name={nm || String(i + 1)} idx={i} />
                    <input className="input" placeholder={t("setup.playerPh", { n: i + 1 })} value={nm} autoFocus={i === 0}
                      onChange={(e) => setNames((p) => p.map((x, j) => j === i ? e.target.value : x))}
                      onKeyDown={(e) => { if (e.key === "Enter") { const el = e.target.closest(".card").querySelectorAll("input"); if (el[i + 1]) el[i + 1].focus(); else start(); } }} />
                  </div>
                ))}
                <button className="btn primary lg block" style={{ marginTop: 4 }} onClick={start}><Icon name="play" />{t("setup.start")}</button>
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}

function SetupRow({ icon, title, sub, children }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
      <div style={{ flex: 1 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
          <Icon name={icon} size={18} /><span style={{ fontWeight: 700, fontSize: 16 }}>{title}</span>
        </div>
        {sub && <p className="muted" style={{ fontSize: 13, marginTop: 4, maxWidth: "34ch" }}>{sub}</p>}
      </div>
      {children}
    </div>
  );
}

function renderCells(str, n) {
  const parts = str.split("§n§");
  return <React.Fragment>{parts[0]}<b style={{ color: "var(--ink)" }}>{n}</b>{parts[1]}</React.Fragment>;
}

Object.assign(window, { Setup, SetupRow, renderCells });
