// Helm — 現金流(收入 / 支出 / 投入 三段)。
// 觀念:支出=花掉就沒了;投入=把錢搬成資產(淨值沒減)。貸款月付由後端自動帶入支出。
(function () {
  const NS = window.HelmDesignSystem_9613a7;
  const { Card, AmountDisplay, 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 shortDate(s) { const m = String(s || "").match(/(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})/); return m ? (Number(m[2]) + "/" + Number(m[3])) : ""; }
  const PH = { "收入": "例:薪水", "支出": "例:信用卡帳單 / 孝親費", "投入": "例:定期定額 0050" };
  const SIGN = { "收入": "+", "支出": "−", "投入": "→" };
  const TONE = { "收入": "pos", "支出": "neg", "投入": "inv" };

  function Section(p) {
    const active = p.form && p.form.kind === p.kind;
    return (
      <Card className="cf-sec">
        <div className="cf-sec__head">
          <span className="t-overline">{p.title}</span>
          <span className={"cf-sec__sum t-num cf-amt--" + TONE[p.kind]}>{SIGN[p.kind]} {fmt(p.subtotal)}</span>
        </div>
        {p.hint ? <div className="cf-sec__hint">{p.hint}</div> : null}
        <div className="cf-list">
          {(p.autoRows || []).map((r) => (
            <div key={r.id} className="cf-row cf-row--static">
              <span className="cf-row__l">
                <span className="cf-row__name">{r.name}<span className="cf-row__auto">自動</span></span>
                {r.monthsLeft != null ? <span className="cf-row__sub">還 {r.monthsLeft} 期 · {monthsToYM(r.monthsLeft)} 還清</span> : null}
              </span>
              <span className="cf-row__amt t-num cf-amt--neg">− {fmt(r.monthly)}</span>
            </div>
          ))}
          {p.rows.map((r) => (
            <button key={r.id} type="button" className="cf-row" onClick={() => p.onEdit(r)}>
              <span className="cf-row__l">
                <span className="cf-row__name">{r.name || "(未命名)"}</span>
                {(r.note || r.updatedAt)
                  ? <span className="cf-row__sub">{[r.note, r.updatedAt ? "更新 " + shortDate(r.updatedAt) : null].filter(Boolean).join(" · ")}</span>
                  : null}
              </span>
              <span className={"cf-row__amt t-num cf-amt--" + TONE[p.kind]}>{SIGN[p.kind]} {fmt(r.monthly)}</span>
            </button>
          ))}
          {p.rows.length === 0 && (!p.autoRows || p.autoRows.length === 0) && !active ? <div className="cf-empty">尚無項目</div> : null}
        </div>
        {active ? (
          <div className="cf-editor">
            <Input placeholder={PH[p.kind]} value={p.form.name} onChange={(e) => p.onField("name", e.target.value)} />
            <Input amount affix="NT$" inputMode="decimal" placeholder="每月金額" value={p.form.monthly}
              onChange={(e) => p.onField("monthly", e.target.value)} />
            <div className="cf-editor__btns">
              {p.form.mode === "edit"
                ? <Button variant="danger" onClick={p.onDelete} loading={p.busy}>刪除</Button>
                : <span className="cf-editor__spacer" />}
              <div className="cf-editor__right">
                <Button variant="secondary" onClick={p.onCancel} disabled={p.busy}>取消</Button>
                <Button variant="primary" onClick={p.onSave} loading={p.busy}>儲存</Button>
              </div>
            </div>
          </div>
        ) : (
          <button type="button" className="cf-add" onClick={() => p.onAdd(p.kind)}>
            <i className="ph ph-plus" aria-hidden="true" />新增{p.title}
          </button>
        )}
      </Card>
    );
  }

  function Cashflow({ onChanged }) {
    const H = window.HELM;
    const cf = H && H.cashflow;
    const monthly = (H && H.monthly) || [];
    const [form, setForm] = React.useState(null);   // {mode,kind,_row,name,monthly}
    const [busy, setBusy] = React.useState(false);
    const [mForm, setMForm] = React.useState(null); // 月結封存 {ym,daili,note}
    const [mBusy, setMBusy] = React.useState(false);

    if (!cf) {
      return (
        <div className="screen">
          <Card><div className="cf-notice">
            <b>現金流需要更新後端</b><br />
            重新部署後端到 version 8 後,重開 App 就會出現囉。
          </div></Card>
        </div>
      );
    }

    const onAdd = (kind) => setForm({ mode: "add", kind: kind, _row: null, name: "", monthly: "" });
    const onEdit = (kind, r) => setForm({ mode: "edit", kind: kind, _row: r._row, name: r.name, monthly: String(r.monthly || "") });
    const onField = (k, v) => setForm((f) => Object.assign({}, f, { [k]: v }));
    const cancel = () => setForm(null);

    function save() {
      if (!form.name.trim() || !(num(form.monthly) > 0)) return;
      setBusy(true);
      const fields = { kind: form.kind, name: form.name.trim(), monthly: num(form.monthly) };
      const req = form.mode === "edit"
        ? window.HelmData.updateCf(Object.assign({ _row: form._row }, fields))
        : window.HelmData.addCf(fields);
      req.then(() => { setBusy(false); setForm(null); onChanged && onChanged(); });
    }
    function del() {
      setBusy(true);
      window.HelmData.deleteCf(form._row).then(() => { setBusy(false); setForm(null); onChanged && onChanged(); });
    }
    function curYM() { const d = new Date(); return d.getFullYear() + "-" + ("0" + (d.getMonth() + 1)).slice(-2); }
    function closeThisMonth() {
      setMBusy(true);
      window.HelmData.closeMonth({ ym: mForm.ym, daili: num(mForm.daili), note: mForm.note })
        .then(() => { setMBusy(false); setMForm(null); onChanged && onChanged(); });
    }

    const sp = cf.savingPower, fb = cf.freeBalance;
    const loansBySoon = (cf.loans || []).slice().sort((a, b) => (a.monthsLeft || 0) - (b.monthsLeft || 0));

    return (
      <div className="screen">
        <Card variant="lg" className="cf-hero">
          <div className="t-overline">每月現金流</div>
          <div className="cf-hero__rows">
            <div className="cf-hero__row"><span>收入</span><span className="t-num cf-amt--pos">+ {fmt(cf.incomeSum)}</span></div>
            <div className="cf-hero__row"><span>支出</span><span className="t-num cf-amt--neg">− {fmt(cf.expenseSum)}</span></div>
            <div className="cf-hero__line" />
            <div className="cf-hero__row cf-hero__row--big">
              <span>儲蓄力</span>
              <span className={"t-num " + (sp >= 0 ? "cf-amt--pos" : "cf-amt--neg")}>{sp >= 0 ? "+" : "−"} {fmt(Math.abs(sp))}</span>
            </div>
            <div className="cf-hero__row"><span>定期投入</span><span className="t-num cf-amt--inv">→ {fmt(cf.investSum)}</span></div>
            <div className="cf-hero__line" />
            <div className="cf-hero__row cf-hero__row--big">
              <span>自由結餘</span>
              <span className={"t-num " + (fb >= 0 ? "cf-amt--pos" : "cf-amt--neg")}>{fb >= 0 ? "+" : "−"} {fmt(Math.abs(fb))}</span>
            </div>
          </div>
          <div className="cf-hero__note">
            {fb < 0
              ? "⚠ 自由結餘是負的:你每月定期投入的比「存得下的」還多,差額得從既有現金或額度補。可考慮調低定期投入,或這是有意識的積極投資。"
              : "投入後每月還有這些錢可自由運用 👍"}
          </div>
        </Card>

        <Section title="收入" kind="收入" rows={cf.income} subtotal={cf.incomeSum}
          form={form} busy={busy} onAdd={onAdd} onEdit={(r) => onEdit("收入", r)}
          onField={onField} onSave={save} onDelete={del} onCancel={cancel} />

        <Section title="支出" kind="支出" rows={cf.expense} autoRows={cf.loans} subtotal={cf.expenseSum}
          hint="貸款月付已自動帶入(標「自動」),不用重複新增。其他固定開銷、孝親費、信用卡帳單填這裡。"
          form={form} busy={busy} onAdd={onAdd} onEdit={(r) => onEdit("支出", r)}
          onField={onField} onSave={save} onDelete={del} onCancel={cancel} />

        <Section title="投入" kind="投入" rows={cf.invest} subtotal={cf.investSum}
          hint="定期定額 ETF、定期換美金…這是把錢變成資產、不是花掉,所以單獨算。"
          form={form} busy={busy} onAdd={onAdd} onEdit={(r) => onEdit("投入", r)}
          onField={onField} onSave={save} onDelete={del} onCancel={cancel} />

        {loansBySoon.length > 0 && (
          <Card className="cf-sec">
            <div className="cf-sec__head"><span className="t-overline">還清里程碑</span></div>
            <div className="cf-list">
              {loansBySoon.map((l) => (
                <div key={l.id} className="cf-row cf-row--static">
                  <span className="cf-row__l">
                    <span className="cf-row__name">{l.name}</span>
                    <span className="cf-row__sub">還清後每月 +{fmt(l.monthly)} 現金流</span>
                  </span>
                  <span className="cf-mile t-num">{monthsToYM(l.monthsLeft)}</span>
                </div>
              ))}
            </div>
          </Card>
        )}

        <Card className="cf-sec">
          <div className="cf-sec__head"><span className="t-overline">月結 · 每月封存</span></div>
          <div className="cf-sec__hint">每月底更新好「信用卡帳單」後按封存,留一筆當月快照——累積後總覽會長出趨勢圖。</div>
          <div className="cf-list">
            {monthly.slice().reverse().map((m) => (
              <div key={m.id} className="cf-row cf-row--static">
                <span className="cf-row__l">
                  <span className="cf-row__name">{m.ym}</span>
                  <span className="cf-row__sub">真實支出 {fmt(m.realExpense)} · 儲蓄 {fmt(m.saving)}{m.daili ? " · 代墊 " + fmt(m.daili) : ""}</span>
                </span>
                <span className="cf-row__amt t-num">淨值 {fmt(m.netWorth)}</span>
              </div>
            ))}
            {monthly.length === 0 && !mForm ? <div className="cf-empty">還沒有月結紀錄</div> : null}
          </div>
          {mForm ? (
            <div className="cf-editor">
              <Input placeholder="年月(例 2026-06)" value={mForm.ym}
                onChange={(e) => setMForm((f) => Object.assign({}, f, { ym: e.target.value }))} />
              <Input amount affix="NT$" inputMode="decimal" placeholder="這個月公司代墊多少"
                value={mForm.daili} onChange={(e) => setMForm((f) => Object.assign({}, f, { daili: e.target.value }))} />
              <div className="goal__hint">會自動抓你現在的淨值/收入/支出/卡費當快照;代墊填上面這格(沒有就留 0)</div>
              <div className="cf-editor__btns">
                <span className="cf-editor__spacer" />
                <div className="cf-editor__right">
                  <Button variant="secondary" onClick={() => setMForm(null)} disabled={mBusy}>取消</Button>
                  <Button variant="primary" onClick={closeThisMonth} loading={mBusy}>封存</Button>
                </div>
              </div>
            </div>
          ) : (
            <button type="button" className="cf-add" onClick={() => setMForm({ ym: curYM(), daili: "", note: "" })}>
              <i className="ph ph-floppy-disk" aria-hidden="true" />封存這個月
            </button>
          )}
        </Card>
      </div>
    );
  }

  window.Cashflow = Cashflow;
})();
