/* QueueUp.gg — Setup wizard (multi-step) + Invite step */
const { useState } = React;
function OptTile({ sel, onClick, ico, emoji, name, desc, multi }) {
  return (
    <button className={`opt ${sel ? "sel" : ""}`} onClick={onClick}>
      <div className="opt-check">{Icons.check({ size: 13, stroke: "#08080d", strokeWidth: 3 })}</div>
      {ico && <div className="opt-ico">{Icons[ico]({ size: 24 })}</div>}
      {emoji && <div className="opt-emoji">{emoji}</div>}
      <div className="opt-name">{name}</div>
      {desc && <div className="opt-desc">{desc}</div>}
    </button>
  );
}

function Wizard({ prefs, setPrefs, onComplete, onExit }) {
  const [step, setStep] = useState(0);
  const STEPS = ["Players", "Platforms", "Time", "Mood", "Details", "Invite"];
  const total = STEPS.length;

  const set = (k, v) => setPrefs((p) => ({ ...p, [k]: v }));
  const toggleArr = (k, v) => setPrefs((p) => {
    const arr = p[k].includes(v) ? p[k].filter((x) => x !== v) : [...p[k], v];
    return { ...p, [k]: arr };
  });

  const canNext = () => {
    if (step === 1) return prefs.platforms.length > 0;
    if (step === 3) return prefs.moods.length > 0;
    return true;
  };
  const next = () => { if (step < total - 1) setStep(step + 1); else onComplete(); };
  const back = () => { if (step === 0) onExit(); else setStep(step - 1); };

  return (
    <div className="wizard container">
      <div className="wz-head">
        <div className="wz-step-label">Step {step + 1} of {total} · {STEPS[step]}</div>
        <button className="nav-link" onClick={onExit} style={{ padding: "6px 10px" }}>Cancel</button>
      </div>
      <div className="progress"><div className="progress-fill" style={{ width: `${((step + 1) / total) * 100}%` }} /></div>

      <div className="card wz-card">
        {step === 0 && (
          <div>
            <div className="wz-q">How many of you are in?</div>
            <div className="wz-hint">Count everyone who'll actually be holding a controller (or mouse).</div>
            <div className="stepper">
              <button onClick={() => set("players", Math.max(1, prefs.players - 1))} aria-label="fewer">−</button>
              <div className="count">{prefs.players}<small>{prefs.players === 1 ? "player" : "players"}</small></div>
              <button onClick={() => set("players", Math.min(16, prefs.players + 1))} aria-label="more">+</button>
            </div>
            <div className="player-quick">
              {[1, 2, 3, 4, 6, 8].map((n) => (
                <button key={n} className={prefs.players === n ? "on" : ""} onClick={() => set("players", n)}>{n}</button>
              ))}
            </div>
          </div>
        )}

        {step === 1 && (
          <div>
            <div className="wz-q">What's in the room?</div>
            <div className="wz-hint">Pick every platform someone can play on. More platforms = more crossplay picks.</div>
            <div className="opt-grid cols-4">
              {PLATFORMS.map((p) => (
                <OptTile key={p.id} ico={p.ico} name={p.name} sel={prefs.platforms.includes(p.id)} onClick={() => toggleArr("platforms", p.id)} />
              ))}
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <div className="wz-q">How long have you got?</div>
            <div className="wz-hint">Be honest. We won't recommend a 3-hour raid for a 30-minute window.</div>
            <div className="opt-grid cols-3">
              {TIMES.map((t) => (
                <OptTile key={t.id} name={t.name} desc={t.desc} sel={prefs.time === t.id} onClick={() => set("time", t.id)} />
              ))}
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <div className="wz-q">What's the vibe tonight?</div>
            <div className="wz-hint">Pick one or stack a few. This is the biggest factor in your matches.</div>
            <div className="opt-grid cols-3">
              {MOODS.map((m) => (
                <OptTile key={m.id} ico={m.ico} name={m.name} desc={m.desc} sel={prefs.moods.includes(m.id)} onClick={() => toggleArr("moods", m.id)} />
              ))}
            </div>
          </div>
        )}

        {step === 4 && (
          <div>
            <div className="wz-q">Last couple things.</div>
            <div className="wz-hint">Fine-tune the squad's budget and competitiveness.</div>
            <div className="toggle-row" style={{ marginBottom: 22 }}>
              <div>
                <div className="t-title">Free games only 💸</div>
                <div className="t-desc">Only show free-to-play picks nobody has to buy.</div>
              </div>
              <button className={`switch ${prefs.freeOnly ? "on" : ""}`} onClick={() => set("freeOnly", !prefs.freeOnly)}><span className="knob" /></button>
            </div>
            <div className="wz-step-label" style={{ marginBottom: 12 }}>Skill level <span className="faint">(optional)</span></div>
            <div className="opt-grid cols-3">
              {SKILLS.map((s) => (
                <OptTile key={s.id} name={s.name} desc={s.desc} sel={prefs.skill === s.id} onClick={() => set("skill", prefs.skill === s.id ? "mixed" : s.id)} />
              ))}
            </div>
          </div>
        )}

        {step === 5 && <InviteStep prefs={prefs} setPrefs={setPrefs} />}

        <div className="wz-foot">
          <button className="btn btn-ghost" onClick={back}>{Icons.arrowL({ size: 17 })} {step === 0 ? "Home" : "Back"}</button>
          <button className="btn btn-primary" onClick={next} disabled={!canNext()}>
            {step === total - 1 ? <>Generate picks {Icons.sparkles({ size: 17 })}</> : <>Continue {Icons.arrowR({ size: 17 })}</>}
          </button>
        </div>
      </div>

      {step === 5 && (
        <div style={{ textAlign: "center", marginTop: 16 }}>
          <button className="nav-link" onClick={onComplete}>Skip — just show me games {Icons.arrowR({ size: 14 })}</button>
        </div>
      )}

      <div className="faint" style={{ textAlign: "center", fontSize: 11.5, marginTop: 18 }}>
        Age Notice: 13+ · GGWhatNext is intended for users aged 13 and above.
      </div>
    </div>
  );
}

