/* Gallery & Launch — Layout B: filter rail + dense studio rows */

function shortModel(m) { return m.split(" (")[0]; }

function GalleryTab({ creatives, mode, sel, setSel, modelFilter, setModelFilter,
                      mediaFilter, setMediaFilter, showRemoved, setShowRemoved,
                      onEdit, onRemove, onRestore, modelList, onLaunch, launchState,
                      plan, setPlan, plans }) {

  const [statusFilter, setStatusFilter] = React.useState("all");
  const [preview, setPreview] = React.useState(null);

  // pool the rail counts off (the non-removed unless "show removed" is on)
  const pool = creatives.filter(c => c.removed ? showRemoved : true);
  const statusOf = c => (mode === "live" ? c.liveStatus : c.status);

  const visible = pool.filter(c => {
    if (modelFilter !== "all" && c.model !== modelFilter) return false;
    if (mediaFilter === "image" && c.isVideo) return false;
    if (mediaFilter === "video" && !c.isVideo) return false;
    if (statusFilter !== "all" && statusOf(c) !== statusFilter) return false;
    return true;
  });

  const total = pool.length;
  const removedCount = creatives.filter(c => c.removed).length;
  const selectableShown = visible.filter(c => !c.removed);

  // rail counts
  const count = pred => pool.filter(pred).length;
  const modelCounts = {}; modelList.forEach(m => modelCounts[m] = count(c => c.model === m));
  const videoCount = count(c => c.isVideo);
  const imageCount = count(c => !c.isVideo);
  const statusOrder = [];
  pool.forEach(c => { const s = statusOf(c); if (!statusOrder.includes(s)) statusOrder.push(s); });

  function selectAllShown() { setSel(prev => { const n = new Set(prev); selectableShown.forEach(c => n.add(c.id)); return n; }); }
  function clearSel() { setSel(new Set()); }
  function toggle(id) { setSel(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; }); }
  const toggleMedia = f => setMediaFilter(v => v === f ? "all" : f);
  const toggleStatus = s => setStatusFilter(v => v === s ? "all" : s);

  return (
    <div className="studio">
      {/* ---------------- FILTER RAIL ---------------- */}
      <aside className="frail">
        <div className="frail-group">
          <div className="frail-label">Model</div>
          <RailItem on={modelFilter === "all"} onClick={() => setModelFilter("all")} label="All models" n={total} />
          {modelList.map(m => (
            <RailItem key={m} on={modelFilter === m} onClick={() => setModelFilter(m)} label={shortModel(m)} n={modelCounts[m]} />
          ))}
        </div>

        <div className="frail-group">
          <div className="frail-label">Format</div>
          <RailItem on={mediaFilter === "video"} onClick={() => toggleMedia("video")} label="Video" n={videoCount} />
          <RailItem on={mediaFilter === "image"} onClick={() => toggleMedia("image")} label="Image" n={imageCount} />
        </div>

        <div className="frail-group">
          <div className="frail-label">Status</div>
          {statusOrder.map(s => (
            <RailItem key={s} on={statusFilter === s} onClick={() => toggleStatus(s)}
              label={statusMeta(s).label} n={count(c => statusOf(c) === s)} />
          ))}
        </div>

        {removedCount > 0 && (
          <button className={"frail-toggle" + (showRemoved ? " on" : "")} onClick={() => setShowRemoved(v => !v)}>
            {showRemoved ? "Hide removed" : `Show removed (${removedCount})`}
          </button>
        )}
      </aside>

      {/* ---------------- MAIN LIST ---------------- */}
      <div className="studio-main">
        <div className="studio-bar">
          <div className="studio-count">
            {visible.length} of {total} creatives
            {sel.size > 0 && <> · <b>{sel.size} selected</b></>}
          </div>
          <div className="chiprow">
            <button className="chip chip-ghost" onClick={selectAllShown}>Select all shown</button>
            <button className="chip chip-ghost" onClick={clearSel}>Clear</button>
          </div>
        </div>

        {visible.length === 0 ? (
          <EmptyState label="No creatives match these filters." />
        ) : (
          <div className="studio-list">
            {visible.map(c => (
              <CreativeRow key={c.id} c={c} mode={mode}
                selected={sel.has(c.id)} onToggle={() => toggle(c.id)} onPreview={() => setPreview(c)}
                onEdit={() => onEdit(c.id)} onRemove={() => onRemove(c.id)} onRestore={() => onRestore(c.id)} />
            ))}
          </div>
        )}

        {sel.size > 0 && (
          <LaunchBar count={sel.size} onLaunch={onLaunch} onClear={clearSel} state={launchState} plan={plan} setPlan={setPlan} plans={plans} />
        )}
      </div>

      {preview && <Lightbox c={preview} onClose={() => setPreview(null)} />}
    </div>
  );
}

function Lightbox({ c, onClose }) {
  const hasAsset = c.assetUrl && /^https?:/.test(c.assetUrl);
  return (
    <div className="overlay" onClick={onClose}>
      <div className="lightbox" onClick={e => e.stopPropagation()}>
        <div className="lb-head">
          <div>
            <div className="lb-title serif">{c.headline || c.id}</div>
            <div className="mid mono">{c.id} · {shortModel(c.model)}{c.angle ? " · " + c.angle : ""} · {c.format}</div>
          </div>
          <button className="ico-btn" onClick={onClose}><Ico d={I.x} s={14} /></button>
        </div>
        <div className="lb-media">
          {hasAsset ? (
            c.isVideo
              ? <video src={c.assetUrl} controls autoPlay loop playsInline />
              : <img src={c.assetUrl} alt="" />
          ) : (
            <div className="lb-noasset">
              <Ico d={I.grid} s={26} />
              <div>No asset yet — this {c.isVideo ? "video" : "image"} hasn't been generated.<br />Add an Asset URL via <b>Edit</b> to preview &amp; launch it.</div>
            </div>
          )}
        </div>
        {c.primary && <div className="lb-primary">{c.primary}</div>}
        <div className="lb-foot">
          <span className="cta-chip">{c.cta}</span>
          {hasAsset && <a className="link-btn" href={c.assetUrl} target="_blank" rel="noopener noreferrer"><Ico d={I.ext} s={13} /> Open original</a>}
        </div>
      </div>
    </div>
  );
}

