// 模板库 — 拆解 / 复刻模板的 CRUD（原 AIDS 拆解库已拆分：规则库 → rule-pack.jsx）

const _CATEGORY_TABS = [
  { id: "teardown",  label: "拆解模板", desc: "用于「2·拆解爆款」analyze stage 的系统提示" },
  { id: "replicate", label: "复刻模板", desc: "用于「3·复刻爆款」chunk_regroup 复刻草稿生成" },
];

const TemplatesPage = () => {
  const [tab, setTab] = React.useState("teardown");
  const [tpls, setTpls] = React.useState([]);
  const [selTplId, setSelTplId] = React.useState(null);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr] = React.useState("");
  const [saveBusy, setSaveBusy] = React.useState(false);

  const [editName, setEditName] = React.useState("");
  const [editDesc, setEditDesc] = React.useState("");
  const [editBody, setEditBody] = React.useState("");

  React.useEffect(() => { loadTemplates(); }, [tab]);

  const loadTemplates = async () => {
    setLoading(true); setErr("");
    try {
      const d = await API.templates.list({ category: tab });
      const items = d.items || [];
      setTpls(items);
      // 切 tab 时如果当前选中模板不在新分类里，重选
      const stillThere = items.some(t => t.id === selTplId);
      if (!stillThere) {
        const firstNonDefault = items.find(t => !t.is_default) || items[0];
        setSelTplId(firstNonDefault ? firstNonDefault.id : null);
      }
    } catch (e) { setErr(String(e.message || e)); }
    finally { setLoading(false); }
  };

  const selTpl = tpls.find(t => t.id === selTplId);
  React.useEffect(() => {
    if (selTpl) {
      setEditName(selTpl.name || "");
      setEditDesc(selTpl.description || "");
      setEditBody(selTpl.prompt_body || "");
    }
  }, [selTplId, selTpl?.updated_at]);

  const onSaveTpl = async () => {
    if (!selTpl || selTpl.is_default) return;
    setSaveBusy(true);
    try {
      await API.templates.update(selTpl.id, {
        name: editName.trim(),
        description: editDesc,
        prompt_body: editBody,
      });
      await loadTemplates();
    } catch (e) { setErr(String(e.message || e)); }
    finally { setSaveBusy(false); }
  };

  const onDuplicateTpl = async () => {
    if (!selTpl) return;
    setSaveBusy(true);
    try {
      const dup = await API.templates.duplicate(selTpl.id);
      await loadTemplates();
      setSelTplId(dup.id);
    } catch (e) { setErr(String(e.message || e)); }
    finally { setSaveBusy(false); }
  };

  const onDeleteTpl = async () => {
    if (!selTpl || selTpl.is_default) return;
    if (!confirm(`删除模板「${selTpl.name}」？`)) return;
    setSaveBusy(true);
    try {
      await API.templates.delete(selTpl.id);
      setSelTplId(null);
      await loadTemplates();
    } catch (e) { setErr(String(e.message || e)); }
    finally { setSaveBusy(false); }
  };

  const onNewTpl = async () => {
    const src = tpls.find(t => t.is_default) || tpls[0];
    const now = new Date();
    const ts = `${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")} ${String(now.getHours()).padStart(2,"0")}:${String(now.getMinutes()).padStart(2,"0")}`;
    setSaveBusy(true);
    try {
      const t = await API.templates.create({
        name: `新模板 ${ts}`,
        description: "",
        category: tab,
        prompt_body: (src && src.prompt_body) || `# 在这里写你的${tab === "replicate" ? "复刻" : "拆解"}模板正文\n`,
      });
      await loadTemplates();
      setSelTplId(t.id);
    } catch (e) { setErr(String(e.message || e)); }
    finally { setSaveBusy(false); }
  };

  return (
    <>
      <Topbar
        crumbs={["资产", "模板库"]}
        right={
          <button className="btn primary" onClick={onNewTpl} disabled={saveBusy}>
            <Icon name="plus" size={11}/>新建模板
          </button>
        }
      />

      {err && (
        <div style={{margin:"10px 16px 0", padding:"10px 12px", background:"var(--pink-soft)", border:"1px solid var(--pink)", borderRadius:5, fontSize:11, color:"var(--pink)"}}>
          {err}
        </div>
      )}

      {/* 分类切换 Tab：拆解 / 复刻 */}
      <div className="row" style={{padding:"8px 16px 0", gap:6, borderBottom:"1px solid var(--line-soft)"}}>
        {_CATEGORY_TABS.map(t => (
          <button
            key={t.id}
            className="btn sm"
            onClick={() => setTab(t.id)}
            style={{
              padding:"6px 14px",
              borderRadius:"4px 4px 0 0",
              borderBottom: tab === t.id ? "2px solid var(--cyan)" : "2px solid transparent",
              background: tab === t.id ? "var(--cyan-soft)" : "transparent",
              color: tab === t.id ? "var(--cyan)" : "var(--fg-2)",
              fontWeight: tab === t.id ? 600 : 400,
            }}
            title={t.desc}
          >
            {t.label}
          </button>
        ))}
        <div className="grow"/>
        <span className="card-sub" style={{padding:"8px 4px"}}>
          {(_CATEGORY_TABS.find(t => t.id === tab) || {}).desc || ""}
        </span>
      </div>

      <div className="main-body">
        {/* 左：模板列表 */}
        <div className="col scroll" style={{width:280, flexShrink:0, padding:"12px 10px", gap:6, borderRight:"1px solid var(--line-soft)", background:"var(--bg-0)"}}>
          <div className="row between" style={{padding:"0 4px 6px"}}>
            <span className="kpi-l">{tab === "replicate" ? "复刻模板" : "拆解模板"}</span>
            <span className="mono" style={{fontSize:10, color:"var(--fg-3)"}}>{tpls.length} 条</span>
          </div>
          {loading && !tpls.length && <div style={{fontSize:11, color:"var(--fg-3)", padding:20, textAlign:"center"}}>加载中…</div>}
          {tpls.map(t => (
            <div key={t.id} onClick={() => setSelTplId(t.id)} className="row gap-8" style={{
              padding:8, borderRadius:5, cursor:"pointer", alignItems:"flex-start",
              background: t.id===selTplId ? "color-mix(in oklch, var(--cyan) 10%, var(--bg-1))" : "var(--bg-1)",
              border: `1px solid ${t.id===selTplId ? "var(--cyan)" : "var(--line-1)"}`,
            }}>
              <div className="col grow gap-2" style={{minWidth:0}}>
                <div className="row gap-6" style={{alignItems:"center"}}>
                  <span style={{fontSize:11.5, fontWeight:600, color:"var(--fg-0)"}}>{t.name}</span>
                  {t.is_default && <span className="tag cyan" style={{fontSize:9}}>默认</span>}
                </div>
                <span className="mono" style={{fontSize:9.5, color:"var(--fg-3)"}}>v{t.version} · {t.updated_at ? t.updated_at.slice(0,16).replace("T"," ") : ""}</span>
              </div>
            </div>
          ))}
          {!loading && !tpls.length && <div style={{fontSize:11, color:"var(--fg-3)", padding:20, textAlign:"center"}}>暂无模板</div>}
        </div>

        {/* 右：模板编辑器 */}
        <div className="col scroll grow" style={{padding:"12px 14px 20px", gap:12, background:"var(--bg-0)", minWidth:0}}>
          {selTpl && (
            <div className="card" style={{overflow:"hidden"}}>
              <div className="card-hd">
                <span className="card-title">{selTpl.is_default ? "默认模板（只读）" : "编辑模板"}</span>
                <span className="card-sub">v{selTpl.version}</span>
                <div className="grow"/>
                <button className="btn sm" onClick={onDuplicateTpl} disabled={saveBusy}>
                  <Icon name="copy" size={10}/>复制
                </button>
                {!selTpl.is_default && (
                  <>
                    <button className="btn sm primary" onClick={onSaveTpl} disabled={saveBusy}>
                      <Icon name="check" size={10}/>{saveBusy ? "保存中" : "保存"}
                    </button>
                    <button className="btn sm" onClick={onDeleteTpl} disabled={saveBusy} style={{color:"var(--pink)"}}>
                      <Icon name="close" size={10}/>删除
                    </button>
                  </>
                )}
              </div>
              <div className="col" style={{padding:12, gap:10}}>
                <div className="col gap-4">
                  <span className="kpi-l">名称</span>
                  <input
                    className="input"
                    value={editName}
                    onChange={e => setEditName(e.target.value)}
                    disabled={selTpl.is_default}
                    style={{fontSize:12.5}}
                  />
                </div>
                <div className="col gap-4">
                  <span className="kpi-l">描述</span>
                  <input
                    className="input"
                    value={editDesc}
                    onChange={e => setEditDesc(e.target.value)}
                    disabled={selTpl.is_default}
                    style={{fontSize:12.5}}
                  />
                </div>
                <div className="col gap-4" style={{flex:1, minHeight:0}}>
                  <span className="kpi-l">Prompt 正文</span>
                  <textarea
                    className="textarea"
                    value={editBody}
                    onChange={e => setEditBody(e.target.value)}
                    disabled={selTpl.is_default}
                    style={{fontSize:12, lineHeight:1.6, minHeight:360, fontFamily:"var(--font-mono)"}}
                  />
                </div>
              </div>
            </div>
          )}

          {!selTpl && (
            <div className="card col center" style={{padding:"40px 20px", gap:10, textAlign:"center"}}>
              <Icon name="folder" size={24} style={{color:"var(--fg-3)"}} />
              <div style={{fontSize:13, color:"var(--fg-1)", fontWeight:500}}>请在左侧选择一个模板</div>
              <div style={{fontSize:11, color:"var(--fg-3)", lineHeight:1.5}}>或点击右上角「新建模板」从默认模板复制一份开始编辑</div>
            </div>
          )}
        </div>
      </div>
    </>
  );
};

Object.assign(window, { TemplatesPage });
