// ———— 全局反馈组件 ————
// 右下角浮动按钮 + 弹窗。提交后后端聚合前后端日志生成 GitHub Issue。
// 仅在已登录布局中挂载（见 app.jsx）。
function FeedbackWidget() {
  const { useState } = React;
  const [open, setOpen] = useState(false);
  const [desc, setDesc] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);   // { issue_url, issue_number }
  const [error, setError] = useState("");

  const reset = () => { setDesc(""); setResult(null); setError(""); setLoading(false); };
  const close = () => { setOpen(false); reset(); };

  const submit = async () => {
    if (!desc.trim()) { setError("请先描述你遇到的问题"); return; }
    setLoading(true); setError("");
    try {
      const r = await window.API.submitFeedback(desc.trim());
      setResult(r);
    } catch (err) {
      setError(err.message || "提交失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* 浮动按钮 */}
      <button
        onClick={() => setOpen(true)}
        title="反馈问题"
        style={{
          position: "fixed", right: 24, bottom: 24, zIndex: 9990,
          height: 44, padding: "0 18px", borderRadius: 22, border: "none",
          background: "var(--brand, oklch(0.52 0.16 258))", color: "#fff",
          fontSize: 13, fontWeight: 600, cursor: "pointer",
          boxShadow: "0 4px 16px rgba(0,0,0,.22)", display: "flex",
          alignItems: "center", gap: 7,
        }}>
        <Icon.Info size={15} /> 反馈
      </button>

      {!open ? null : (
        <div
          onClick={(e) => { if (e.target === e.currentTarget) close(); }}
          style={{
            position: "fixed", inset: 0, zIndex: 1000,
            background: "rgba(15,20,35,.45)", display: "flex", zIndex: 9999,
            alignItems: "center", justifyContent: "center",
          }}>
          <div style={{
            width: 520, maxWidth: "92vw", background: "var(--surface, #fff)",
            borderRadius: 12, boxShadow: "0 12px 48px rgba(0,0,0,.3)",
            overflow: "hidden", fontSize: 13,
          }}>
            {/* 头 */}
            <div style={{
              display: "flex", alignItems: "center", justifyContent: "space-between",
              padding: "14px 18px", borderBottom: "1px solid var(--border, #e5e7eb)",
            }}>
              <strong style={{ fontSize: 14 }}>反馈问题</strong>
              <button onClick={close} className="btn ghost sm" style={{ padding: 4 }}>
                <Icon.Close size={14} />
              </button>
            </div>

            {/* 体 */}
            <div style={{ padding: 18 }}>
              {result ? (
                <div style={{ textAlign: "center", padding: "12px 0" }}>
                  <div style={{ color: "var(--ok, #16a34a)", marginBottom: 10 }}>
                    <Icon.Check size={28} />
                  </div>
                  <div style={{ fontWeight: 600, marginBottom: 6 }}>反馈已提交，感谢！</div>
                  {result.issue_url && (
                    <a href={result.issue_url} target="_blank" rel="noreferrer"
                       style={{ color: "var(--brand, #4f46e5)", display: "inline-flex", alignItems: "center", gap: 5 }}>
                      查看 Issue #{result.issue_number} <Icon.External size={12} />
                    </a>
                  )}
                  <div style={{ marginTop: 16 }}>
                    <button className="btn primary" onClick={close}>完成</button>
                  </div>
                </div>
              ) : (
                <>
                  <div style={{ color: "var(--ink-3, #6b7280)", marginBottom: 10, lineHeight: 1.6 }}>
                    描述你遇到的问题，提交后会自动附上最近的前端操作日志和服务端日志，
                    生成一个 GitHub Issue。
                    <br />
                    <span style={{ fontSize: 11.5 }}>（已自动脱敏，不会上传你的 API Key）</span>
                  </div>

                  {error && (
                    <div style={{
                      marginBottom: 10, padding: "8px 12px", borderRadius: 6, fontSize: 12,
                      background: "var(--danger-bg, #fff0f0)", border: "1px solid var(--danger, #dc2626)",
                      color: "var(--danger, #dc2626)",
                    }}>{error}</div>
                  )}

                  <textarea
                    className="input"
                    value={desc}
                    onChange={(e) => setDesc(e.target.value)}
                    placeholder="例如：搜索页点击提交后一直转圈，没有结果返回……"
                    rows={5}
                    style={{ width: "100%", resize: "vertical", fontFamily: "inherit" }}
                    autoFocus
                  />

                  <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 14 }}>
                    <button className="btn ghost" onClick={close} disabled={loading}>取消</button>
                    <button className="btn primary" onClick={submit} disabled={loading}>
                      {loading && <Icon.Spinner />}
                      {loading ? "提交中..." : "提交反馈"}
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}
window.FeedbackWidget = FeedbackWidget;