function RailItem({ on, onClick, label, n }) {
  return (
    <button className={"frail-item" + (on ? " on" : "")} onClick={onClick}>
      <span className="frail-name">{label}</span>
      <span className="frail-n">{n}</span>
    </button>
  );
}

function CreativeRow({ c, mode, selected, onToggle, onEdit, onRemove, onRestore, onPreview }) {
  const status = mode === "live" ? c.liveStatus : c.status;
  const showMetrics = mode === "live" && status !== "paused" && status !== "ready" && status !== "gathering";
  return (
    <div className={"srow" + (selected ? " sel" : "") + (c.removed ? " removed" : "")}>
      {!c.removed ? (
        <button className={"ck" + (selected ? " on" : "")} onClick={onToggle} title="Select to launch">
          {selected && <Ico d={I.check} s={12} />}
        </button>
      ) : <span className="ck-spacer" />}

      <div className="srow-thumb" onClick={onPreview} title="Click to preview" style={{ cursor: "zoom-in" }}>
        <MediaTile c={c} ratio="16 / 10">
          <span className="srow-fmt">{c.isVideo ? "▶ " : "▣ "}{c.format}</span>
          <span className="srow-zoom"><Ico d={I.ext} s={12} /></span>
        </MediaTile>
      </div>

      <div className="srow-body">
        <div className="srow-head serif">{c.headline}</div>
        <div className="srow-meta mono">{c.id} · {shortModel(c.model)}{c.angle ? " · " + c.angle : ""}</div>
        <div className="srow-primary">{c.primary}</div>
      </div>

      {showMetrics && (
        <div className="srow-metric mono">
          <span>{fmt.money(c.live.spend)}</span>
          <span>{c.live.leads} leads</span>
          {c.live.cpa != null && <span className={c.live.cpa > 150 ? "over" : "under"}>{fmt.cpl(c.live.cpa)} CPL</span>}
        </div>
      )}

      <div className="srow-actions">
        <Badge status={status} />
        <span className="cta-chip">{c.cta}</span>
        {c.removed ? (
          <>
            {c.removedAt && <span className="lead-muted" style={{ font: "10.5px var(--mono)", color: "var(--t4)" }}>removed {String(c.removedAt).slice(0, 10)}</span>}
            <button className="link-btn" onClick={onRestore}><Ico d={I.refresh} s={13} /> Restore</button>
          </>
        ) : (
          <>
            <button className="ico-btn" onClick={onEdit} title="Edit copy"><Ico d={I.edit} s={13} /></button>
            <button className="ico-btn danger" onClick={onRemove} title="Remove"><Ico d={I.x} s={13} /></button>
          </>
        )}
      </div>
    </div>
  );
}

function LaunchBar({ count, onLaunch, onClear, state, plan, setPlan, plans }) {
  const cfg = (plans && plans[plan]) || {};
  return (
    <div className="launchbar-wrap">
      <div className="launchbar">
        <div className="lb-safety">
          <span className="lb-lock"><Ico d={I.lock} s={15} /></span>
          <div>
            <div className="lb-safety-t">Launches as <b>PAUSED</b></div>
            <div className="lb-safety-s">Nothing spends until you switch it on in Meta.</div>
          </div>
        </div>
        <div className="lb-count"><b>{count}</b> creative{count > 1 ? "s" : ""} selected</div>
        <div className="lb-actions">
          {state.result && <span className={"lb-result " + state.kind}>{state.result}</span>}
          {plans && setPlan && (
            <label className="lb-plan" title="How to structure the campaign(s) in Meta" style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ fontSize: 11, color: "var(--t3)", textTransform: "uppercase", letterSpacing: ".05em" }}>Plan</span>
              <select value={plan} onChange={e => setPlan(e.target.value)} className="lb-plan-sel"
                style={{ background: "var(--s2,#fff)", color: "var(--t1)", border: "1px solid var(--line,#ccc)", borderRadius: 8, padding: "7px 9px", fontSize: 12, fontFamily: "inherit", maxWidth: 280 }}>
                {Object.keys(plans).map(k => <option key={k} value={k}>{plans[k].label}</option>)}
              </select>
            </label>
          )}
          <button className="btn btn-ghost btn-sm" onClick={onClear}>Clear</button>
          <button className="btn btn-accent btn-lg" onClick={onLaunch} disabled={state.loading}>
            <Ico d={I.rocket} s={15} cls={state.loading ? "spin" : ""} />
            {state.loading ? "Pushing to Meta…" : "Launch to Meta (paused)"}
          </button>
        </div>
      </div>
    </div>
  );
}

function EmptyState({ label }) {
  return (
    <div className="empty">
      <Ico d={I.grid} s={26} />
      <div>{label}</div>
    </div>
  );
}

Object.assign(window, { GalleryTab, RailItem, CreativeRow, Lightbox, LaunchBar, EmptyState, shortModel });
