/* UsedIn.jsx — "Used in" on the asset request page (Editorial E3b, 0136).
   Which episodes used this request, or material that came from it, so someone about to
   reuse it sees where it has been. Advisory, like the hold banner (D5).
   Data: LedgerAPI.ed.usedIn (asset_usage_history).

   Three kinds of row:
     - confirmed: a producer attached the request in Airtable, or confirmed it in Link Review;
     - proposed: inferred from a confirmed episode → matter link, not yet confirmed;
     - a producer-attached row on a request that is NOT received reads "planned": in Airtable
       "attached" means planned, so it is not evidence of use (E3-C).
   Episode titles link to the episode page only for people who hold Editorial. */
(function () {
  const Ic = ({ n }) => <span className="ic-wrap" key={n}><i data-lucide={n} /></span>;
  const icons = () => setTimeout(() => window.lucide && window.lucide.createIcons(), 30);

  function UsedIn({ request }) {
    const [rows, setRows] = React.useState(null);
    const id = request && request.id;
    React.useEffect(() => {
      let live = true;
      setRows(null);
      const ed = window.LedgerAPI && window.LedgerAPI.ed;
      if (!id || !ed || !ed.usedIn) return undefined;
      ed.usedIn(id).then((r) => { if (live) setRows(r || []); }).catch(() => { if (live) setRows([]); });
      return () => { live = false; };
    }, [id]);
    React.useEffect(() => { if (rows && rows.length) icons(); }, [rows]);
    if (!rows) return null;

    const received = request.status === "received";
    const canOpen = !!(window.LedgerCaps || {}).isEditorial;
    const fmt = (d) => (d ? window.LedgerTime.fmtDate(d) : "Undated");
    const kind = (r) => (r.usage_status === "proposed" ? { cls: "warn", text: "Unconfirmed" }
      : !received && r.grain === "request" ? { cls: "n", text: "Planned" } : { cls: "ok", text: "Used" });
    const n = (t) => rows.filter((r) => kind(r).text === t).length;
    const plural = (k, w) => `${k} ${w}${k === 1 ? "" : "s"}`;
    const summary = rows.length === 0 ? "No episode yet" : [
      n("Used") && plural(n("Used"), "episode"),
      n("Unconfirmed") && `${n("Unconfirmed")} unconfirmed`,
      n("Planned") && `${n("Planned")} planned, not received`,
    ].filter(Boolean).join(" · ");

    return (
      <div className="used-in">
        <div className="used-in__head">
          <Ic n="clapperboard" />
          <b>Used in</b>
          <span className="used-in__sum">{summary}</span>
        </div>
        {rows.length > 0 && (
          <ul className="used-in__list">
            {rows.map((r) => {
              const k = kind(r);
              return (
                <li key={r.usage_id || r.piece_id}>
                  <span className={"ed-pill " + k.cls}>{k.text}</span>
                  <span className="used-in__show">{r.show_label}</span>
                  {canOpen ? <a href={`#ed/ep/${r.display_id}`} className="used-in__title">{r.title || r.display_id}</a>
                           : <span className="used-in__title">{r.title || r.display_id}</span>}
                  <span className="used-in__date">{fmt(r.air_date)}</span>
                  {r.grain !== "request" && <span className="used-in__via">via the {r.grain === "folder" ? "case folder" : "Iconik asset"}</span>}
                </li>
              );
            })}
          </ul>
        )}
      </div>
    );
  }

  window.LedgerUsedIn = UsedIn;
})();
