/* ============================================================
   page-entity.jsx — 公司主体后台
   15 家法人主体 · 机构认证 / 绑合同 / 银行账户
   ============================================================ */
function PageEntity() {
  const [rows, ops] = useTable("entities_v4", window.__SEED__.ENTITIES);
  const { editing } = useEditMode();
  const [drawerId, setDrawerId] = useState(null);
  const [statusFilter, setStatusFilter] = useState("__all__");
  const blank = {
    name: "", uscc: "", license: "",
    legal: "", legalId: "", legalIdPhoto: "",
    accountName: "",
    bank: "", account: "", alipayVerified: "",
    realName: "", realNameId: "",
    phone: "", email: "", address: "",
    wechat: "",
    phoneContact: "", emailContact: "", wechatContact: "",
    status: "—", fanqie: "—", 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 drawerEntity = useMemo(() => rows.find(r => r.id === drawerId), [rows, drawerId]);

  const statusCounts = useMemo(() => ({
    __all__: rows.length,
    OK: rows.filter(r => r.status === "OK").length,
    pending: rows.filter(r => r.status !== "OK").length,
  }), [rows]);
  const visible = useMemo(() => rows.filter(r => {
    if (statusFilter === "__all__") return true;
    if (statusFilter === "OK") return r.status === "OK";
    return r.status !== "OK";
  }), [rows, statusFilter]);

  return (
    <>
      <FolderHead
        index="05"
        title="公司主体后台"
        sub="法人主体 · 信用代码 / 营业执照 / 银行账户 / 联系人 一站式查找"
      />

      <div className="callout" style={{ marginTop: 20 }}>
        <strong>用途 ·</strong>
        <strong>机构认证用</strong> — 给平台提交主体认证时调取(信用代码 / 营业执照 / 法人 / 银行);
        <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>
          <button
            className={"filter-tab" + (statusFilter === "OK" ? " is-active" : "")}
            onClick={() => setStatusFilter("OK")}
          >已开通<span className="filter-tab__count">{statusCounts.OK}</span></button>
          <button
            className={"filter-tab" + (statusFilter === "pending" ? " is-active" : "")}
            onClick={() => setStatusFilter("pending")}
          >待开通<span className="filter-tab__count">{statusCounts.pending}</span></button>
        </div>
      </div>

      <div className="tbl-wrap tbl-wrap--scroll">
        <table className="tbl tbl--compact tbl--fixed entity-tbl">
          <colgroup>
            <col style={{ width: 280 }} />
            <col style={{ width: 170 }} />
            <col style={{ width: 80 }} />
            <col style={{ width: 240 }} />
            <col style={{ width: 96 }} />
            <col style={{ width: 92 }} />
            <col style={{ width: 96 }} />
            <col style={{ width: 56 }} />
            {editing && <col style={{ width: 60 }} />}
          </colgroup>
          <thead>
            <tr>
              <th>法人主体</th>
              <th>统一信用代码</th>
              <th>法人</th>
              <th>开户行 / 账号</th>
              <th>联系人</th>
              <th>后台</th>
              <th>番茄 IP</th>
              <th></th>
              {editing && <th className="center">操作</th>}
            </tr>
          </thead>
          <tbody>
            {visible.map(r => {
              const set = (k, v) => ops.setCell(r.id, k, v);
              return (
                <tr key={r.id} className="entity-row" onClick={(e) => {
                  // ignore clicks on input / button / select (let editing happen)
                  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 className="col-id"><EditableCell value={r.uscc} onChange={v => set("uscc", v)} className="mono" /></td>
                  <td>
                    <div className="cell" style={{ whiteSpace: "nowrap" }}>
                      <EditableCell value={r.legal} onChange={v => set("legal", v)} />
                    </div>
                  </td>
                  <td>
                    <div className="cell-stack" style={{ padding: "6px 10px" }}>
                      <div className="cell-stack__primary">
                        <EditableCell value={r.bank} onChange={v => set("bank", v)} placeholder="开户行" />
                      </div>
                      <div className="cell-stack__secondary">
                        <EditableCell value={r.account} onChange={v => set("account", v)} placeholder="账号" />
                      </div>
                    </div>
                  </td>
                  <td>
                    <div className="cell" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                      <EditableCell
                        value={r.phoneContact || r.emailContact || r.wechatContact}
                        onChange={v => set("phoneContact", v)}
                        placeholder="—"
                      />
                    </div>
                  </td>
                  <td>
                    <div className="cell">
                      <StatusBadge
                        value={r.status === "OK" ? "OK" : (r.status || "—")}
                        onChange={v => set("status", v)}
                        options={["OK", "进行中", "待申请", "—"]}
                      />
                    </div>
                  </td>
                  <td>
                    <div className="cell" style={{ fontSize: 12, color: "var(--ink-3)" }}>
                      <EditableCell value={r.fanqie} onChange={v => set("fanqie", 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>

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

function EntityDrawer({ entity, onChange, onClose, editing }) {
  const r = entity;
  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="① 机构认证" hint="给平台提交资质用">
            <DrawerRow label="公司名称">
              <EditableCell value={r.name} onChange={v => onChange("name", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="统一信用代码" mono>
              <EditableCell value={r.uscc} onChange={v => onChange("uscc", v)} placeholder="—" className="mono" />
            </DrawerRow>
            <DrawerRow label="营业执照">
              <EditableCell value={r.license} onChange={v => onChange("license", v)} placeholder="粘贴飞书 / 图床 URL" />
            </DrawerRow>
            <DrawerRow label="法人代表">
              <EditableCell value={r.legal} onChange={v => onChange("legal", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="法人身份证号" mono>
              <EditableCell value={r.legalId} onChange={v => onChange("legalId", v)} placeholder="—" className="mono" />
            </DrawerRow>
            <DrawerRow label="法人身份证照片">
              <EditableCell value={r.legalIdPhoto} onChange={v => onChange("legalIdPhoto", v)} placeholder="正反面 URL" />
            </DrawerRow>
          </DrawerSection>

          <DrawerSection title="② 银行账户" hint="收款用">
            <DrawerRow label="收款账号名称">
              <EditableCell value={r.accountName} onChange={v => onChange("accountName", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="开户银行">
              <EditableCell value={r.bank} onChange={v => onChange("bank", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="银行卡号" mono>
              <EditableCell value={r.account} onChange={v => onChange("account", v)} placeholder="—" className="mono" />
            </DrawerRow>
            <DrawerRow label="支付宝认证">
              <EditableCell value={r.alipayVerified} onChange={v => onChange("alipayVerified", v)} placeholder="一般法人支付宝认证状态" />
            </DrawerRow>
          </DrawerSection>

          <DrawerSection title="③ 实名认证" hint="绑合同用 · 可与法人不同(如惊人:法人=夏雷,实名人=杜伟强)">
            <DrawerRow label="实名人姓名">
              <EditableCell value={r.realName} onChange={v => onChange("realName", v)} placeholder="可重复认证" />
            </DrawerRow>
            <DrawerRow label="实名人身份证号" mono>
              <EditableCell value={r.realNameId} onChange={v => onChange("realNameId", v)} placeholder="—" className="mono" />
            </DrawerRow>
            <DrawerRow label="手机号" mono>
              <EditableCell value={r.phone} onChange={v => onChange("phone", v)} placeholder="—" className="mono" />
            </DrawerRow>
            <DrawerRow label="邮箱">
              <EditableCell value={r.email} onChange={v => onChange("email", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="联系微信 ID" mono>
              <EditableCell value={r.wechat} onChange={v => onChange("wechat", v)} placeholder="—" className="mono" />
            </DrawerRow>
            <DrawerRow label="联系地址">
              <EditableCell value={r.address} onChange={v => onChange("address", v)} placeholder="—" multiline />
            </DrawerRow>
          </DrawerSection>

          <DrawerSection title="④ 联系人" hint="不同渠道可对不同人">
            <DrawerRow label="手机号联系人">
              <EditableCell value={r.phoneContact} onChange={v => onChange("phoneContact", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="邮箱联系人">
              <EditableCell value={r.emailContact} onChange={v => onChange("emailContact", v)} placeholder="—" />
            </DrawerRow>
            <DrawerRow label="微信联系人">
              <EditableCell value={r.wechatContact} onChange={v => onChange("wechatContact", v)} placeholder="昵称 / 备注" />
            </DrawerRow>
          </DrawerSection>

          <DrawerSection title="⑤ 平台进度">
            <DrawerRow label="后台进度(模式一)">
              <StatusBadge
                value={r.status === "OK" ? "OK" : (r.status || "—")}
                onChange={v => onChange("status", v)}
                options={["OK", "进行中", "待申请", "—"]}
              />
            </DrawerRow>
            <DrawerRow label="番茄 IP 进度(模式二)">
              <EditableCell value={r.fanqie} onChange={v => onChange("fanqie", v)} placeholder="—" />
            </DrawerRow>
          </DrawerSection>

          <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 DrawerSection({ title, hint, children }) {
  return (
    <section className="drawer-sec">
      <header className="drawer-sec__head">
        <h3 className="drawer-sec__title">{title}</h3>
        {hint && <span className="drawer-sec__hint">{hint}</span>}
      </header>
      <div className="drawer-sec__body">{children}</div>
    </section>
  );
}

function DrawerRow({ label, children }) {
  return (
    <div className={"drawer-row" + (label ? "" : " drawer-row--full")}>
      {label && <div className="drawer-row__label">{label}</div>}
      <div className="drawer-row__value">{children}</div>
    </div>
  );
}

Object.assign(window, { PageEntity, EntityDrawer, DrawerSection, DrawerRow });
