/* ============================================================
   doc-table.jsx — DocList + ProcessFlow + Section header
   两个统一组件,所有 4 个文件夹都用它们
   ============================================================ */

/* ---------------- ProcessFlow ---------------- */
function ProcessFlow({ steps, title = "流程说明" }) {
  return (
    <div className="proc">
      <div className="proc__head">
        <span className="proc__dot" />
        <span className="proc__title">{title}</span>
      </div>
      <div className="proc__steps">
        {steps.map((s, i) => (
          <React.Fragment key={i}>
            <div className="proc__step">
              <div className="proc__num">{String(i + 1).padStart(2, "0")}</div>
              <div className="proc__body">
                <div className="proc__name">{s.name}</div>
                {s.who && <div className="proc__who">{s.who}</div>}
                {s.desc && <div className="proc__desc">{s.desc}</div>}
              </div>
            </div>
            {i < steps.length - 1 && <div className="proc__arrow">→</div>}
          </React.Fragment>
        ))}
      </div>
    </div>
  );
}

/* ---------------- DocList ----------------
   columns:
     文档名 · 类型 · 归属 · URL · 描述 · 维护人 · 最近更新
   ---------------------------------------- */
const TYPE_COLOR = {
  "书单":       "books",
  "网站":       "site",
  "项目介绍":   "brief",
  "活动方案":   "campaign",
  "SOP":        "sop",
  "协议":       "deal",
  "排期":       "sched",
  "申请表":     "apply",
  "反馈表":     "feedback",
  "字段词典":   "dict",
  "主体资料":   "entity",
};

function DocList({ tableKey, seed, types, title, subtitle, hint }) {
  const [rows, ops] = useTable(tableKey, seed);
  const { editing } = useEditMode();
  const [typeFilter, setTypeFilter] = useState("__all__");
  const [belongFilter, setBelongFilter] = useState("__all__");
  const blank = { name: "", type: types[0], belong: "", url: "", desc: "", owner: "", updated: "" };

  const availableTypes = useMemo(() => {
    const present = new Set(rows.map(r => r.type));
    return types.filter(t => present.has(t));
  }, [rows, types]);

  const belongOptions = useMemo(() => {
    const set = new Set();
    rows.forEach(r => { if (r.belong) set.add(r.belong); });
    return [...set];
  }, [rows]);

  const visible = useMemo(() => rows.filter(r =>
    (typeFilter === "__all__" || r.type === typeFilter) &&
    (belongFilter === "__all__" || r.belong === belongFilter)
  ), [rows, typeFilter, belongFilter]);

  return (
    <div className="section">
      <div className="section__head">
        <h3 className="section__title">{title}</h3>
        {subtitle && <span className="section__sub">{subtitle}</span>}
      </div>
      {hint && <div className="note" style={{ marginBottom: 12 }}>{hint}</div>}

      <div className="filter-bar">
        <div className="filter-bar__group">
          <span className="filter-bar__label">类型</span>
          <button
            className={"filter-tab" + (typeFilter === "__all__" ? " is-active" : "")}
            onClick={() => setTypeFilter("__all__")}
          >全部</button>
          {availableTypes.map(t => {
            const colorKey = TYPE_COLOR[t] || "default";
            return (
              <button
                key={t}
                className={`filter-tab filter-tab--${colorKey}` + (typeFilter === t ? " is-active" : "")}
                onClick={() => setTypeFilter(t)}
              >{t}</button>
            );
          })}
        </div>
        {belongOptions.length > 1 && (
          <div className="filter-bar__group">
            <span className="filter-bar__label">归属</span>
            <select
              className="filter-select"
              value={belongFilter}
              onChange={e => setBelongFilter(e.target.value)}
            >
              <option value="__all__">全部归属</option>
              {belongOptions.map(b => <option key={b} value={b}>{b}</option>)}
            </select>
            {belongFilter !== "__all__" && (
              <button className="filter-clear" onClick={() => setBelongFilter("__all__")}>清除 ✕</button>
            )}
          </div>
        )}
      </div>

      <div className="tbl-wrap">
        <table className="tbl tbl--docs-v2">
          <colgroup>
            <col style={{ width: 260 }} />
            <col style={{ width: 90 }} />
            <col style={{ width: 130 }} />
            <col />
            <col style={{ width: 110 }} />
            <col style={{ width: 96 }} />
            {editing && <col style={{ width: 60 }} />}
          </colgroup>
          <thead>
            <tr>
              <th>文档</th>
              <th>类型</th>
              <th>归属</th>
              <th>URL</th>
              <th>维护人</th>
              <th>更新</th>
              {editing && <th className="center">操作</th>}
            </tr>
          </thead>
          <tbody>
            {visible.length === 0 ? (
              <tr>
                <td colSpan={editing ? 7 : 6}>
                  <div className="cell" style={{ justifyContent: "center", color: "var(--ink-4)", padding: "32px 0", minHeight: 0 }}>
                    没有符合条件的文档 ·
                    <button
                      className="filter-clear"
                      style={{ marginLeft: 8 }}
                      onClick={() => { setTypeFilter("__all__"); setBelongFilter("__all__"); }}
                    >清除筛选</button>
                  </div>
                </td>
              </tr>
            ) : visible.map(r => {
              const set = (k, v) => ops.setCell(r.id, k, v);
              const colorKey = TYPE_COLOR[r.type] || "default";
              return (
                <tr key={r.id}>
                  <td className="col-doc">
                    <div className="cell-stack">
                      <div className="cell-stack__primary">
                        <EditableCell value={r.name} onChange={v => set("name", v)} placeholder="文档名" />
                      </div>
                      <div className="cell-stack__secondary">
                        <EditableCell value={r.desc} onChange={v => set("desc", v)} placeholder="一句话描述" />
                      </div>
                    </div>
                  </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 }}
                        >
                          {types.map(t => <option key={t} value={t}>{t}</option>)}
                        </select>
                      ) : (
                        <span className={`tag tag--type tag--${colorKey}`}>{r.type}</span>
                      )}
                    </div>
                  </td>
                  <td><EditableCell value={r.belong} onChange={v => set("belong", v)} placeholder="—" /></td>
                  <td className="col-url"><EditableCell value={r.url} onChange={v => set("url", v)} placeholder="粘贴飞书 / 网站 URL" /></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)} placeholder="YYYY-MM-DD" className="mono" /></td>
                  {editing && (
                    <td><div className="cell center"><DeleteBtn onClick={() => ops.removeRow(r.id)} /></div></td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </table>
        <AddRowBar onAdd={() => ops.addRow(blank)} label="新增文档" />
      </div>
    </div>
  );
}

/* ---------------- FolderHead ---------------- */
function FolderHead({ index, title, sub, meta }) {
  return (
    <div className="folder-head">
      <div className="folder-head__main">
        <div className="folder-head__index">{index}</div>
        <div>
          <h1 className="folder-head__title">{title}</h1>
          {sub && <div className="folder-head__sub">{sub}</div>}
        </div>
      </div>
      {meta && <div className="folder-head__meta">{meta}</div>}
    </div>
  );
}

Object.assign(window, { ProcessFlow, DocList, FolderHead, TYPE_COLOR });
