/* ============================================================
   shell.jsx — TopBar + Sidebar (v2 · 4 folders only)
   ============================================================ */
const NAV = [
  { id: "cpr-archive", label: "版权方档案",     desc: "19 家版权方 · 官方表 / 书单 / 后台 / 对接群" },
  { id: "cpr-flow",    label: "版权流程",       desc: "承制方申请 → 审核 → 反馈 + 表单矩阵" },
  { id: "prod-flow",   label: "生产流程",       desc: "23 个线下自营操盘手工程文件源" },
  { id: "dist",        label: "发行流程",       desc: "上传 → 传剧 → 审核 + 各平台账号" },
  { id: "entity",      label: "公司主体后台",   desc: "15 家法人 · 机构认证 / 绑合同" },
];

function TopBar({ activePage }) {
  const { editing, setEditing } = useEditMode();
  const page = NAV.find(n => n.id === activePage);
  const fileRef = useRef(null);

  const exportAll = () => {
    const data = {};
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k && k.startsWith("__mj_")) {
        try { data[k] = JSON.parse(localStorage.getItem(k)); }
        catch { data[k] = localStorage.getItem(k); }
      }
    }
    const blob = new Blob([JSON.stringify({
      __schema: "manju-workbench/v1",
      __exported: new Date().toISOString(),
      data,
    }, null, 2)], { type: "application/json" });
    const ts = new Date().toISOString().slice(0, 16).replace(/[T:]/g, "-");
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `漫剧文件夹-备份-${ts}.json`;
    a.click();
    setTimeout(() => URL.revokeObjectURL(a.href), 1000);
  };

  const importAll = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const ok = confirm(
      "导入备份会覆盖当前所有数据,是否继续?\n\n" +
      "建议先点「导出 JSON」做一次本地备份。"
    );
    if (!ok) { e.target.value = ""; return; }
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const parsed = JSON.parse(reader.result);
        const data = parsed.data || parsed;
        if (typeof data !== "object" || data == null) throw new Error("格式错误");
        // wipe old __mj_ keys then write new
        const oldKeys = [];
        for (let i = 0; i < localStorage.length; i++) {
          const k = localStorage.key(i);
          if (k && k.startsWith("__mj_")) oldKeys.push(k);
        }
        oldKeys.forEach(k => localStorage.removeItem(k));
        Object.entries(data).forEach(([k, v]) => {
          if (k.startsWith("__mj_")) {
            localStorage.setItem(k, typeof v === "string" ? v : JSON.stringify(v));
          }
        });
        alert("导入成功,即将刷新页面。");
        location.reload();
      } catch (err) {
        alert("导入失败:" + err.message);
      }
    };
    reader.readAsText(file);
    e.target.value = "";
  };

  return (
    <header className="topbar">
      <div className="topbar__brand">
        <div className="topbar__stamp">豹</div>
        <span>漫剧文件夹</span>
      </div>
      <div className="topbar__crumbs">
        {page && <strong>{page.label}</strong>}
      </div>
      <div className="topbar__actions">
        <input
          ref={fileRef}
          type="file"
          accept="application/json,.json"
          onChange={importAll}
          style={{ display: "none" }}
        />
        <button
          className="topbar__icon-btn"
          onClick={() => fileRef.current?.click()}
          title="导入 JSON 备份(覆盖当前数据)"
        >
          <span style={{ fontSize: 13 }}>↓</span> 导入
        </button>
        <button
          className="topbar__icon-btn"
          onClick={exportAll}
          title="导出全部数据为 JSON 备份"
        >
          <span style={{ fontSize: 13 }}>↑</span> 导出
        </button>
        <button
          className={`edit-toggle ${editing ? "is-on" : ""}`}
          onClick={() => setEditing(!editing)}
          title={editing ? "关闭编辑模式" : "开启编辑模式 — 所有单元格可点击修改"}
        >
          <span className="dot"></span>
          {editing ? "编辑模式 已开启" : "编辑模式"}
        </button>
      </div>
    </header>
  );
}

function Sidebar({ active, onPick }) {
  return (
    <aside className="sidebar">
      <div className="sidebar__intro">
        <div className="sidebar__intro-title">5 个文件夹</div>
        <div className="sidebar__intro-desc">每个文件夹 = 流程说明 + 关键文档</div>
      </div>
      {NAV.map((it, i) => (
        <div
          key={it.id}
          className={"sidebar__folder" + (active === it.id ? " is-active" : "")}
          onClick={() => onPick(it.id)}
        >
          <div className="sidebar__folder-num">{String(i + 1).padStart(2, "0")}</div>
          <div className="sidebar__folder-body">
            <div className="sidebar__folder-label">{it.label}</div>
            <div className="sidebar__folder-desc">{it.desc}</div>
          </div>
        </div>
      ))}
      <div style={{ padding: "24px 18px 0", fontSize: 11, color: "#9C978A", lineHeight: 1.7 }}>
        <div>v0.2 · 内部使用</div>
        <div>所有修改自动存本地</div>
      </div>
    </aside>
  );
}

function EditBanner() {
  const { editing } = useEditMode();
  if (!editing) return null;
  return (
    <div className="edit-banner">
      <strong>编辑模式已开启 ·</strong> 单击单元格直接修改,粘贴 URL 自动识别为链接,所有修改自动保存到浏览器本地。
    </div>
  );
}

Object.assign(window, { NAV, TopBar, Sidebar, EditBanner });
