window.FB = window.FB || {};

// 「资料」页 — Claude 要的资料在这里问, 她在这里填 (2026-08-02)
// 以前每次要资料就重做一个 HTML 页发链接给她, 链接会散在聊天记录里找不回。
// 现在问题住 data_requests: 加新题 = INSERT 一行, 前端不用动。
//
// 存法: 每题一行 answer jsonb。逐题提交 (不是整份提交) —— 她常常只答得出其中一两项,
// 一题一存才不会因为别题没填而卡住, 也不怕填一半关掉。
FB.AskTab = function AskTab({ lang, user }) {
  const { useState, useEffect } = React;
  const t = FB.makeT(lang);
  const L = (zh, en) => (lang === "zh" ? zh : en);

  const [rows, setRows] = useState(null);
  const [draft, setDraft] = useState({});     // {id: {key: val}} 本地未提交的改动
  const [busy, setBusy] = useState({});       // {id: true}
  const [okId, setOkId] = useState(null);
  const [showDone, setShowDone] = useState(false);

  function load() { FB.api.dataRequests().then(setRows); }
  useEffect(() => { load(); }, []);

  // 当前值 = 本地草稿优先, 否则库里存的
  const valOf = (r, k) => {
    const d = draft[r.id] || {};
    if (k in d) return d[k];
    return (r.answer || {})[k] ?? "";
  };
  const dirty = (r) => {
    const d = draft[r.id] || {};
    return Object.keys(d).some((k) => String(d[k]) !== String((r.answer || {})[k] ?? ""));
  };
  const answered = (r) => Object.keys(r.answer || {}).length > 0;

  function edit(id, k, v) {
    setDraft((s) => ({ ...s, [id]: { ...(s[id] || {}), [k]: v } }));
  }

  async function submit(r) {
    const d = draft[r.id];
    if (!d || busy[r.id]) return;
    setBusy((b) => ({ ...b, [r.id]: true }));
    const res = await FB.api.submitAnswer({ id: r.id, answer: d, by: user.name });
    setBusy((b) => ({ ...b, [r.id]: false }));
    if (!res || res.error || !res.ok) return;
    setDraft((s) => { const n = { ...s }; delete n[r.id]; return n; });
    setRows((rs) => rs.map((x) => (x.id === r.id ? { ...x, ...res.row } : x)));
    setOkId(r.id);
    setTimeout(() => setOkId((v) => (v === r.id ? null : v)), 1600);
  }

  const open = (rows || []).filter((r) => r.status !== "done");
  const done = (rows || []).filter((r) => r.status === "done");
  const answeredN = open.filter(answered).length;

  useEffect(() => {
    if (rows && FB.setPageInfo)
      FB.setPageInfo({ text: L("已答 ", "Answered ") + answeredN + " / " + open.length, num: answeredN, den: open.length });
  }, [rows, answeredN, open.length, lang]);

  // 分组 (sort_order 已排好, 同 section 连在一起)
  const groups = [];
  open.forEach((r) => {
    let g = groups.find((x) => x.s === r.section);
    if (!g) { g = { s: r.section, note: r.section_note, items: [] }; groups.push(g); }
    g.items.push(r);
  });

  const COL = { s1: "#A81E12", s3: "#A07A06", s4: "#4A7A1C", plain: "#A8A29E" };
  const BG = { s1: "#FCEDEA", s3: "#FBF6E4", s4: "#F1F6EC", plain: "#F5F5F4" };

  if (!rows) return <div className="px-3 py-3 max-w-md mx-auto"><p className="text-sm text-stone-400">{t("loading")}</p></div>;

  return (
    <div className="px-3 py-3 max-w-md mx-auto pb-28">
      <h1 className="text-[20px] font-semibold text-stone-900 px-1">{L("资料", "Data requests")}</h1>
      <p className="text-[12px] text-stone-400 px-1 mt-0.5 mb-4">
        {L("Claude 要的资料。填多少算多少,一题一题存 —— 不用一次填完。",
           "What Claude needs. Answer any subset; each saves on its own.")}
      </p>

      {open.length === 0 && (
        <div className="rounded-2xl border border-stone-200 bg-white p-6 text-center text-sm text-stone-500">
          ✓ {L("没有待填的资料", "Nothing pending")}
        </div>
      )}

      {groups.map((g) => (
        <div key={g.s} className="mb-5">
          <div className="flex items-baseline gap-2 px-1 mb-1">
            <h2 className="text-[14px] font-semibold text-stone-800">{g.s}</h2>
            <span className="ml-auto text-[11px] text-stone-400 tabular-nums">
              {g.items.filter(answered).length} / {g.items.length}
            </span>
          </div>
          {g.note && <p className="text-[11.5px] text-stone-500 px-1 mb-2 leading-relaxed">{g.note}</p>}

          {g.items.map((r) => {
            const sev = r.severity || "s3";
            const isOk = okId === r.id;
            return (
              <div key={r.id} className="rounded-xl border border-stone-200 bg-white p-3 mb-2"
                style={{ borderLeft: "3px solid " + (answered(r) ? COL.s4 : COL[sev]) }}>
                <div className="flex items-start gap-2">
                  <p className="text-[14.5px] font-semibold text-stone-900 leading-snug flex-1">{r.title}</p>
                  {answered(r) && !dirty(r) && <span className="text-[15px] shrink-0" style={{ color: COL.s4 }}>✓</span>}
                </div>

                {r.note && r.note.split("\n").map((line, i) => (
                  <p key={i} className="text-[12px] text-stone-500 mt-1 leading-relaxed">{line}</p>
                ))}

                {r.flag && (
                  <span className="inline-block mt-2 text-[11px] font-semibold px-2 py-1 rounded-md"
                    style={{ background: BG[sev], color: COL[sev] }}>{r.flag}</span>
                )}

                {/* 输入框 */}
                {(r.fields || []).length > 0 && (
                  <div className="flex flex-wrap gap-2 mt-2.5">
                    {(r.fields || []).map((f) => (
                      <label key={f.key}
                        className="flex flex-col gap-1"
                        style={{ flex: f.type === "textarea" ? "1 1 100%" : "1 1 130px" }}>
                        <span className="text-[10.5px] text-stone-400">{f.label}</span>
                        {f.type === "textarea" ? (
                          <textarea value={valOf(r, f.key)} rows={3}
                            onChange={(e) => edit(r.id, f.key, e.target.value)}
                            className="w-full px-2.5 py-2 rounded-xl border border-stone-200 text-[15px] leading-snug" />
                        ) : (
                          <input type={f.type === "number" ? "number" : "text"}
                            inputMode={f.type === "number" ? "decimal" : "text"}
                            value={valOf(r, f.key)}
                            onChange={(e) => edit(r.id, f.key, e.target.value)}
                            className="w-full h-11 px-2.5 rounded-xl border border-stone-200 text-[16px] tabular-nums" />
                        )}
                      </label>
                    ))}
                  </div>
                )}

                {/* 单选药丸 */}
                {(r.options || []).length > 0 && (
                  <div className="flex flex-wrap gap-1.5 mt-2.5">
                    {(r.options || []).map((op) => {
                      const k = r.option_key || "选择";
                      const on = String(valOf(r, k)) === op;
                      return (
                        <button key={op} onClick={() => edit(r.id, k, on ? "" : op)}
                          className="text-[13px] px-3.5 h-9 rounded-full border active:scale-95 transition-colors"
                          style={on
                            ? { background: "#B91C1C", borderColor: "#B91C1C", color: "#fff", fontWeight: 600 }
                            : { borderColor: "#E7E5E4", color: "#57534E" }}>
                          {op}
                        </button>
                      );
                    })}
                  </div>
                )}

                {/* 存 —— 有改动才出现, 免得一堆灰按钮 */}
                {(dirty(r) || isOk) && (
                  <button onClick={() => submit(r)} disabled={busy[r.id] || isOk}
                    className="w-full h-11 mt-2.5 rounded-xl text-white text-[14px] font-semibold active:scale-[0.98]"
                    style={{ background: isOk ? COL.s4 : "#B91C1C" }}>
                    {isOk ? "✓ " + L("存好了", "Saved") : busy[r.id] ? "…" : L("存这题", "Save")}
                  </button>
                )}

                {answered(r) && r.answered_by && !dirty(r) && (
                  <p className="text-[10.5px] text-stone-400 mt-2">
                    {r.answered_by} · {String(r.answered_at || "").slice(0, 10)}
                  </p>
                )}
              </div>
            );
          })}
        </div>
      ))}

      {/* 处理完的收起来 */}
      {done.length > 0 && (
        <div className="rounded-xl border border-stone-200 bg-white overflow-hidden mt-4">
          <button onClick={() => setShowDone((v) => !v)}
            className="w-full flex items-center gap-2 px-3 py-2.5 text-[12.5px] text-stone-600">
            <FB.UI.Chev open={showDone} />
            <span className="font-semibold">{L("Claude 已处理", "Handled")} {done.length}</span>
          </button>
          {showDone && (
            <div className="divide-y divide-stone-50 border-t border-stone-100">
              {done.map((r) => (
                <div key={r.id} className="px-3 py-2.5">
                  <p className="text-[13px] text-stone-600">{r.title}</p>
                  <p className="text-[11px] text-stone-400 mt-0.5">
                    {Object.entries(r.answer || {}).map(([k, v]) => k + ": " + v).join(" · ")}
                  </p>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};
