/* ============================================================
   page-dist.jsx — 发行流程 (流程图 + 14 平台档案 + 辅助文档)
   每个平台点击 → 抽屉显示完整子账号 / 厂牌 / 小程序 / 文档
   ============================================================ */
function PageDist() {
  const [rows, ops] = useTable("platforms_v6", window.__SEED__.PLATFORM_DETAILS);
  const [docs, docsOps] = useTable("dist_docs_v3", window.__SEED__.DIST_DOCS);
  const { editing } = useEditMode();
  const [drawerId, setDrawerId] = useState(null);
  const [regionFilter, setRegionFilter] = useState("__all__");

  const blank = {
    name: "", region: "国内", category: "", mainEntity: "", status: "正常",
    docs: [], sections: [], note: "",
  };
  const blankDoc = { name: "", type: "SOP", url: "", desc: "", owner: "", updated: "" };

  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 regionCounts = useMemo(() => {
    const m = { __all__: rows.length, 国内: 0, 国外: 0 };
    rows.forEach(r => { m[r.region] = (m[r.region] || 0) + 1; });
    return m;
  }, [rows]);

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

  // count "records" across all sections + docs to show as resource indicator
  const recordCount = (r) => {
    const docCount = (r.docs || []).length;
    const sectionRows = (r.sections || []).reduce((s, sec) => s + (sec.rows || []).length, 0);
    return docCount + sectionRows;
  };

  return (
    <>
      <FolderHead
        index="04"
        title="发行流程"
        sub="上传母片 → 传剧 / 投流 → 审核回收 → 结算对账"
      />

      <ProcessFlow steps={window.__SEED__.FLOW_DIST} title="发行四步流程" />

      <div className="section">
        <div className="section__head">
          <h3 className="section__title">发行平台</h3>
          <span className="section__sub">每个平台的子账号 / 厂牌 / 小程序 / 文档 · 点击行查看完整信息</span>
        </div>

        <div className="filter-bar">
          <div className="filter-bar__group">
            <span className="filter-bar__label">平台类型</span>
            <button
              className={"filter-tab" + (regionFilter === "__all__" ? " is-active" : "")}
              onClick={() => setRegionFilter("__all__")}
            >全部<span className="filter-tab__count">{regionCounts.__all__}</span></button>
            {["国内", "国外"].map(r => (
              <button
                key={r}
                className={"filter-tab" + (regionFilter === r ? " is-active" : "")}
                onClick={() => setRegionFilter(r)}
              >{r}<span className="filter-tab__count">{regionCounts[r] || 0}</span></button>
            ))}
          </div>
        </div>

        <div className="tbl-wrap">
          <table className="tbl tbl--compact tbl--fixed entity-tbl">
            <colgroup>
              <col style={{ width: 130 }} />
              <col style={{ width: 84 }} />
              <col style={{ width: 220 }} />
              <col style={{ width: 90 }} />
              <col style={{ width: 80 }} />
              <col />
              <col style={{ width: 56 }} />
              {editing && <col style={{ width: 56 }} />}
            </colgroup>
            <thead>
              <tr>
                <th>平台</th>
                <th>类型</th>
                <th>分类</th>
                <th>状态</th>
                <th className="center">条目</th>
                <th>备注</th>
                <th></th>
                {editing && <th className="center">操作</th>}
              </tr>
            </thead>
            <tbody>
              {visible.length === 0 ? (
                <tr>
                  <td colSpan={editing ? 8 : 7}>
                    <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 isStop = r.status === "未开通" || r.status === "停用";
                return (
                  <tr
                    key={r.id}
                    className={"entity-row" + (isStop ? " 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">
                        {editing ? (
                          <select
                            value={r.region}
                            onChange={(e) => set("region", e.target.value)}
                            className={`tag tag--type tag--${r.region === "国外" ? "site" : "sop"}`}
                            style={{ border: "none", appearance: "menulist", cursor: "pointer", padding: "2px 6px", fontFamily: "inherit", fontSize: 11.5 }}
                          >
                            <option value="国内">国内</option>
                            <option value="国外">国外</option>
                          </select>
                        ) : (
                          <span className={`tag tag--type tag--${r.region === "国外" ? "site" : "sop"}`}>{r.region}</span>
                        )}
                      </div>
                    </td>
                    <td><EditableCell value={r.category} onChange={v => set("category", v)} placeholder="—" /></td>
                    <td>
                      <div className="cell">
                        <StatusBadge
                          value={r.status}
                          onChange={v => set("status", v)}
                          options={["正常","试运营","未开通","停用"]}
                        />
                      </div>
                    </td>
                    <td>
                      <div className="cell center" style={{ color: recordCount(r) > 0 ? "var(--ink-2)" : "var(--ink-4)", fontFamily: "var(--font-mono)", fontSize: 12 }}>
                        {recordCount(r)}
                      </div>
                    </td>
                    <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 }}>点击任意平台查看子账号 / 厂牌 / 小程序 / 文档;条目 = 文档数 + 子表行数</span>
          </div>
        </div>
      </div>

      <div className="section">
        <div className="section__head">
          <h3 className="section__title">辅助文档</h3>
          <span className="section__sub">催审、取消申请等异常处理表单</span>
        </div>
        <div className="tbl-wrap">
          <table className="tbl tbl--compact tbl--fixed">
            <colgroup>
              <col style={{ width: 160 }} />
              <col style={{ width: 90 }} />
              <col style={{ width: 280 }} />
              <col style={{ width: 240 }} />
              <col style={{ width: 110 }} />
              <col style={{ width: 110 }} />
              {editing && <col style={{ width: 56 }} />}
            </colgroup>
            <thead>
              <tr>
                <th>文档</th>
                <th>类型</th>
                <th>URL</th>
                <th>用途</th>
                <th>维护人</th>
                <th>更新</th>
                {editing && <th className="center">操作</th>}
              </tr>
            </thead>
            <tbody>
              {docs.map(r => {
                const set = (k, v) => docsOps.setCell(r.id, k, v);
                const colorKey = (TYPE_COLOR || {})[r.type] || "default";
                return (
                  <tr key={r.id}>
                    <td className="col-name"><EditableCell value={r.name} onChange={v => set("name", v)} /></td>
                    <td>
                      <div className="cell">
                        {editing ? (
                          <select
                            value={r.type}
                            onChange={(e) => set("type", e.target.value)}
                            className={`tag tag--type tag--${colorKey}`}
                            style={{ border: "none", appearance: "menulist", cursor: "pointer", padding: "2px 6px", fontFamily: "inherit", fontSize: 11.5 }}
                          >
                            {["SOP", "申请表", "反馈表", "排期", "网站", "协议"].map(t => <option key={t} value={t}>{t}</option>)}
                          </select>
                        ) : (
                          <span className={`tag tag--type tag--${colorKey}`}>{r.type}</span>
                        )}
                      </div>
                    </td>
                    <td className="col-url"><EditableCell value={r.url} onChange={v => set("url", v)} placeholder="粘贴 URL" /></td>
                    <td><EditableCell value={r.desc} onChange={v => set("desc", v)} placeholder="—" /></td>
                    <td><EditableCell value={r.owner} onChange={v => set("owner", v)} placeholder="—" /></td>
                    <td className="col-id"><EditableCell value={r.updated} onChange={v => set("updated", v)} className="mono" placeholder="—" /></td>
                    {editing && (
                      <td><div className="cell center"><DeleteBtn onClick={() => docsOps.removeRow(r.id)} /></div></td>
                    )}
                  </tr>
                );
              })}
            </tbody>
          </table>
          <div className="tbl-foot">
            <button className="btn-add" onClick={() => docsOps.addRow(blankDoc)}>＋ 新增文档</button>
          </div>
        </div>
      </div>

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

function PlatformDrawer({ row, onChange, onClose, editing = true }) {
  const r = row;
  const setDocs = (newDocs) => onChange("docs", newDocs);
  const setSections = (newSections) => onChange("sections", newSections);

  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 style={{ marginTop: 6, display: "flex", gap: 8, alignItems: "center", fontSize: 12, color: "var(--ink-3)" }}>
              <span className={`tag tag--type tag--${r.region === "国外" ? "site" : "sop"}`}>{r.region}</span>
              <span>{r.category}</span>
              {r.mainEntity && r.mainEntity !== "—" && (
                <>
                  <span style={{ opacity: 0.4 }}>·</span>
                  <span>主体 {r.mainEntity}</span>
                </>
              )}
            </div>
          </div>
          <button className="drawer__close" onClick={onClose} aria-label="关闭">✕</button>
        </header>

        <div className="drawer__body">
          {/* Documents section */}
          {(r.docs && r.docs.length > 0) || editing ? (
            <DrawerSection title="平台文档 / 后台入口">
              <div className="pd-list">
                {(r.docs || []).map((d, i) => (
                  <div key={i} className="pd-row">
                    <div className="pd-row__label">
                      <EditableCell
                        value={d.label}
                        onChange={(v) => {
                          const next = [...r.docs];
                          next[i] = { ...d, label: v };
                          setDocs(next);
                        }}
                        placeholder="文档名"
                      />
                    </div>
                    <div className="pd-row__val">
                      <EditableCell
                        value={d.url}
                        onChange={(v) => {
                          const next = [...r.docs];
                          next[i] = { ...d, url: v };
                          setDocs(next);
                        }}
                        placeholder="粘贴 URL"
                      />
                    </div>
                    {editing && (
                      <button
                        className="btn-del"
                        onClick={() => setDocs(r.docs.filter((_, j) => j !== i))}
                      >×</button>
                    )}
                  </div>
                ))}
                {editing && (
                  <button
                    className="btn-add"
                    style={{ alignSelf: "flex-start", marginTop: 4 }}
                    onClick={() => setDocs([...(r.docs || []), { label: "", url: "" }])}
                  >＋ 新增文档</button>
                )}
              </div>
            </DrawerSection>
          ) : null}

          {/* Sections (sub-tables) */}
          {(r.sections || []).map((sec, si) => (
            <DrawerSection key={si} title={sec.title} hint={sec.subtitle}>
              <SubTable
                section={sec}
                editing={editing}
                onChange={(updated) => {
                  const next = [...r.sections];
                  next[si] = updated;
                  setSections(next);
                }}
                onDelete={() => setSections(r.sections.filter((_, j) => j !== si))}
              />
            </DrawerSection>
          ))}

          {editing && (
            <div style={{ marginTop: 16 }}>
              <button
                className="btn-add"
                onClick={() => {
                  const title = prompt("新分区标题");
                  if (!title) return;
                  setSections([
                    ...(r.sections || []),
                    { title, subtitle: "", columns: ["字段 1", "字段 2"], rows: [["", ""]] },
                  ]);
                }}
              >＋ 新增分区</button>
            </div>
          )}

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

          {!editing && (
            <div className="drawer__hint">
              开启<strong>编辑模式</strong>后,任意字段可点击修改;所有修改自动保存。
            </div>
          )}
        </div>
      </aside>
    </>
  );
}

function SubTable({ section, editing, onChange, onDelete }) {
  const { columns = [], rows = [], colTypes = [] } = section;
  const setRow = (ri, ci, v) => {
    const next = rows.map((row, i) => {
      if (i !== ri) return row;
      const nr = [...row];
      nr[ci] = v;
      return nr;
    });
    onChange({ ...section, rows: next });
  };
  const addRow = () => onChange({ ...section, rows: [...rows, columns.map(() => "")] });
  const delRow = (ri) => {
    if (!confirm("删除该行?")) return;
    onChange({ ...section, rows: rows.filter((_, i) => i !== ri) });
  };
  const setColType = (ci, options) => {
    const next = [...(colTypes.length ? colTypes : columns.map(() => null))];
    next[ci] = options;
    onChange({ ...section, colTypes: next });
  };
  const setColName = (ci, name) => {
    const next = [...columns];
    next[ci] = name;
    onChange({ ...section, columns: next });
  };
  const addCol = () => {
    const name = prompt("新增列名");
    if (!name) return;
    const newColumns = [...columns, name];
    const newRows = rows.map(r => [...r, ""]);
    const newColTypes = [...(colTypes.length ? colTypes : columns.map(() => null)), null];
    onChange({ ...section, columns: newColumns, rows: newRows, colTypes: newColTypes });
  };
  const editColOptions = (ci) => {
    const cur = colTypes[ci];
    const txt = prompt(
      `列「${columns[ci]}」的下拉选项,用逗号分隔(留空表示不限,改为自由输入)`,
      Array.isArray(cur) ? cur.join("、") : ""
    );
    if (txt == null) return;
    const opts = txt.split(/[、,，]/).map(s => s.trim()).filter(Boolean);
    setColType(ci, opts.length ? opts : null);
  };

  return (
    <div className="sub-tbl-wrap">
      <table className="sub-tbl">
        <thead>
          <tr>
            {columns.map((c, ci) => {
              const opts = colTypes[ci];
              return (
                <th key={ci}>
                  {editing ? (
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                      <input
                        value={c}
                        onChange={e => setColName(ci, e.target.value)}
                        style={{
                          background: "transparent", border: "none",
                          font: "inherit", color: "inherit", padding: 0,
                          width: Math.max(4, (c || "").length) + 2 + "ch",
                          minWidth: 24, outline: "none",
                        }}
                      />
                      <button
                        type="button"
                        className="btn-coltype"
                        title={opts ? "下拉:" + opts.join("、") + " · 点击修改" : "设为下拉"}
                        onClick={() => editColOptions(ci)}
                      >{opts ? "▾" : "✎"}</button>
                    </span>
                  ) : c}
                </th>
              );
            })}
            {editing && <th style={{ width: 56 }}><button className="btn-add" onClick={addCol} style={{ padding: "2px 6px", fontSize: 11 }}>＋列</button></th>}
          </tr>
        </thead>
        <tbody>
          {rows.length === 0 ? (
            <tr>
              <td colSpan={columns.length + (editing ? 1 : 0)} style={{ color: "var(--ink-4)", fontSize: 12, padding: "10px 12px", fontStyle: "italic" }}>
                暂无记录
              </td>
            </tr>
          ) : rows.map((row, ri) => (
            <tr key={ri}>
              {columns.map((_, ci) => {
                const opts = colTypes[ci];
                if (Array.isArray(opts) && opts.length && editing) {
                  return (
                    <td key={ci}>
                      <div className="cell" style={{ padding: "4px 8px" }}>
                        <select
                          value={row[ci] || ""}
                          onChange={e => setRow(ri, ci, e.target.value)}
                          style={{
                            background: "transparent", border: "none",
                            font: "inherit", color: "inherit",
                            padding: "2px 4px", width: "100%", cursor: "pointer",
                            outline: "none",
                          }}
                        >
                          <option value="">—</option>
                          {opts.map(o => <option key={o} value={o}>{o}</option>)}
                        </select>
                      </div>
                    </td>
                  );
                }
                return (
                  <td key={ci}>
                    <EditableCell
                      value={row[ci]}
                      onChange={(v) => setRow(ri, ci, v)}
                      placeholder="—"
                    />
                  </td>
                );
              })}
              {editing && (
                <td>
                  <button className="btn-del" onClick={() => delRow(ri)} title="删除该行">×</button>
                </td>
              )}
            </tr>
          ))}
        </tbody>
      </table>
      {editing && (
        <div className="sub-tbl-foot">
          <button className="btn-add" onClick={addRow}>＋ 新增行</button>
          <button className="btn-del" onClick={onDelete} style={{ marginLeft: 8 }}>删除整个分区</button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PageDist });
