// 图片素材库 (/image-library)
//   - 左：笔记列表（按入库时间倒序，封面 + N 张 + 来源链接）
//   - 右：选中笔记后大图 grid，可逐张删除

const ImageLibraryPage = () => {
  const [notes, setNotes]         = React.useState([]);
  const [stats, setStats]         = React.useState(null);
  const [activeId, setActiveId]   = React.useState(null);
  const [detail, setDetail]       = React.useState(null);
  const [loading, setLoading]     = React.useState(false);
  const [err, setErr]             = React.useState("");
  const [busyId, setBusyId]       = React.useState("");
  const [batchBusy, setBatchBusy] = React.useState(false);
  const [batchMsg, setBatchMsg]   = React.useState("");
  const batchInputRef             = React.useRef(null);

  const load = async () => {
    setLoading(true); setErr("");
    try {
      const r = await API.imageLibrary.list();
      setNotes(r.items || []);
      setStats(r.stats || null);
      if (!activeId && (r.items || []).length) setActiveId(r.items[0].note_id);
    } catch (e) { setErr(String(e.message || e)); }
    finally { setLoading(false); }
  };

  const loadDetail = async (noteId) => {
    if (!noteId) { setDetail(null); return; }
    try { setDetail(await API.imageLibrary.get(noteId)); }
    catch (e) { setDetail(null); setErr(String(e.message || e)); }
  };

  React.useEffect(() => { load(); }, []);
  React.useEffect(() => { loadDetail(activeId); }, [activeId]);

  const onBatchPick = async (e) => {
    const files = Array.from(e.target.files || []);
    e.target.value = "";
    if (!files.length) return;
    setBatchBusy(true); setBatchMsg(`上传中：0 / ${files.length}`);
    try {
      const fd = new FormData();
      for (const f of files) fd.append("files", f);
      // 用浏览器本地时间作 fallback 标题（后端兜底了，不传也行）
      fd.append("title", `手动上传 · ${new Date().toLocaleString("zh-CN")}`);
      const r = await API.imageLibrary.uploadImages(fd);
      const ok = r.ok_count || (r.uploaded || []).length;
      const fail = r.fail_count || (r.skipped || []).length;
      if (ok) {
        setBatchMsg(`✓ 新建笔记 ${r.note_id?.slice(0,8) || ""}… · 上传 ${ok} 张 · 跳过 ${fail}`);
        await load();
        if (r.note_id) setActiveId(r.note_id);
      } else {
        setBatchMsg(`✗ 全部失败 · ${(r.skipped?.[0]?.reason) || "未知错误"}`);
      }
    } catch (err2) {
      setBatchMsg(`✗ 上传失败：${err2.message || err2}`);
    } finally {
      setBatchBusy(false);
      setTimeout(() => setBatchMsg(""), 6000);
    }
  };

  const deleteNote = async (note) => {
    if (busyId) return;
    if (!window.confirm(`删除整条笔记「${note.title}」？\n会移除 ${note.image_count} 张图片，不可恢复。`)) return;
    setBusyId(note.note_id);
    setErr("");
    try {
      await API.imageLibrary.deleteNote(note.note_id);
      if (activeId === note.note_id) { setActiveId(null); setDetail(null); }
      await load();
    } catch (e) { setErr(String(e.message || e)); }
    finally { setBusyId(""); }
  };

  const deleteImage = async (name) => {
    if (!detail || busyId) return;
    if (!window.confirm(`删除这张图「${name}」？`)) return;
    setBusyId(`${detail.note_id}/${name}`);
    setErr("");
    try {
      await API.imageLibrary.deleteImage(detail.note_id, name);
      await loadDetail(detail.note_id);
      await load();
    } catch (e) { setErr(String(e.message || e)); }
    finally { setBusyId(""); }
  };

  const activeNote = notes.find(n => n.note_id === activeId);

  return (
    <>
      <Topbar
        crumbs={["资产", "图片素材库"]}
        right={<>
          <span className="pill" style={{
            background: "color-mix(in oklch, var(--cyan) 14%, var(--bg-1))",
            color: "var(--cyan)",
          }}>
            <Icon name="folder" size={10}/>
            {stats?.notes || 0} 笔记 · {stats?.images || 0} 张图
          </span>
          <button className="btn ghost" onClick={load} disabled={loading}>
            <Icon name="refresh" size={11}/>{loading ? "刷新…" : "刷新"}
          </button>
          <button className="btn ghost" onClick={() => batchInputRef.current?.click()}
                  disabled={batchBusy}
                  title="从本地文件夹批量上传图片（支持 jpg/jpeg/png/webp/gif · 一次可选多文件）。
所选图全部归入一条新笔记。">
            <Icon name="folder" size={11}/>{batchBusy ? "上传中…" : "批量上传素材"}
          </button>
          <input ref={batchInputRef} type="file" multiple
                 accept=".jpg,.jpeg,.png,.webp,.gif,image/*"
                 style={{ display: "none" }}
                 onChange={onBatchPick}/>
        </>}
      />

      {batchMsg && (
        <div style={{
          margin: "10px 16px 0", padding: "8px 12px", borderRadius: 5,
          background: batchMsg.startsWith("✗")
            ? "color-mix(in oklch, var(--pink) 14%, var(--bg-1))"
            : batchMsg.startsWith("✓")
              ? "color-mix(in oklch, var(--green) 14%, var(--bg-1))"
              : "color-mix(in oklch, var(--cyan) 14%, var(--bg-1))",
          color: batchMsg.startsWith("✗") ? "var(--pink)"
            : batchMsg.startsWith("✓") ? "var(--green)" : "var(--cyan)",
          fontSize: 12,
        }}>{batchMsg}</div>
      )}

      {err && (
        <div style={{ margin: "10px 16px 0", padding: "8px 12px",
                      background: "color-mix(in oklch, var(--pink) 14%, var(--bg-1))",
                      color: "var(--pink)", borderRadius: 4, fontSize: 11 }}>{err}</div>
      )}

      <div className="main-body">
        {/* 左：笔记列表 */}
        <div className="col scroll" style={{
          width: 320, flexShrink: 0, padding: "12px 12px",
          borderRight: "1px solid var(--line-soft)", background: "var(--bg-0)",
        }}>
          {notes.length === 0 ? (
            <div style={{ padding: 30, textAlign: "center", fontSize: 11, color: "var(--fg-3)" }}>
              {loading ? "加载中…" : (
                <>
                  暂无图文笔记
                  <div style={{ marginTop: 8, fontSize: 10 }}>
                    在拆解爆款页贴小红书图文笔记链接，系统会自动落到这里
                  </div>
                </>
              )}
            </div>
          ) : (
            <div className="col gap-6">
              {notes.map(n => (
                <div key={n.note_id} onClick={() => setActiveId(n.note_id)}
                     style={{
                       padding: 8, borderRadius: 5, cursor: "pointer",
                       border: `1.5px solid ${activeId === n.note_id ? "var(--cyan)" : "var(--line-1)"}`,
                       background: activeId === n.note_id
                         ? "color-mix(in oklch, var(--cyan) 8%, var(--bg-1))" : "var(--bg-1)",
                     }}>
                  <div className="row gap-8" style={{ alignItems: "center" }}>
                    {n.cover_url && (
                      <img src={window.withApiToken(n.cover_url)} style={{
                        width: 50, height: 66, objectFit: "cover",
                        borderRadius: 3, flexShrink: 0, background: "#000",
                      }} onError={(e) => { e.currentTarget.style.display = "none"; }}/>
                    )}
                    <div className="col gap-3" style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, fontWeight: 500, color: "var(--fg-0)",
                                     overflow: "hidden", textOverflow: "ellipsis",
                                     whiteSpace: "nowrap" }} title={n.title}>
                        {n.title}
                      </div>
                      <div style={{ fontSize: 10, color: "var(--fg-3)" }}>
                        {n.image_count} 张 · {n.source}
                      </div>
                      <div className="mono" style={{ fontSize: 9, color: "var(--fg-3)" }}>
                        {(n.saved_at || "").slice(0, 19).replace("T", " ")}
                      </div>
                    </div>
                    <button className="btn sm ghost"
                            onClick={(e) => { e.stopPropagation(); deleteNote(n); }}
                            disabled={busyId === n.note_id}
                            title="删除整条笔记">
                      <Icon name="close" size={10}/>
                    </button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 右：图片网格 */}
        <div className="col grow scroll" style={{
          padding: "12px 14px 24px", background: "var(--bg-0)", minWidth: 0,
        }}>
          {!activeNote ? (
            <div className="card col center" style={{ padding: "60px 20px", gap: 10, textAlign: "center" }}>
              <Icon name="folder" size={24} style={{ color: "var(--fg-3)" }}/>
              <div style={{ fontSize: 13, color: "var(--fg-1)" }}>选一条图文笔记看图</div>
            </div>
          ) : (
            <div className="col gap-10">
              <div className="row between" style={{ alignItems: "center" }}>
                <div className="col gap-2">
                  <span style={{ fontSize: 14, fontWeight: 600, color: "var(--fg-0)" }}>{activeNote.title}</span>
                  {activeNote.link_url && (
                    <a href={activeNote.link_url} target="_blank" rel="noreferrer"
                       className="mono" style={{ fontSize: 10, color: "var(--cyan)" }}>
                      {activeNote.link_url}
                    </a>
                  )}
                </div>
                <span className="kpi-l">{activeNote.image_count} 张</span>
              </div>

              {detail?.image_urls?.length ? (
                <div style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))",
                  gap: 10,
                }}>
                  {detail.image_urls.map((url, i) => {
                    const name = detail.image_names[i];
                    const isBusy = busyId === `${detail.note_id}/${name}`;
                    return (
                      <div key={url} style={{
                        position: "relative", border: "1px solid var(--line-1)",
                        borderRadius: 5, overflow: "hidden", background: "#000",
                        aspectRatio: "3 / 4",
                      }}>
                        <a href={window.withApiToken(url)} target="_blank" rel="noreferrer">
                          <img src={window.withApiToken(url)} style={{
                            width: "100%", height: "100%", objectFit: "cover",
                          }}/>
                        </a>
                        <span className="mono" style={{
                          position: "absolute", top: 4, left: 4, fontSize: 9,
                          background: "rgba(0,0,0,.55)", color: "#fff",
                          padding: "1px 5px", borderRadius: 2,
                        }}>{i + 1}</span>
                        <button
                          title="删除该图"
                          onClick={() => deleteImage(name)}
                          disabled={isBusy}
                          style={{
                            position: "absolute", bottom: 4, right: 4,
                            width: 22, height: 22, padding: 0, borderRadius: 4,
                            border: "1px solid rgba(255,255,255,.25)",
                            background: isBusy ? "rgba(0,0,0,.55)" : "rgba(220, 50, 70, .85)",
                            color: "#fff", fontSize: 13, lineHeight: 1, cursor: "pointer",
                            display: "flex", alignItems: "center", justifyContent: "center",
                          }}>
                          {isBusy ? "…" : "✕"}
                        </button>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <div style={{ padding: 30, color: "var(--fg-3)", fontSize: 11 }}>加载中…</div>
              )}
            </div>
          )}
        </div>
      </div>
    </>
  );
};

Object.assign(window, { ImageLibraryPage });
