// Helm — 核心-衛星部位追蹤。把你有代號的持股分成「核心(市值型大盤 ETF)」與「衛星(個股/主題/槓桿)」，
//   看衛星佔比與集中度提醒:核心=分散地基、衛星=報酬彈性也是風險。教育用、非投資建議。純前端讀 window.HELM.assets。
(function () {
  const NS = window.HelmDesignSystem_9613a7;
  function fmt(n) { return Math.round(n || 0).toLocaleString("en-US"); }
  function wan(n) { return (Math.round((n || 0) / 1e4)).toLocaleString("en-US"); }
  function pct(a, b) { return b > 0 ? a / b * 100 : 0; }

  // 市值型大盤 ETF 視為「核心」；其餘有代號的持股(個股/主題/槓桿/高股息)視為「衛星」。
  const CORE = ["0050", "006208", "006204", "00646", "00850", "VOO", "VTI", "VT", "SPY", "IVV", "VTSAX", "0051", "00692", "00905"];
  function coreKey(t) { return String(t || "").toUpperCase().replace(/\.TW$/, ""); }
  function isCore(t) { return CORE.indexOf(coreKey(t)) >= 0; }

  const WARN_PCT = 20;   // 衛星佔比警戒線(可依風險偏好調整)

  function SatelliteScreen({ onClose }) {
    const H = window.HELM || {};
    const holdings = (H.assets || []).filter(function (a) { return a.ticker && a.twd > 0; });
    const core = holdings.filter(function (a) { return isCore(a.ticker); });
    const sat = holdings.filter(function (a) { return !isCore(a.ticker); });
    const coreTwd = core.reduce(function (s, a) { return s + a.twd; }, 0);
    const satTwd = sat.reduce(function (s, a) { return s + a.twd; }, 0);
    const total = coreTwd + satTwd;
    const satPct = pct(satTwd, total);
    const corePct = pct(coreTwd, total);
    const warn = satPct > WARN_PCT;
    const sortedSat = sat.slice().sort(function (a, b) { return b.twd - a.twd; });
    const topSat = sortedSat[0];
    const topSatPct = topSat ? pct(topSat.twd, total) : 0;

    const coreCol = "var(--accent-brass, #cbac74)";
    const satCol = warn ? "var(--c-neg, #c0392b)" : "var(--c-alloc-3, #b5794a)";
    const gCol = "var(--c-pos, #1b8a5a)", rCol = "var(--c-neg, #c0392b)";

    function Shell(children) {
      return (
        <div className="fpage" role="dialog" aria-modal="true" aria-label="核心衛星部位">
          <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">核心 · 衛星部位</span>
              <span aria-hidden="true" />
            </header>
            <div className="fpage__scroll"><div className="fpage__body">{children}</div></div>
          </div>
        </div>
      );
    }

    if (!holdings.length) {
      return Shell(
        <section className="fpage__card">
          <div className="fpage__card-head"><span className="t-overline">核心 · 衛星</span></div>
          <div className="fire-desc">
            <p>💡 這張卡會把你「有股票代號」的持股，自動分成 <b>核心(市值型大盤 ETF，如 0050 / VOO)</b> 和 <b>衛星(個股、主題、槓桿)</b>，算出衛星佔比、提醒集中度。</p>
            <p>目前還沒讀到有代號的持股。到「明細」新增你的持股(填代號與股數)後再回來看。</p>
          </div>
          <p className="fx-disclaim">核心/衛星依代號自動判定(市值型 ETF=核心)。教育用途、非投資建議。</p>
        </section>
      );
    }

    return Shell(
      <React.Fragment>
        <section className="fpage__card">
          <div className="fpage__card-head"><span className="t-overline">衛星佔你持股的比重</span></div>
          <div className="fx-now">
            <span className="fx-now__unit">衛星部位佔比{warn ? "(偏高)" : ""}</span>
            <span className="fx-now__rate t-num" style={{ color: warn ? rCol : "inherit" }}>{satPct.toFixed(0)}%</span>
          </div>

          <div style={{ display: "flex", height: 16, borderRadius: 8, overflow: "hidden", background: "var(--line-faint, #eee)", margin: "6px 0 10px" }}>
            <div style={{ width: corePct + "%", background: coreCol }} title={"核心 " + corePct.toFixed(0) + "%"} />
            <div style={{ width: satPct + "%", background: satCol }} title={"衛星 " + satPct.toFixed(0) + "%"} />
          </div>
          <div className="goal__nums">
            <span className="t-num" style={{ color: coreCol }}>核心 {corePct.toFixed(0)}% · {wan(coreTwd)} 萬</span>
            <span className="goal__pct t-num" style={{ color: satCol }}>衛星 {satPct.toFixed(0)}% · {wan(satTwd)} 萬</span>
          </div>

          <div className="fire-desc">
            <p>💡 <b>核心</b>({wan(coreTwd)} 萬)是分散的地基、<b>衛星</b>({wan(satTwd)} 萬)是你挑的個股/主題——報酬彈性來源，也是風險來源。{warn
              ? <b style={{ color: rCol }}>目前衛星佔 {satPct.toFixed(0)}%，超過 {WARN_PCT}% 的參考線，集中度偏高，留意「選錯一檔就傷到整體」的風險。</b>
              : <span>目前衛星佔 {satPct.toFixed(0)}%，在 {WARN_PCT}% 參考線內，比重還算克制。</span>}</p>
            {topSat && topSatPct >= 10 && <p>最大的單一衛星是 <b>{topSat.name}</b>，佔總持股 <b>{topSatPct.toFixed(0)}%</b>——單一個股別讓它太重，它腰斬時你才扛得住。</p>}
          </div>
        </section>

        <section className="fpage__card">
          <div className="fpage__card-head"><span className="t-overline">持股明細 · 依佔比</span></div>
          <div className="tax-break">
            {core.length > 0 && <div className="tax-row tax-row--sum"><span style={{ color: coreCol }}>◆ 核心 · 市值型 ETF</span><span className="t-num">{corePct.toFixed(0)}%</span></div>}
            {core.slice().sort(function (a, b) { return b.twd - a.twd; }).map(function (a) {
              return <div className="tax-row" key={a.id}><span>{a.name}<span style={{ opacity: .6 }}> · {a.ticker}</span></span><span className="t-num">{fmt(a.twd)}（{pct(a.twd, total).toFixed(0)}%）</span></div>;
            })}
            {sat.length > 0 && <div className="tax-row tax-row--sum"><span style={{ color: satCol }}>★ 衛星 · 個股/主題</span><span className="t-num">{satPct.toFixed(0)}%</span></div>}
            {sortedSat.map(function (a) {
              return <div className="tax-row" key={a.id}><span>{a.name}<span style={{ opacity: .6 }}> · {a.ticker}</span></span><span className="t-num">{fmt(a.twd)}（{pct(a.twd, total).toFixed(0)}%）</span></div>;
            })}
          </div>
          <p className="fx-disclaim">核心/衛星依代號自動判定:市值型大盤 ETF(0050、006208、VOO、VT 等)=核心，其餘有代號的持股=衛星。判定僅供參考、可能與你的認定不同。教育用途、非投資建議。</p>
        </section>
      </React.Fragment>
    );
  }

  window.SatelliteScreen = SatelliteScreen;
})();
