/* ============================================================
   page-cpr-archive.jsx — 版权方档案 (双层表头分成 + drawer)
   主表分成区:自然流·抖音 / 投流·抖音 / 视频号 三组,每组「版权方% | 我方%」
   只填数字;文字说明放各渠道 note 或主备注
   我方默认 90%,对方 = 100 − 我方
   ============================================================ */
function PageCprArchive() {
  const [rows, ops] = useTable("publishers_v6", window.__SEED__.PUBLISHERS);
  const { editing } = useEditMode();
  const [statusFilter, setStatusFilter] = useState("__all__");
  const [drawerId, setDrawerId] = useState(null);
  const blank = {
    name: "", status: "合作",
    natLabel: "自然流(抖音)", natOur: 90, natNote: "",
    paidLabel: "投流(抖音)", paidOur: 90, paidNote: "",
    sphLabel: "视频号", sphOur: 90, sphNote: "",
    docs: [],
    backend: "", group: "", note: "",
  };

  const open = (id) => setDrawerId(id);
  const close = () => setDrawerId(null);

  useEffect(() => {
    if (!drawerId) return;
    const onKey = (e) => { if (e.key === "Escape") close(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [drawerId]);

  const drawerRow = useMemo(() => rows.find(r => r.id === drawerId), [rows, drawerId]);

  const statusCounts = useMemo(() => {
    const m = { __all__: rows.length, "合作": 0, "暂停授权": 0, "暂未合作": 0 };
    rows.forEach(r => { m[r.status] = (m[r.status] || 0) + 1; });
    return m;
  }, [rows]);

  const visible = useMemo(() =>
    rows.filter(r => statusFilter === "__all__" || r.status === statusFilter),
    [rows, statusFilter]
  );

  return (
    <>
      <FolderHead
        index="01"
        title="版权方档案"
        sub="分成是核心 · 我方默认 90% · 对方 = 100 − 我方"
      />

      <div className="callout" style={{ marginTop: 20 }}>
        <strong>读法 ·</strong> 三组色块对应<strong>自然流·抖音 / 投流·抖音 / 视频号</strong>。
        每组下「<strong>版权方</strong>」自动 = 100 − 我方,只编辑「<strong>我方</strong>」即可。
        我方默认 <strong>90%</strong>,合法范围 1~90%。
        不规则计算(阶梯 / 净收益 / 流水点位)放<strong>备注</strong>列,数字留空显示「—」。
      </div>

      <div className="filter-bar">
        <div className="filter-bar__group">
          <span className="filter-bar__label">合作状态</span>
          <button
            className={"filter-tab" + (statusFilter === "__all__" ? " is-active" : "")}
            onClick={() => setStatusFilter("__all__")}
          >全部<span className="filter-tab__count">{statusCounts.__all__}</span></button>
          {["合作", "暂停授权", "暂未合作"].map(s => {
            const n = statusCounts[s] || 0;
            if (n === 0) return null;
            return (
              <button
                key={s}
                className={"filter-tab" + (statusFilter === s ? " is-active" : "")}
                onClick={() => setStatusFilter(s)}
              >{s}<span className="filter-tab__count">{n}</span></button>
            );
          })}
        </div>
      </div>

      <div className="tbl-wrap">
        <table className="tbl tbl--compact">
          <colgroup>
            <col style={{ width: 110 }} />
            <col style={{ width: 86 }} />
            <col style={{ width: 68 }} /><col style={{ width: 68 }} />
            <col style={{ width: 68 }} /><col style={{ width: 68 }} />
            <col style={{ width: 68 }} /><col style={{ width: 68 }} />
            <col />
            <col style={{ width: 50 }} />
            {editing && <col style={{ width: 56 }} />}
          </colgroup>
          <thead>
            <tr>
              <th rowSpan={2}>版权方</th>
              <th rowSpan={2}>状态</th>
              <th className="group-head tint-warm" colSpan={2}>自然流 · 抖音</th>
              <th className="group-head tint-blue" colSpan={2}>投流 · 抖音</th>
              <th className="group-head tint-green" colSpan={2}>视频号</th>
              <th rowSpan={2}>备注</th>
              <th rowSpan={2}></th>
              {editing && <th rowSpan={2} className="center">操作</th>}
            </tr>
            <tr>
              <th className="sub-head tint-warm center">版权方</th>
              <th className="sub-head tint-warm center">我方</th>
              <th className="sub-head tint-blue center">版权方</th>
              <th className="sub-head tint-blue center">我方</th>
              <th className="sub-head tint-green center">版权方</th>
              <th className="sub-head tint-green center">我方</th>
            </tr>
          </thead>
          <tbody>
            {visible.length === 0 ? (
              <tr>
                <td colSpan={editing ? 11 : 10}>
                  <div className="cell" style={{ justifyContent: "center", color: "var(--ink-4)", padding: "24px 0", minHeight: 0 }}>
                    没有符合条件的版权方
                  </div>
                </td>
              </tr>
            ) : visible.map(r => {
              const set = (k, v) => ops.setCell(r.id, k, v);
              const isPaused = r.status === "暂停授权" || r.status === "暂未合作";
              return (
                <tr
                  key={r.id}
                  className={"entity-row" + (isPaused ? " is-paused" : "")}
                  onClick={(e) => {
                    if (e.target.closest("input,textarea,select,button,.cell.is-editable")) return;
                    open(r.id);
                  }}
                >
                  <td className="col-name"><EditableCell value={r.name} onChange={v => set("name", v)} /></td>
                  <td>
                    <div className="cell">
                      <StatusBadge
                        value={r.status}
                        onChange={v => set("status", v)}
                        options={["合作", "暂停授权", "暂未合作"]}
                      />
                    </div>
                  </td>
                  <SplitCells our={r.natOur} onChange={v => set("natOur", v)} tint="tint-warm" />
                  <SplitCells our={r.paidOur} onChange={v => set("paidOur", v)} tint="tint-blue" />
                  <SplitCells our={r.sphOur} onChange={v => set("sphOur", v)} tint="tint-green" />
                  <td>
                    <div className="cell" style={{ color: "var(--ink-3)", fontSize: 12.5 }}>
                      <EditableCell value={r.note} onChange={v => set("note", v)} placeholder="—" />
                    </div>
                  </td>
                  <td>
                    <div className="cell center" style={{ padding: 0 }}>
                      <span className="entity-row__chev" title="查看详情">›</span>
                    </div>
                  </td>
                  {editing && (
                    <td><div className="cell center"><DeleteBtn onClick={(e) => { e.stopPropagation(); ops.removeRow(r.id); }} /></div></td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="tbl-foot">
          <button className="btn-add" onClick={() => ops.addRow(blank)}>＋ 新增版权方</button>
          <span className="muted" style={{ fontSize: 11.5 }}>点击「我方」数字可编辑(1~90);点击行查看官方表 / 书单 / 后台 / 对接群等</span>
        </div>
      </div>

      {drawerRow && (
        <EditContext.Provider value={{ editing: true, setEditing: () => {} }}>
          <PublisherDrawer
            row={drawerRow}
            onChange={(k, v) => ops.setCell(drawerRow.id, k, v)}
            onClose={close}
            editing={true}
          />
        </EditContext.Provider>
      )}
    </>
  );
}

/* 一组「版权方% | 我方%」单元 · 版权方自动 = 100 − 我方 · 范围 1~90 */
function SplitCells({ our, onChange, tint }) {
  const isNum = our != null && our !== "";
  const pubVal = isNum ? Math.max(0, Math.round((100 - Number(our)) * 100) / 100) : null;
  const clampOur = (v) => {
    if (v == null || v === "") return null;
    const n = Number(v);
    if (!Number.isFinite(n)) return null;
    if (n < 1) return 1;
    if (n > 90) return 90;
    return n;
  };
  return (
    <>
      <td className={tint + " col-pct"}>
        <div className="cell" style={{ justifyContent: "flex-end", color: "var(--ink-3)" }}>
          {isNum ? pubVal : <span className="muted">—</span>}
          <span style={{ marginLeft: 2, color: "var(--ink-4)", fontSize: 11 }}>%</span>
        </div>
      </td>
      <td className={tint + " col-pct"}>
        <EditableCell value={our} numeric onChange={(v) => onChange(clampOur(v))} align="center" />
      </td>
    </>
  );
}

function PublisherDrawer({ row, onChange, onClose, editing }) {
  const r = row;
  const pub = (v) => (v == null || v === "" ? null : Math.max(0, 100 - Number(v)));
  return (
    <>
      <div className="drawer-scrim" onClick={onClose}></div>
      <aside className="drawer drawer--wide" role="dialog">
        <header className="drawer__head">
          <div>
            <div className="drawer__eyebrow">版权方</div>
            <h2 className="drawer__title">{r.name || "(未命名)"}</h2>
          </div>
          <button className="drawer__close" onClick={onClose} aria-label="关闭">✕</button>
        </header>

        <div className="drawer__body">
          <DrawerSection title="基本信息">
            <DrawerRow label="版权方">
              <EditableCell value={r.name} onChange={v => onChange("name", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="合作状态">
              <StatusBadge
                value={r.status}
                onChange={v => onChange("status", v)}
                options={["合作", "暂停授权", "暂未合作"]}
              />
            </DrawerRow>
          </DrawerSection>

          <DrawerSection title="分成" hint="只填数字 · 我方 = 不鸣 · 版权方 = 100 − 我方 · 点击首列可改渠道名">
            <RevRow
              label={r.natLabel || "自然流(抖音)"} our={r.natOur} note={r.natNote}
              onChangeLabel={v => onChange("natLabel", v)}
              onChangeOur={v => onChange("natOur", v)} onChangeNote={v => onChange("natNote", v)} pub={pub(r.natOur)}
            />
            <RevRow
              label={r.paidLabel || "投流(抖音)"} our={r.paidOur} note={r.paidNote}
              onChangeLabel={v => onChange("paidLabel", v)}
              onChangeOur={v => onChange("paidOur", v)} onChangeNote={v => onChange("paidNote", v)} pub={pub(r.paidOur)}
            />
            <RevRow
              label={r.sphLabel || "视频号"} our={r.sphOur} note={r.sphNote}
              onChangeLabel={v => onChange("sphLabel", v)}
              onChangeOur={v => onChange("sphOur", v)} onChangeNote={v => onChange("sphNote", v)} pub={pub(r.sphOur)}
            />
          </DrawerSection>

          <DrawerSection title="文档资源" hint="版权方提供的链接 / 路径 · 点击首列可改标签名">
            {(() => {
              const getDocs = () => {
                if (Array.isArray(r.docs)) return r.docs;
                const d = [];
                if (r.officialList) d.push({ id: `d1-${r.id}`, label: "官方表", value: r.officialList });
                if (r.bookList)     d.push({ id: `d2-${r.id}`, label: "书单",   value: r.bookList });
                if (r.intro)        d.push({ id: `d3-${r.id}`, label: "项目介绍", value: r.intro });
                return d;
              };
              const docs = getDocs();
              const setDoc = (i, key, val) => {
                const next = [...docs];
                next[i] = { ...docs[i], [key]: val };
                onChange("docs", next);
              };
              const delDoc = (i) => onChange("docs", docs.filter((_, j) => j !== i));
              const addDoc = () => onChange("docs", [...docs, { id: `doc-${Date.now()}`, label: "", value: "" }]);
              return (
                <div className="pd-list">
                  {docs.map((d, i) => (
                    <div key={d.id || i} className="pd-row">
                      <div className="pd-row__label">
                        {editing ? (
                          <input
                            value={d.label || ""}
                            onChange={e => setDoc(i, "label", e.target.value)}
                            placeholder="标签名"
                            style={{ background:"transparent", border:"none", outline:"none", font:"inherit", fontSize:"inherit", color:"inherit", padding:0, width:"100%" }}
                          />
                        ) : (d.label || <span style={{ color:"var(--ink-4)" }}>—</span>)}
                      </div>
                      <div className="pd-row__val">
                        <EditableCell value={d.value} onChange={v => setDoc(i, "value", v)} placeholder="粘贴 URL 或写描述" />
                      </div>
                      {editing && (
                        <button className="btn-del" onClick={() => delDoc(i)} style={{ margin:"0 8px" }}>×</button>
                      )}
                    </div>
                  ))}
                  {docs.length === 0 && !editing && (
                    <div style={{ padding:"12px 14px", fontSize:12, color:"var(--ink-4)" }}>暂无文档，开启编辑模式添加</div>
                  )}
                  {editing && (
                    <button className="btn-add" style={{ alignSelf:"flex-start", margin:"8px 12px" }} onClick={addDoc}>＋ 新增文档</button>
                  )}
                </div>
              );
            })()}
          </DrawerSection>

          <DrawerSection title="后台 & 协作">
            <DrawerRow label="抖音后台">
              <EditableCell value={r.backend} onChange={v => onChange("backend", v)} placeholder="子账号 / 后台路径" />
            </DrawerRow>
            <DrawerRow label="对接群">
              <EditableCell value={r.group} onChange={v => onChange("group", v)} placeholder="飞书群 / 微信群名称" />
            </DrawerRow>
          </DrawerSection>

          <DrawerSection title="备注">
            <DrawerRow label="">
              <EditableCell value={r.note} onChange={v => onChange("note", v)} placeholder="—" multiline />
            </DrawerRow>
          </DrawerSection>
        </div>
      </aside>
    </>
  );
}

function RevRow({ label, our, note, pub, onChangeLabel, onChangeOur, onChangeNote }) {
  const clamp = (v) => {
    if (v == null || v === "") return null;
    const n = Number(v);
    if (!Number.isFinite(n)) return null;
    if (n < 1) return 1;
    if (n > 90) return 90;
    return n;
  };
  return (
    <div className="rev-row">
      <div className="rev-row__label" style={{ minWidth:0, overflow:"hidden" }}>
        {onChangeLabel ? (
          <input
            value={label || ""}
            onChange={e => onChangeLabel(e.target.value)}
            style={{ background:"transparent", border:"none", outline:"none", font:"inherit", fontWeight:500, color:"inherit", padding:0, width:"100%", minWidth:0, display:"block" }}
          />
        ) : label}
      </div>
      <div className="rev-row__nums">
        <div className="rev-row__num">
          <div className="rev-row__sub">版权方</div>
          <div className="rev-row__val rev-row__val--readonly">
            {pub != null ? `${pub}%` : "—"}
          </div>
        </div>
        <div className="rev-row__num">
          <div className="rev-row__sub">我方</div>
          <div className="rev-row__val">
            <EditableCell value={our} numeric onChange={v => onChangeOur(clamp(v))} align="center" />
            <span className="rev-row__pct">%</span>
          </div>
        </div>
      </div>
      <div className="rev-row__note">
        <EditableCell value={note} onChange={onChangeNote} placeholder="备注:阶梯 / 流水点位 / 净收益等" multiline />
      </div>
    </div>
  );
}

Object.assign(window, { PageCprArchive });
