// 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, "· ");
  }

  // 對話紀錄存本機(這台裝置),關掉重開還在;上限 120 則避免無限長
  const LOG_KEY = "helm-chat-log";
  function loadLog() { try { const a = JSON.parse(localStorage.getItem(LOG_KEY) || "[]"); return Array.isArray(a) ? a : []; } catch (e) { return []; } }
  function saveLog(msgs) { try { localStorage.setItem(LOG_KEY, JSON.stringify(msgs.slice(-120))); } catch (e) {} }
  const IS_MAC = /Mac|iPhone|iPad/.test((navigator && navigator.platform) || "");
  const SEND_HINT = (IS_MAC ? "⌘" : "Ctrl") + "+Enter 送出";

  function ChatScreen({ onClose }) {
    const [msgs, setMsgs] = React.useState(loadLog);   // {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 [synced, setSynced] = React.useState(false);   // 是否已跟雲端對過(避免新裝置空畫面閃出 starters)
    const scrollRef = React.useRef(null);

    React.useEffect(function () {
      if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }, [msgs, busy]);
    React.useEffect(function () { saveLog(msgs); }, [msgs]);   // 每次對話變動就存本機快取

    // 打開聊天時才跟雲端拿紀錄(lazy,不在 App 啟動時跑 → 不拖慢開啟)。雲端為準,本機快取先頂著即時顯示。
    React.useEffect(function () {
      if (window.HelmData && window.HelmData.getChat) {
        window.HelmData.getChat().then(function (cloud) {
          if (Array.isArray(cloud)) { setMsgs(cloud); saveLog(cloud); }   // null = 抓失敗 → 保留本機快取
          setSynced(true);
        });
      } else { setSynced(true); }
    }, []);

    function clearLog() {
      if (!msgs.length) return;
      if (window.confirm("清除全部對話紀錄?(雲端與本機都會清除,無法復原)")) {
        setMsgs([]); setErr(null);
        try { localStorage.removeItem(LOG_KEY); } catch (e) {}
        if (window.HelmData && window.HelmData.clearChat) window.HelmData.clearChat();
      }
    }

    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) {
          const aiMsg = { role: "assistant", content: d.reply, model: d.model };
          setMsgs(function (m) { return m.concat([aiMsg]); });
          if (window.HelmData.appendChat) window.HelmData.appendChat([{ role: "user", content: q }, aiMsg]);   // 雲端同步這一輪(背景)
        } 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>
            {msgs.length > 0
              ? <button className="chat-clear" onClick={clearLog} title="清除對話紀錄"><i className="ph ph-trash" aria-hidden="true" />清除</button>
              : <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 && !synced && <p className="chat-intro" style={{ textAlign: "center", opacity: .7 }}>載入對話紀錄中…</p>}
              {msgs.length === 0 && synced && (
                <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={"問我任何財務問題…(" + SEND_HINT + ")"} value={input}
              onChange={function (e) { setInput(e.target.value); }}
              onKeyDown={function (e) { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { e.preventDefault(); ask(input); } }} />
            <Button variant="primary" onClick={function () { ask(input); }} loading={busy} disabled={!input.trim()}>送出</Button>
          </div>
        </div>
      </div>
    );
  }

  window.ChatScreen = ChatScreen;
})();
