/* ===========================================================================
   library.jsx — where wizard output lives: Shot list · Generated · Angles
   props: store, tab, setTab
   =========================================================================== */
const L = window.STUDIO;

const STATUS_META = {
  todo:    { label: "To film", cls: "status-todo", ico: "clock" },
  filming: { label: "Filming", cls: "status-filming", ico: "video" },
  filmed:  { label: "Filmed",  cls: "status-filmed", ico: "check" },
};
const NEXT_STATUS = { todo: "filming", filming: "filmed", filmed: "todo" };

function scriptById(id) { return L.scripts.find((s) => s.id === id); }

function Empty({ icon, title, desc, cta, onCta }) {
  return (
    <div className="empty">
      <div className="empty-ico"><Icon name={icon} size={26}/></div>
      <h3>{title}</h3>
      <p>{desc}</p>
      {cta && <button className="btn primary" onClick={onCta}><Icon name="wand" size={15}/> {cta}</button>}
    </div>
  );
}

function ShotList({ store }) {
  if (!store.shot.length) return <Empty icon="video" title="Nothing queued yet" desc="When you send a creative to Alli from the Create flow, it lands here as a shot to film." cta="Create a creative" onCta={() => store.goCreate()}/>;
  return (
    <div>
      {store.shot.map((item) => {
        const s = scriptById(item.id);
        if (!s) return null;
        const sm = STATUS_META[item.status] || STATUS_META.todo;
        return (
          <div className="shot" key={item.id}>
            <div className="shot-thumb"><GenFrame script={s} ratio="44/56" showBadge={false}/></div>
            <div className="shot-main">
              <div className="shot-name">{s.slug}</div>
              <div className="shot-hook">“{s.hook}”</div>
            </div>
            <span className="chip ghost" style={{ flex: "0 0 auto" }}>{s.length}</span>
            <button className={`status-pill ${sm.cls}`} title="Click to advance" onClick={() => store.cycleShot(item.id)}>
              <Icon name={sm.ico} size={12} stroke={2.4}/> {sm.label}
            </button>
            <button className="shot-x" title="Remove" onClick={() => store.removeShot(item.id)}><Icon name="trash" size={15}/></button>
          </div>
        );
      })}
    </div>
  );
}

