// Sessions list (home) + New Session wizard (hero)

function SessionsList({ onNav: onNavProp, stepperVariant }) {
  const { actions } = useStore();
  const onNav = onNavProp || ((k, id) => actions.nav(k, id));
  const [filter, setFilter] = React.useState("all");
  const sessions = window.SESSIONS;
  return (
    <div>
      <Topbar
        title="Sessions"
        right={
          <>
            <button className="btn sm">
              <Icon name="filter" size={13} /> Filter
            </button>
            <button className="btn primary sm" onClick={() => onNav("new")}>
              <Icon name="plus" size={13} /> New Session
            </button>
          </>
        }
      />
      <div className="content">
        <div className="page-head">
          <div>
            <h1 className="page-title">Your playable ad sessions</h1>
            <div className="page-sub">
              Six in flight · two export-ready · average time-to-first-preview:
              6m 42s
            </div>
          </div>
          <div style={{ display: "flex", gap: 4 }}>
            {["all", "building", "awaiting", "exported"].map((f) => (
              <button
                key={f}
                className={`btn sm ${filter === f ? "primary" : ""}`}
                onClick={() => setFilter(f)}
                style={{ textTransform: "capitalize" }}
              >
                {f}
              </button>
            ))}
          </div>
        </div>

        <table className="table">
          <thead>
            <tr>
              <th style={{ width: "28%" }}>Game</th>
              <th style={{ width: "24%" }}>Stage</th>
              <th style={{ width: "10%" }}>Variants</th>
              <th style={{ width: "16%" }}>Status</th>
              <th style={{ width: "12%" }}>Updated</th>
              <th style={{ width: "10%", textAlign: "right" }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {sessions.map((s) => {
              const g = window.GAMES.find((x) => x.id === s.gameId);
              return (
                <tr
                  key={s.id}
                  className="hoverable"
                  onClick={() => onNav("session", s.id)}
                >
                  <td>
                    <div className="game-cell">
                      <GameIcon game={g} />
                      <div>
                        <div className="game-name">{g?.name}</div>
                        <div className="game-pub">
                          {g?.publisher} · {g?.genre}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div
                      style={{
                        display: "flex",
                        flexDirection: "column",
                        gap: 4,
                      }}
                    >
                      <div className="progress-line">
                        {window.STAGES.map((_, i) => (
                          <div
                            key={i}
                            className={`seg ${i < s.stage ? "done" : i === s.stage ? "current" : ""}`}
                          />
                        ))}
                      </div>
                      <div className="spec">{s.stageName}</div>
                    </div>
                  </td>
                  <td className="mono">
                    {s.variantsReady}/{s.variants}
                  </td>
                  <td>
                    <StatusChip status={s.status} />
                  </td>
                  <td
                    className="mono"
                    style={{ color: "var(--ink-faint)", fontSize: 12 }}
                  >
                    {s.updated}
                  </td>
                  <td style={{ textAlign: "right" }}>
                    <button
                      className="btn ghost sm"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <Icon name="more" size={13} />
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>

        <div style={{ marginTop: 28 }}>
          <div className="section-label">Golden path</div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            {[
              ["Name game + upload assets", "30s"],
              ["Describe intent", "15s"],
              ["Approve strategy", "40s"],
              ["Watch first preview", "5–8m"],
              ["Export 2 variants", "15m"],
            ].map(([label, time], i) => (
              <div key={i} className="chip" style={{ padding: "6px 10px" }}>
                <span style={{ color: "var(--ink-faint)" }}>{i + 1}</span>
                <span style={{ color: "var(--ink)" }}>{label}</span>
                <span style={{ color: "var(--lime-ink)" }}>· {time}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function StatusChip({ status }) {
  const map = {
    in_progress: { label: "In progress", cls: "", dot: "neutral" },
    building: { label: "Building", cls: "cyan", dot: "live" },
    export_ready: { label: "Export-ready", cls: "lime", dot: "success" },
    awaiting_assets: { label: "Awaiting assets", cls: "warn", dot: "warn" },
    awaiting_approval: { label: "Needs approval", cls: "warn", dot: "warn" },
    exported: { label: "Exported", cls: "", dot: "neutral" },
  };
  const v = map[status] || map.in_progress;
  return (
    <span className={`chip ${v.cls}`}>
      <span className={`dot ${v.dot}`} /> {v.label}
    </span>
  );
}

// ---------- New Session wizard (HERO) ----------
function NewSessionWizard({ onNav: onNavProp }) {
  const { actions } = useStore();
  const onNav = onNavProp || ((k, id) => actions.nav(k, id));
  const [step, setStep] = React.useState(1);
  const [gameName, setGameName] = React.useState("");
  const [storeUrl, setStoreUrl] = React.useState("");
  const [assets, setAssets] = React.useState([]);
  const [brief, setBrief] = React.useState("");
  const [scanning, setScanning] = React.useState(false);
  const [hot, setHot] = React.useState(false);

  // Auto-detect game name from store url
  React.useEffect(() => {
    if (storeUrl.includes("gemquest") || storeUrl.includes("gem-quest")) {
      setGameName("Gem Quest: Legends");
    }
  }, [storeUrl]);

  const step1Done = gameName.length > 2;
  const step2Done = assets.length >= 3;
  const step3Done = brief.length > 12;
  const canCreate = step1Done && step2Done && step3Done;

  const simulateUpload = () => {
    if (scanning || assets.length > 0) return;
    setScanning(true);
    const fakes = [
      { name: "hero_character.png", tag: "CHARACTER", hue: 330 },
      { name: "logo_primary.png", tag: "LOGO", hue: 45 },
      { name: "screenshot_01.png", tag: "SCREEN", hue: 280 },
      { name: "screenshot_02.png", tag: "SCREEN", hue: 200 },
      { name: "ui_buttons.png", tag: "UI-KIT", hue: 150 },
      { name: "gameplay_loop.mp4", tag: "VIDEO", hue: 20 },
      { name: "icon_app.png", tag: "ICON", hue: 330 },
    ];
    fakes.forEach((f, i) => {
      setTimeout(
        () => {
          setAssets((prev) => [...prev, f]);
          if (i === fakes.length - 1) setScanning(false);
        },
        (i + 1) * 180,
      );
    });
  };

  // auto-advance
  React.useEffect(() => {
    if (step1Done && step === 1) setStep(2);
  }, [step1Done]);
  React.useEffect(() => {
    if (step2Done && step === 2 && !scanning) setTimeout(() => setStep(3), 400);
  }, [step2Done, scanning]);

  return (
    <div>
      <Topbar
        homeButton={() => onNav("home")}
        title="New Session"
        crumbs={[
          <span
            key="c"
            style={{ cursor: "pointer" }}
            onClick={() => onNav("home")}
          >
            Sessions
          </span>,
        ]}
        right={
          <button className="btn ghost sm" onClick={() => onNav("home")}>
            <Icon name="x" size={13} /> Cancel
          </button>
        }
      />
      <div className="content">
        <div className="wizard">
          <h1 className="tighter">
            Turn <em>your game</em>
            <br />
            into playable ad variants.
          </h1>
          <p className="lede">
            Drop in your game and what you want to test. A first playable
            preview in under 8 minutes — no agency cycle required.
          </p>

          {/* step 1 */}
          <div
            className={`wizard-step ${step === 1 ? "active" : ""} ${step1Done ? "done" : ""}`}
          >
            <div className="ws-head">
              <div className="ws-num">{step1Done ? "✓" : "1"}</div>
              <div className="ws-title">Your existing game</div>
              <div className="ws-sub">~10 seconds</div>
            </div>
            <div
              style={{
                display: "grid",
                gridTemplateColumns: "1fr 1fr",
                gap: 10,
              }}
            >
              <div>
                <div className="spec" style={{ marginBottom: 5 }}>
                  GAME NAME
                </div>
                <input
                  className="input"
                  placeholder="e.g. Gem Quest: Legends"
                  value={gameName}
                  onChange={(e) => setGameName(e.target.value)}
                />
              </div>
              <div>
                <div className="spec" style={{ marginBottom: 5 }}>
                  APP STORE URL (OPTIONAL)
                </div>
                <input
                  className="input"
                  placeholder="apps.apple.com/ca/app/…"
                  value={storeUrl}
                  onChange={(e) => setStoreUrl(e.target.value)}
                />
              </div>
            </div>
            {storeUrl && (
              <div
                style={{
                  marginTop: 10,
                  fontSize: 12,
                  color: "var(--lime-ink)",
                  display: "flex",
                  alignItems: "center",
                  gap: 6,
                }}
              >
                <Icon name="check" size={12} /> Metadata auto-filled from App
                Store · Casual Puzzle · Match-3
              </div>
            )}
          </div>

          {/* step 2 */}
          <div
            className={`wizard-step ${step === 2 ? "active" : ""} ${step2Done && !scanning ? "done" : ""} ${step < 2 ? "locked" : ""}`}
          >
            <div className="ws-head">
              <div className="ws-num">{step2Done && !scanning ? "✓" : "2"}</div>
              <div className="ws-title">Drop your brand assets</div>
              <div className="ws-sub">
                {assets.length > 0
                  ? `${assets.length} file${assets.length > 1 ? "s" : ""} · ${scanning ? "scanning…" : "detected"}`
                  : "~15 seconds"}
              </div>
            </div>

            {assets.length === 0 ? (
              <div
                className={`dropzone ${hot ? "hot" : ""}`}
                onDragOver={(e) => {
                  e.preventDefault();
                  setHot(true);
                }}
                onDragLeave={() => setHot(false)}
                onDrop={(e) => {
                  e.preventDefault();
                  setHot(false);
                  simulateUpload();
                }}
                onClick={simulateUpload}
              >
                <div style={{ marginBottom: 10 }}>
                  <Icon name="upload" size={22} />
                </div>
                <div className="dropzone-hint">
                  <b>Drag screenshots, logos, or UI art here</b> — or click to
                  browse
                </div>
                <div className="dropzone-sub">
                  png · jpg · svg · mp4 · max 50MB · 3+ assets recommended
                </div>
              </div>
            ) : (
              <div>
                <div className="asset-row">
                  {assets.filter(Boolean).map((a, i) => (
                    <div
                      key={i}
                      className="asset-tile detected fadein"
                      title={a?.name || ""}
                      style={{
                        background: window.placeholderUrl(
                          a?.tag || "asset",
                          120,
                          120,
                          a?.hue || 180,
                        ),
                        backgroundSize: "cover",
                      }}
                    >
                      <div className="badge">{a?.tag}</div>
                    </div>
                  ))}
                  {scanning && (
                    <div
                      className="asset-tile shimmer"
                      style={{ background: "var(--bg-subtle)" }}
                    ></div>
                  )}
                  <button
                    className="asset-tile"
                    style={{
                      background: "var(--bg-sunken)",
                      display: "grid",
                      placeItems: "center",
                      color: "var(--ink-faint)",
                    }}
                  >
                    <Icon name="plus" size={18} />
                  </button>
                </div>
                {!scanning && (
                  <div
                    style={{
                      marginTop: 10,
                      fontSize: 12,
                      color: "var(--lime-ink)",
                      display: "flex",
                      alignItems: "center",
                      gap: 6,
                    }}
                  >
                    <Icon name="sparkle" size={12} /> Detected 1 character · 1
                    logo · 2 screenshots · 1 UI kit · 1 gameplay video · 1 app
                    icon
                  </div>
                )}
              </div>
            )}
          </div>

          {/* step 3 */}
          <div
            className={`wizard-step ${step === 3 ? "active" : ""} ${step3Done ? "done" : ""} ${step < 3 ? "locked" : ""}`}
          >
            <div className="ws-head">
              <div className="ws-num">{step3Done ? "✓" : "3"}</div>
              <div className="ws-title">What should the ad test?</div>
              <div className="ws-sub">~15 seconds</div>
            </div>
            <textarea
              className="input"
              style={{ minHeight: 80, resize: "vertical" }}
              placeholder="e.g. Hook users in the first 3 seconds. Prioritize the match-3 mechanic. Test an IAP-reward variant vs. a difficulty-curve variant. Target: US, 18–34, casual puzzle lookalikes."
              value={brief}
              onChange={(e) => setBrief(e.target.value)}
            />
            <div
              style={{
                display: "flex",
                gap: 6,
                marginTop: 10,
                flexWrap: "wrap",
              }}
            >
              {[
                "Hook user in 3s",
                "Reward-first",
                "Near-miss loop",
                "IAP moment",
                "Low-funnel CTA",
              ].map((p) => (
                <button
                  key={p}
                  className="chip"
                  style={{ cursor: "pointer" }}
                  onClick={() => setBrief((b) => (b ? b + ". " : "") + p)}
                >
                  + {p}
                </button>
              ))}
            </div>
          </div>

          {/* create */}
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              marginTop: 18,
              padding: "14px 22px",
              background: "var(--ink)",
              borderRadius: "var(--r-lg)",
              color: "var(--bg)",
            }}
          >
            <div>
              <div
                style={{
                  fontSize: 13,
                  color: "var(--lime)",
                  fontFamily: "var(--font-mono)",
                }}
              >
                → NEXT
              </div>
              <div
                style={{
                  fontSize: 15,
                  fontWeight: 600,
                  letterSpacing: "-0.01em",
                  marginTop: 2,
                }}
              >
                Build reference pack · generate strategy · queue 4 variants
              </div>
            </div>
            <button
              className="btn accent lg"
              disabled={!canCreate}
              onClick={() => onNav("session", "s1")}
            >
              Create session <Icon name="arrowRight" size={14} />
            </button>
          </div>

          {/* tiny footer */}
          <div
            style={{
              marginTop: 18,
              fontSize: 11,
              fontFamily: "var(--font-mono)",
              color: "var(--ink-faint)",
              textAlign: "center",
            }}
          >
            your assets stay in your workspace · no model training · no
            auto-publish
          </div>
        </div>
      </div>
    </div>
  );
}

window.SessionsList = SessionsList;
window.NewSessionWizard = NewSessionWizard;
window.StatusChip = StatusChip;
