/* ============================================================
   page-backend.jsx — 工作后台
   字段：名称 / 工作用途 / 工作地址 / 用户名 / 密码 / 后台类型
   ============================================================ */
function PageBackend() {
  const [rows, ops] = useTable("work_backends_v1", window.__SEED__.WORK_BACKENDS || []);
  const { editing } = useEditMode();
  const [showPwd, setShowPwd] = useState({});
  const [typeFilter, setTypeFilter] = useState("__all__");

  const blank = { name: "", usage: "", url: "", username: "", password: "", type: "" };
  const TYPES = ["版权平台", "协作工具", "内容平台", "财务系统", "运营后台", "其他"];

  const typeCounts = useMemo(() => {
    const m = { __all__: rows.length };
    rows.forEach(r => { if (r.type) m[r.type] = (m[r.type] || 0) + 1; });
    return m;
  }, [rows]);

  const visible = useMemo(() =>
    typeFilter === "__all__" ? rows : rows.filter(r => r.type === typeFilter),
    [rows, typeFilter]
  );

  return (
    <>
      <FolderHead
        index="06"
        title="工作后台"
        sub="内部使用的各平台后台账号汇总"
      />

      <div className="filter-bar" style={{ marginBottom: 16 }}>
        <div className="filter-bar__group">
          <button
            className={"filter-tab" + (typeFilter === "__all__" ? " is-active" : "")}
            onClick={() => setTypeFilter("__all__")}
          >全部<span className="filter-tab__count">{typeCounts.__all__}</span></button>
          {TYPES.filter(t => typeCounts[t]).map(t => (
            <button
              key={t}
              className={"filter-tab" + (typeFilter === t ? " is-active" : "")}
              onClick={() => setTypeFilter(t)}
            >{t}<span className="filter-tab__count">{typeCounts[t]}</span></button>
          ))}
        </div>
      </div>

      <div className="tbl-wrap tbl-wrap--scroll">
        <table className="tbl tbl--fixed">
          <colgroup>
            <col style={{ width: 130 }} />
            <col style={{ width: 220 }} />
            <col style={{ width: 150 }} />
            <col style={{ width: 120 }} />
            <col style={{ width: 120 }} />
            <col style={{ width: 90 }} />
            {editing && <col style={{ width: 60 }} />}
          </colgroup>
          <thead>
            <tr>
              <th>名称</th>
              <th>工作地址</th>
              <th>工作用途</th>
              <th>用户名</th>
              <th>密码</th>
              <th>后台类型</th>
              {editing && <th className="center">操作</th>}
            </tr>
          </thead>
          <tbody>
            {visible.map(r => {
              const set = (k, v) => ops.setCell(r.id, k, v);
              const pwdVisible = showPwd[r.id];
              return (
                <tr key={r.id}>
                  <td><strong><EditableCell value={r.name} onChange={v => set("name", v)} placeholder="后台名称" /></strong></td>
                  <td className="col-url"><EditableCell value={r.url} onChange={v => set("url", v)} placeholder="粘贴地址 URL" /></td>
                  <td><EditableCell value={r.usage} onChange={v => set("usage", v)} placeholder="用途说明" /></td>
                  <td><EditableCell value={r.username} onChange={v => set("username", v)} placeholder="—" /></td>
                  <td>
                    <div className="cell" style={{ gap: 6 }}>
                      {editing ? (
                        <input
                          value={r.password || ""}
                          onChange={e => set("password", e.target.value)}
                          type="text"
                          placeholder="—"
                          style={{ border:"none", outline:"none", background:"transparent", font:"inherit", fontSize:13, color:"inherit", flex:1, minWidth:0 }}
                        />
                      ) : r.password ? (
                        <>
                          <span style={{ fontFamily:"monospace", letterSpacing: pwdVisible ? 0 : 2 }}>
                            {pwdVisible ? r.password : "•".repeat(Math.min(r.password.length, 8))}
                          </span>
                          <span
                            onClick={() => setShowPwd(p => ({ ...p, [r.id]: !p[r.id] }))}
                            style={{ fontSize:11, color:"var(--ink-3)", cursor:"pointer", flexShrink:0 }}
                          >{pwdVisible ? "隐藏" : "查看"}</span>
                        </>
                      ) : <span className="muted">—</span>}
                    </div>
                  </td>
                  <td>
                    {editing ? (
                      <select
                        value={r.type || ""}
                        onChange={e => set("type", e.target.value)}
                        style={{ border:"1px solid var(--rule)", borderRadius:3, padding:"3px 6px", fontSize:12, background:"var(--surface)", outline:"none", width:"100%" }}
                      >
                        <option value="">—</option>
                        {TYPES.map(t => <option key={t} value={t}>{t}</option>)}
                      </select>
                    ) : r.type ? (
                      <span style={{ fontSize:11, padding:"2px 8px", borderRadius:3, background:"var(--paper-2)", color:"var(--ink-2)" }}>{r.type}</span>
                    ) : <span className="muted">—</span>}
                  </td>
                  {editing && (
                    <td><div className="cell center"><DeleteBtn onClick={() => 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>
    </>
  );
}

Object.assign(window, { PageBackend });
