// Helm — 目標(存錢目標:進度 + 預計達成年月)。後端已算 pct/remaining/monthsLeft。
(function () {
  const NS = window.HelmDesignSystem_9613a7;
  const { Card, Button, Input } = NS;

  function fmt(n) { return Math.round(n || 0).toLocaleString("en-US"); }
  function num(v) { return parseFloat(String(v).replace(/,/g, "")) || 0; }
  function monthsToYM(m) {
    const d = new Date(); const t = d.getFullYear() * 12 + d.getMonth() + (m || 0);
    return Math.floor(t / 12) + "/" + ("0" + (t % 12 + 1)).slice(-2);
  }

  function Goal({ g, onEdit }) {
    const done = g.pct >= 100 || g.monthsLeft === 0;
    return (
      <Card className="goal">
        <button type="button" className="goal__head" onClick={() => onEdit(g)}>
          <span className="goal__name">{g.name || "(未命名目標)"}</span>
          <span className="goal__pct t-num">{g.pct}%</span>
        </button>
        <div className="goal__bar">
          <div className={"goal__fill" + (done ? " goal__fill--done" : "")} style={{ width: Math.min(100, g.pct) + "%" }} />
        </div>
        <div className="goal__nums">
          <span className="t-num">NT$ {fmt(g.saved)} <span className="goal__of">/ {fmt(g.target)}</span></span>
          {done
            ? <span className="goal__eta goal__eta--done">🎉 已達成</span>
            : g.monthsLeft != null
              ? <span className="goal__eta">還差 NT$ {fmt(g.remaining)} · 預計 <b>{monthsToYM(g.monthsLeft)}</b>（{g.monthsLeft} 個月)</span>
              : <span className="goal__eta goal__eta--muted">還差 NT$ {fmt(g.remaining)} · 設「每月存入」才能估達成時間</span>}
        </div>
      </Card>
    );
  }

  function Goals({ onChanged }) {
    const H = window.HELM;
    const goals = H && H.goals;
    const free = (H && H.cashflow && H.cashflow.freeBalance) || 0;
    const [form, setForm] = React.useState(null);   // {mode,_row,name,target,saved,monthly}
    const [busy, setBusy] = React.useState(false);

    if (!goals) {
      return (
        <div className="screen"><Card><div className="cf-notice">
          <b>目標需要更新後端</b><br />重新部署後端(version 10)後重開即可。
        </div></Card></div>
      );
    }

    const openAdd = () => setForm({ mode: "add", _row: null, name: "", target: "", saved: "", monthly: free > 0 ? String(Math.round(free)) : "" });
    const openEdit = (g) => setForm({ mode: "edit", _row: g._row, name: g.name, target: String(g.target || ""), saved: String(g.saved || ""), monthly: String(g.monthly || "") });
    const fld = (k, v) => setForm((f) => Object.assign({}, f, { [k]: v }));
    const cancel = () => setForm(null);

    function save() {
      if (!form.name.trim() || !(num(form.target) > 0)) return;
      setBusy(true);
      const fields = { name: form.name.trim(), target: num(form.target), saved: num(form.saved), monthly: num(form.monthly) };
      const req = form.mode === "edit"
        ? window.HelmData.updateGoal(Object.assign({ _row: form._row }, fields))
        : window.HelmData.addGoal(fields);
      req.then(() => { setBusy(false); setForm(null); onChanged && onChanged(); });
    }
    function del() {
      setBusy(true);
      window.HelmData.deleteGoal(form._row).then(() => { setBusy(false); setForm(null); onChanged && onChanged(); });
    }

    return (
      <div className="screen">
        <span className="t-overline goal-intro">存錢目標</span>

        {goals.length === 0 && !form ? (
          <Card><div className="cf-notice">
            還沒有目標,設一個吧——例如<b>緊急預備金</b>(建議存到 3~6 個月生活費)、房子裝修頭期、或為「提前還車貸」先存一筆。
          </div></Card>
        ) : null}

        {goals.map((g) => <Goal key={g.id} g={g} onEdit={openEdit} />)}

        {form ? (
          <Card className="cf-sec">
            <div className="cf-sec__head"><span className="t-overline">{form.mode === "edit" ? "編輯目標" : "新增目標"}</span></div>
            <div className="goal-form">
              <Input placeholder="目標名稱(例:緊急預備金)" value={form.name} onChange={(e) => fld("name", e.target.value)} />
              <Input amount affix="NT$" inputMode="decimal" placeholder="目標金額" value={form.target} onChange={(e) => fld("target", e.target.value)} />
              <Input amount affix="NT$" inputMode="decimal" placeholder="目前已存" value={form.saved} onChange={(e) => fld("saved", e.target.value)} />
              <Input amount affix="NT$" inputMode="decimal" placeholder="每月存入" value={form.monthly} onChange={(e) => fld("monthly", e.target.value)} />
              {free > 0 ? <div className="goal__hint">參考:你每月「自由結餘」約 NT$ {fmt(free)},可當每月存入的上限</div> : null}
              <div className="cf-editor__btns">
                {form.mode === "edit"
                  ? <Button variant="danger" onClick={del} loading={busy}>刪除</Button>
                  : <span className="cf-editor__spacer" />}
                <div className="cf-editor__right">
                  <Button variant="secondary" onClick={cancel} disabled={busy}>取消</Button>
                  <Button variant="primary" onClick={save} loading={busy}>儲存</Button>
                </div>
              </div>
            </div>
          </Card>
        ) : (
          <button type="button" className="cf-add" onClick={openAdd}>
            <i className="ph ph-plus" aria-hidden="true" />新增目標
          </button>
        )}
      </div>
    );
  }

  window.Goals = Goals;
})();