/* ---- invite / party step ---- */
const FRIEND_POOL = [
  { name: "Riley", plat: "PC", hue: 280 },
  { name: "Sam", plat: "PS5", hue: 190 },
  { name: "Jordan", plat: "Switch", hue: 330 },
  { name: "Kai", plat: "Xbox", hue: 140 },
];
function InviteStep({ prefs, setPrefs }) {
  const [copied, setCopied] = useState(false);
  const link = `ggwhatnext.com/s/${prefs.sessionId}`;
  const party = prefs.party || [];

  const regenLink = () => setPrefs((p) => ({ ...p, sessionId: newSessionId() }));

  const addFriend = () => {
    if (party.length >= FRIEND_POOL.length) return;
    const f = FRIEND_POOL[party.length];
    setPrefs((p) => ({ ...p, party: [...(p.party || []), f] }));
  };
  const copy = () => {
    navigator.clipboard?.writeText(link).catch(() => {});
    setCopied(true); setTimeout(() => setCopied(false), 1600);
  };

  return (
    <div>
      <div className="wz-q">Pull in the squad <span className="faint">(optional)</span></div>
      <div className="wz-hint">Share the link and friends hop in with their own platform. Or skip — we've got your back solo.</div>

      <div className="invite-link">
        {Icons.link({ size: 17, stroke: "var(--text-faint)" })}
        <code>{link}</code>
        <button className="btn btn-primary" style={{ padding: "9px 16px" }} onClick={copy}>
          {copied ? <>{Icons.check({ size: 16 })} Copied</> : <>{Icons.copy({ size: 16 })} Copy</>}
        </button>
      </div>
      <button className="btn btn-ghost" style={{ marginTop: 10, padding: "7px 14px", fontSize: 13 }} onClick={regenLink}>
        {Icons.refresh({ size: 15 })} Generate new link
      </button>

      <div className="party-list">
        <div className="party-row">
          <div className="avatar" style={{ background: "linear-gradient(135deg, var(--a1), var(--a2))" }}>YOU</div>
          <div>
            <div className="pname">You <span className="chip chip-a1" style={{ marginLeft: 6 }}>host</span></div>
            <div className="pmeta">{prefs.platforms.join(" · ") || "no platform yet"}</div>
          </div>
          <div className="online-dot" />
        </div>
        {party.map((f) => (
          <div key={f.name} className="party-row">
            <div className="avatar" style={{ background: `linear-gradient(135deg, oklch(0.62 0.2 ${f.hue}), oklch(0.6 0.18 ${(f.hue+50)%360}))` }}>{f.name.slice(0,2).toUpperCase()}</div>
            <div>
              <div className="pname">{f.name} just joined</div>
              <div className="pmeta">{f.plat} · ready</div>
            </div>
            <div className="online-dot" />
          </div>
        ))}
      </div>

      {party.length < FRIEND_POOL.length && (
        <button className="btn btn-outline" style={{ marginTop: 16, width: "100%", justifyContent: "center" }} onClick={addFriend}>
          {Icons.users({ size: 17 })} Simulate a friend joining
        </button>
      )}
    </div>
  );
}
window.Wizard = Wizard;
window.FRIEND_POOL = FRIEND_POOL;
