// Helm — AI 財務教練。前端聊天畫面 → 後端 chat proxy → Claude(看得到你的財務快照)。
//   教育型、非投資建議。金鑰存後端,不經前端。
(function () {
  const NS = window.HelmDesignSystem_9613a7;
  const { Button } = NS;

  const STARTERS = [
    "我現在財務上最該注意什麼?",
    "我的緊急預備金夠嗎?",
    "解釋一下我的淨值趨勢",
    "以我的狀況,該先還債還是先投資?",
  ];

  // 輕量清掉 markdown 記號,讓 pre-wrap 顯示乾淨
  function clean(t) {
    return String(t || "")
      .replace(/^#{1,6}\s+/gm, "")
      .replace(/\*\*(.+?)\*\*/g, "$1")
      .replace(/^\s*[-*]\s+/gm, "· ");
  }

  function ChatScreen({ onClose }) {
    const [msgs, setMsgs] = React.useState([]);   // {role:"user"|"assistant", content, model?}
    const [input, setInput] = React.useState("");
    const [busy, setBusy] = React.useState(false);
    const [deep, setDeep] = React.useState(false);
    const [err, setErr] = React.useState(null);
    const scrollRef = React.useRef(null);

    React.useEffect(function () {
      if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }, [msgs, busy]);

    function ask(q) {
      q = String(q || "").trim();
      if (!q || busy) return;
      const history = msgs.map(function (m) { return { role: m.role, content: m.content }; });
      setMsgs(function (m) { return m.concat([{ role: "user", content: q }]); });
      setInput(""); setBusy(true); setErr(null);
      window.HelmData.chat(q, history, deep).then(function (res) {
        setBusy(false);
        const d = res && res.data;
        if (res && res.ok && d && d.reply) {
          setMsgs(function (m) { return m.concat([{ role: "assistant", content: d.reply, model: d.model }]); });
        } else if (d && d.error === "no_key") {
          setErr("還沒設定 AI 金鑰——請在 GAS 專案設定的「指令碼屬性」加上 ANTHROPIC_API_KEY,並執行一次 authorizeExternal 授權連外網。");
        } else if (res && res.error === "auth") {
          setErr("登入逾時,請重新進入 App。");
        } else {
          setErr("AI 回應失敗:" + ((d && d.detail) || (res && res.error) || "請稍後再試") + "");
        }
      });
    }

    return (
      <div className="fpage" role="dialog" aria-modal="true" aria-label="AI 財務教練">
        <div className="fpage__panel">
          <header className="fpage__bar">
            <button className="fpage__cancel" onClick={onClose}><i className="ph ph-arrow-left" aria-hidden="true" />返回</button>
            <span className="fpage__title">AI 財務教練</span>
            <span aria-hidden="true" />
          </header>

          <div className="fpage__scroll" ref={scrollRef}>
            <div className="fpage__body chat-body">
              <p className="chat-intro">這位 AI 看得到你在 Helm 的財務全貌(淨值、現金流、保障、目標…),陪你想清楚財務決定。<b>是教練不是投顧——做教育與情境分析,不報明牌、不下投資建議。</b>重要決定仍請找合格專業人士確認。</p>

              {msgs.length === 0 && (
                <div className="chat-starters">
                  {STARTERS.map(function (s, i) {
                    return <button key={i} type="button" className="chat-starter" onClick={function () { ask(s); }}>{s}</button>;
                  })}
                </div>
              )}

              {msgs.map(function (m, i) {
                return (
                  <div key={i} className={"chat-msg chat-msg--" + m.role}>
                    {m.role === "assistant" && <i className="ph ph-sparkle chat-msg__icon" aria-hidden="true" />}
                    <div className="chat-bubble">{m.role === "assistant" ? clean(m.content) : m.content}</div>
                  </div>
                );
              })}

              {busy && <div className="chat-msg chat-msg--assistant"><i className="ph ph-sparkle chat-msg__icon" aria-hidden="true" /><div className="chat-bubble chat-bubble--think">思考中…{deep ? "(深入推理,可能久一點)" : ""}</div></div>}
              {err && <div className="fx-advice fx-advice--mid" style={{ marginTop: 10 }}><span className="fx-advice__txt">⚠️ {err}</span></div>}
            </div>
          </div>

          <div className="chat-inputbar">
            <button type="button" className={"chat-deep" + (deep ? " chat-deep--on" : "")} onClick={function () { setDeep(!deep); }} title="重大決定用更強的模型深入推理">
              <i className={"ph " + (deep ? "ph-brain" : "ph-brain")} aria-hidden="true" />{deep ? "深入" : "一般"}
            </button>
            <textarea className="chat-input" rows={1} placeholder="問我任何財務問題…" value={input}
              onChange={function (e) { setInput(e.target.value); }}
              onKeyDown={function (e) { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(input); } }} />
            <Button variant="primary" onClick={function () { ask(input); }} loading={busy} disabled={!input.trim()}>送出</Button>
          </div>
        </div>
      </div>
    );
  }

  window.ChatScreen = ChatScreen;
})();
