// Helm — Detail (明細). Segmented 資產｜負債, grouped list with subtotals, drill-in rows.
(function () {
  const NS = window.HelmDesignSystem_9613a7;
  const { SegmentedControl, Card, ListRow, AmountDisplay, Badge } = NS;

  function fmt(n) { return Math.round(n).toLocaleString("en-US"); }

  function Group({ g, onEdit }) {
    return (
      <div className="helm-group">
        <div className="helm-group__head">
          <span className="helm-group__title">
            <span className="helm-tag__dot" style={{ color: g.color }} />{g.cat}
          </span>
          <span className="helm-group__subtotal t-num">NT$ {fmt(g.subtotal)}</span>
        </div>
        <Card variant="flat" style={{ padding: 6 }}>
          {g.items.map((it, idx) => (
            <React.Fragment key={it.id}>
              {idx > 0 && <div className="helm-group__divider" />}
              <ListRow
                name={it.name}
                category={it.cat}
                categoryColor={g.color}
                note={it.note}
                date={it.date}
                stale={it.stale}
                onClick={() => onEdit(it)}
                amount={<AmountDisplay value={((it.auto && it.livePrice) || it.loanAuto) ? it.twd : (it.ccy === "USD" ? it.usd : it.twd)} currency={((it.auto && it.livePrice) || it.loanAuto) ? "TWD" : it.ccy} size="md" />}
                subAmount={
                  (it.auto && it.livePrice)
                    ? ("自動 · " + it.shares + " 股 × " + (it.priceCcy === "USD" ? "US$ " : "NT$ ") + Number(it.livePrice).toLocaleString("en-US", { maximumFractionDigits: 2 }))
                    : it.loanAuto
                      ? (it.loanWarn === "paylow"
                          ? "⚠ 月付金不足付利息,請檢查利率/月付金"
                          : "每月自動遞減 · " + (it.loanMonths > 0 ? "已過 " + it.loanMonths + " 期" : "本月起算") + (it.loanPay ? " · 月付 NT$ " + fmt(it.loanPay) : ""))
                      : (it.ccy === "USD" ? "≈ NT$ " + fmt(it.twd) : null)
                }
              />
            </React.Fragment>
          ))}
        </Card>
      </div>
    );
  }

  function Detail({ onEdit }) {
    const H = window.HELM;
    const [side, setSide] = React.useState("asset");
    const groups = side === "asset" ? H.assetGroups : H.liabGroups;

    return (
      <div className="screen">
        <SegmentedControl
          value={side}
          onChange={setSide}
          tones={["positive", "negative"]}
          options={[
            { value: "asset", label: "資產", count: "NT$ " + fmt(H.totalAssets) },
            { value: "liab", label: "負債", count: "NT$ " + fmt(H.totalLiab) },
          ]}
        />

        <div className="dt-list">
          {groups.map((g) => <Group key={g.cat} g={g} onEdit={onEdit} />)}
        </div>

        {/* 保險：展示但不計入淨值（沒有保障資料時整個不顯示，避免空框） */}
        {side === "asset" && H.protection.length > 0 && (
          <div className="helm-group">
            <div className="helm-group__head">
              <span className="helm-group__title" style={{ color: "var(--text-tertiary)" }}>
                <i className="ph ph-umbrella" style={{ fontSize: "1rem" }} />保障
              </span>
              <Badge tone="brass">不計入淨值</Badge>
            </div>
            <Card variant="flat" style={{ padding: 6 }}>
              {H.protection.map((it) => (
                <ListRow key={it.id} name={it.name} excluded chevron={false}
                  amount={<AmountDisplay value={it.twd} size="sm" tone="muted" />}
                  subAmount="保額 · 理賠給受益人，不是你的資產" />
              ))}
            </Card>
          </div>
        )}
      </div>
    );
  }

  window.Detail = Detail;
})();