function GeneratedGallery({ store }) {
  const gen = L.scripts.filter((s) => s.generated);
  return (
    <div className="ad-grid">
      {gen.map((s) => {
        const added = store.shot.some((x) => x.id === s.id);
        return (
          <div className="ad-card" key={s.id} style={{ cursor: "default" }}>
            <div style={{ borderBottom: "1px solid var(--line)" }}><GenFrame script={s} ratio="1/1"/></div>
            <div className="ad-foot">
              <div className="ad-advertiser"><span className="sponsor-ava" style={{ background: "var(--magenta)" }}><Icon name="sparkle" size={11}/></span>{s.slug}</div>
              <div className="ad-copy">“{s.ctaOverlay}”</div>
              <div style={{ marginTop: 11, display: "flex", gap: 6 }}>
                {added
                  ? <button className="btn gold sm" disabled style={{ flex: 1, justifyContent: "center", opacity: 0.95 }}><Icon name="check" size={13} stroke={3}/> In shot list</button>
                  : <button className="btn sm" style={{ flex: 1, justifyContent: "center" }} onClick={() => { store.addShot(s.id); store.toast("Added to shot list", { label: "View", fn: () => store.setTab("shot") }); }}><Icon name="video" size={13}/> Add to shot list</button>}
                {s.asset_url && <a className="btn sm" href={downloadHref(s.asset_url)} title="Download" style={{ textDecoration: "none" }}><Icon name="download" size={13}/></a>}
              </div>
              {s.asset_url && (
                <div style={{ marginTop: 6, display: "flex", gap: 6 }}>
                  <button className="btn sm" style={{ flex: 1, justifyContent: "center", fontSize: 11.5 }} onClick={() => store.toast("Create ad campaign · routed to Slack bot", { label: "OK", fn: () => {} })}>
                    <Icon name="bolt" size={12}/> Create ad campaign
                  </button>
                  <button className="btn sm" style={{ flex: 1, justifyContent: "center", fontSize: 11.5 }} onClick={() => store.toast("Post to Instagram · routed to Slack bot", { label: "OK", fn: () => {} })}>
                    <Icon name="image" size={12}/> Post to Instagram
                  </button>
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function AnglesList({ store }) {
  if (!store.angles.length) return <Empty icon="gap" title="No approved angles yet" desc="Approve an opening from the Create flow and it'll show up here as a direction to pursue." cta="Find an opening" onCta={() => store.goCreate()}/>;
  return (
    <div>
      {store.angles.map((a) => (
        <div className="angle" key={a.id}>
          <div className="feed-ico" style={{ background: "var(--accent)", width: 34, height: 34, flex: "0 0 34px" }}><Icon name="gap" size={18}/></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="angle-title">{a.title}</div>
            <div className="angle-note">{a.note}</div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8, alignItems: "flex-end", flex: "0 0 auto" }}>
            <Chip tone="olive" dot="#3f9d6b">Approved</Chip>
            <button className="shot-x" title="Remove" onClick={() => store.removeAngle(a.id)}><Icon name="trash" size={15}/></button>
          </div>
        </div>
      ))}
    </div>
  );
}

function MascotLibrary() {
  const mascots = (L.mascots || []);
  if (mascots.length === 0) {
    return <Empty icon="sparkle" title="No mascot animations yet" desc="Generate character animations for each SKU and they'll show up here as your reusable brand library."/>;
  }
  return (
    <div>
      <p style={{ fontSize: 14, color: "var(--ink-soft)", marginBottom: 20, lineHeight: 1.55 }}>
        {mascots.length} animated brand characters — pull from this library to drop into any founder video as B-roll, transitions, or hero moments. Each is the 3D-rendered version of the cartoon mascot from the product packaging.
      </p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 20 }}>
        {mascots.map((m) => (
          <div key={m.id} className="card" style={{ overflow: "hidden", padding: 0 }}>
            <div style={{ aspectRatio: "1/1", background: "#0a0a0a", position: "relative" }}>
              <video src={m.url} muted loop autoPlay playsInline style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
              <div style={{ position: "absolute", top: 10, left: 10, padding: "4px 10px", background: m.palette, color: "#fff", fontSize: 10.5, fontFamily: "var(--mono)", fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", borderRadius: 999 }}>
                {m.character}
              </div>
              <div style={{ position: "absolute", top: 10, right: 10, padding: "4px 9px", background: "rgba(0,0,0,0.65)", color: "#fff", fontSize: 9.5, fontFamily: "var(--mono)", fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", borderRadius: 6 }}>
                Video
              </div>
            </div>
            <div style={{ padding: "14px 16px" }}>
              <div style={{ fontFamily: "var(--display)", fontSize: 14.5, fontWeight: 700, letterSpacing: "-0.01em" }}>{m.product}</div>
              <div style={{ fontSize: 13, color: "var(--ink-soft)", marginTop: 4 }}>{m.action}</div>
              <div style={{ display: "flex", gap: 6, marginTop: 10 }}>
                <Chip tone="ghost">{m.vibe}</Chip>
                <a className="btn sm" href={downloadHref(m.url)} download style={{ marginLeft: "auto", textDecoration: "none" }}>
                  <Icon name="download" size={12}/> Download
                </a>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Library({ store, tab, setTab }) {
  const toFilm = store.shot.filter((s) => s.status !== "filmed").length;
  const genCount = L.scripts.filter((s) => s.generated).length;
  const mascotCount = (L.mascots || []).length;
  const tabs = [
    ["shot", "Shot list", store.shot.length],
    ["generated", "Generated", genCount],
    ["mascots", "Mascots", mascotCount],
    ["angles", "Angles", store.angles.length],
  ];
  return (
    <div className="lib">
      <div className="page-head">
        <div className="eyebrow"><Icon name="script" size={13}/> Workspace</div>
        <h1 className="page-title sm">Your library</h1>
        <p className="page-desc">Everything the studio has made for you — queued for Alli, generated by Higgsfield, the mascot animations, and the angles you've greenlit.</p>
      </div>

      <div className="lib-stat-row">
        <div className="lib-stat"><div className="ls-num">{toFilm}</div><div className="ls-lab">To film</div></div>
        <div className="lib-stat"><div className="ls-num">{genCount}</div><div className="ls-lab">Generated frames</div></div>
        <div className="lib-stat"><div className="ls-num">{mascotCount}</div><div className="ls-lab">Mascots</div></div>
        <div className="lib-stat"><div className="ls-num">{store.angles.length}</div><div className="ls-lab">Approved angles</div></div>
      </div>

      <div className="tabs">
        {tabs.map(([k, label, n]) => (
          <button key={k} className={`tab ${tab === k ? "active" : ""}`} onClick={() => setTab(k)}>
            {label} <span style={{ color: "var(--ink-faint)", fontWeight: 500 }}>{n}</span>
          </button>
        ))}
      </div>

      {tab === "shot" && <ShotList store={store}/>}
      {tab === "generated" && <GeneratedGallery store={store}/>}
      {tab === "mascots" && <MascotLibrary/>}
      {tab === "angles" && <AnglesList store={store}/>}
    </div>
  );
}

Object.assign(window, { Library });
