// Screens that match the original Streamlit dashboard pages 1:1.
// Original pages: Home, Accounts, Tax, Cash flow, History
// No invented features — every section maps to something in dashboard/dashboard/app.py.
//
// Each screen receives a `nav` object with: tab(id), focusAccount(name)
// Per-render data is read via `window.KIS_DATA.get()` so the active user
// (combined / 조범진 / 박수현) controls what shows.

// ═══════════════════════════════════════════════════════════════════
// HOME — original Streamlit Home: hero metrics + value chart + gain chart
//        + monthly P/L bars + yearly P/L bars + account cards + flows
// Period toggle (1주/1달/3달/6달/1년) drives the value chart.
// ═══════════════════════════════════════════════════════════════════
function HomeScreen({ nav }) {
  const D = window.KIS_DATA.get();
  const { hero, valueSeries, costSeries, investedSeries, gainSeries, marginSeries,
          dateSeries, accounts, dailyFlows, monthlyPL, yearlyPL } = D;
  // generatedAt lives on the container, not the per-user slice — read it there.
  const genAt = window.KIS_DATA.generatedAt;

  const [period, setPeriod] = React.useState("1m");
  const [chartTab, setChartTab] = React.useState("value");  // value | gain | monthly | yearly

  return (
    <div className="kis-screen">
      <AppBar title="" leading="" trailing={
        <span className="t-sm dim">USD {D.fxUsdKrw.toFixed(2)}</span>
      } />

      {/* Massive hero — total value + lifetime return */}
      <div style={{ padding: "8px 24px 20px" }}>
        <div className="t-sm muted">총자산 · {D.displayName}</div>
        <div className="spacer-8" />
        <div className="num" style={{ fontSize: 40, fontWeight: 800, letterSpacing: "-0.04em", lineHeight: 1.05 }}>
          ₩{fmtKRW(hero.totalValue)}
        </div>
        <div className="spacer-8" />
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <span className={`t-md ${upDown(hero.totalGain)}`} style={{ fontWeight: 700 }}>{fmtSigned(hero.totalGain)}</span>
          <span className={`chip chip-${upDown(hero.totalGain)}`}>{
            hero.netInvested > 0
              ? fmtPct((hero.totalGain / hero.netInvested) * 100)
              : "—"
          }</span>
          <span className="t-sm dim">총수익</span>
        </div>
      </div>

      {/* Big chart card with sub-tabs */}
      <div style={{ padding: "0 16px" }}>
        <div className="card-elev" style={{ padding: 16 }}>
          {/* Chart-type sub-tabs */}
          <div style={{ display: "flex", gap: 4, marginBottom: 12, borderBottom: "1px solid var(--border)" }}>
            {[
              { id: "value",   label: "자산 추이" },
              { id: "gain",    label: "이익·마진" },
              { id: "monthly", label: "월별" },
              { id: "yearly",  label: "연도별" },
            ].map(t => (
              <button key={t.id} onClick={() => setChartTab(t.id)} style={{
                padding: "8px 4px", border: "none", background: "transparent",
                color: chartTab === t.id ? "var(--fg)" : "var(--fg-tertiary)",
                fontSize: 12, fontWeight: 700, cursor: "pointer",
                fontFamily: "inherit",
                borderBottom: chartTab === t.id ? "2px solid var(--accent)" : "2px solid transparent",
                marginBottom: -1,
                flex: 1,
              }}>{t.label}</button>
            ))}
          </div>

          {/* Chart body */}
          <div style={{ minHeight: 200 }}>
            {chartTab === "value" && (
              <ValueChart
                valueSeries={valueSeries[period]}
                costSeries={costSeries[period]}
                investedSeries={investedSeries[period]}
                period={period}
                dates={(dateSeries || {})[period]}
                generatedAt={genAt}
                height={200}
              />
            )}
            {chartTab === "gain" && (
              <GainChart
                gainSeries={gainSeries[period]}
                marginSeries={marginSeries[period]}
                period={period}
                dates={(dateSeries || {})[period]}
                generatedAt={genAt}
                height={200}
              />
            )}
            {chartTab === "monthly" && (
              <PLBarsChart data={monthlyPL} xKey="month" height={200} />
            )}
            {chartTab === "yearly" && (
              <PLBarsChart data={yearlyPL} xKey="year" height={200} />
            )}
          </div>

          {/* Period toggle (only relevant for value/gain) */}
          {(chartTab === "value" || chartTab === "gain") && (
            <div style={{ marginTop: 10 }}>
              <PeriodToggle value={period} onChange={setPeriod} />
            </div>
          )}
        </div>
      </div>

      <div className="spacer-16" />

      {/* 4-card metric grid — net invested, daily delta, realized, unrealized.
          Total gain + return % moved up to the hero header per user request. */}
      <div style={{ padding: "0 20px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 8 }}>
          <Stat label="누적 순입금" value={`₩${fmtKRW(hero.netInvested, true)}`} />
          {(() => {
            // Delta vs the most recent prior trading day. Always label it
            // "전일 대비" — we no longer surface the explicit basis date
            // (it could read as a stale 3-day-old date whenever a refresh
            // gap leaves the prior snapshot a few days back; data itself is
            // sound, so the date caveat is just noise).
            const basis = hero.todayBasis || "";
            const when = basis ? "전일 대비" : "최근 변동";
            return (
              <Stat label={when}
                    value={`${fmtSigned(hero.todayDelta, true)} (${fmtPct(hero.todayDeltaPct)})`}
                    cls={upDown(hero.todayDelta)} />
            );
          })()}
          <Stat label="실현" value={fmtSigned(hero.realized, true)} cls={upDown(hero.realized)} />
          <Stat label="평가" value={fmtSigned(hero.unrealized, true)} cls={upDown(hero.unrealized)} />
        </div>
      </div>

      {/* Account cards */}
      <SectionHead
        title={window.KIS_DATA.activeSlug === "combined" ? "전체 계좌" : "내 계좌"}
        more={`${accounts.length}개 ›`}
        onMore={() => nav.tab("accounts")} />
      <div className="list">
        {accounts.map(a => (
          <AccountRow key={a.id} a={a} onClick={() => nav.focusAccount(a.id)} />
        ))}
      </div>

      <SectionHead title="최근 자금 흐름" more="전체 ›" onMore={() => nav.tab("flow")} />
      <div className="list">
        {dailyFlows.slice(0, 4).map((f, i) => <FlowRow key={i} f={f} />)}
      </div>
      <div style={{ height: 24 }} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// ACCOUNTS — original behavior: shows ALL accounts stacked, each with metrics + holdings.
// If `focus` is set, only that account renders (with "← Show all" button at top).
// ═══════════════════════════════════════════════════════════════════
function AccountsScreen({ nav, focus }) {
  const D = window.KIS_DATA.get();
  const list = focus ? D.accounts.filter(a => a.id === focus) : D.accounts;
  return (
    <div className="kis-screen">
      <AppBar title="계좌" leading="" />

      {focus && (
        <div style={{ padding: "0 20px 8px" }}>
          <button className="btn-ghost" onClick={() => nav.focusAccount(null)} style={{ fontSize: 13 }}>
            ← 전체 계좌 보기
          </button>
        </div>
      )}

      {!focus && (
        <div style={{ padding: "0 20px 8px" }}>
          <div className="t-sm muted">전체 자산</div>
          <div className="num" style={{ fontSize: 30, fontWeight: 800 }}>
            ₩{fmtKRW(D.accounts.reduce((s, a) => s + a.value, 0))}
          </div>
        </div>
      )}

      {list.map(a => <AccountSection key={a.id} a={a} nav={nav} />)}

      <div style={{ height: 24 }} />
    </div>
  );
}

function AccountSection({ a, nav }) {
  // The API now sends per-account holdings on `a.holdings`. The previous
  // code filtered the GLOBAL holdings list by bucket, which displayed every
  // user-wide US holding on every US account.
  const holdings = a.holdings || [];

  return (
    <div style={{ borderTop: "1px solid var(--border)", marginTop: 12, padding: "16px 20px 0" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 12 }}>
        <AccountAvatar name={a.name} kind={a.bucket === "us" ? "us" : a.name.includes("ISA") ? "isa" : "domestic"} />
        <div>
          <div className="t-md" style={{ fontWeight: 700 }}>{a.name}</div>
          <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0 }}>{a.id}</div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginBottom: 14 }}>
        <Stat label="평가금액" value={`₩${fmtKRW(a.value, true)}`} />
        <Stat label="ROI" value={fmtPct(a.roi)} cls={upDown(a.roi)} />
        <Stat label="실현" value={fmtSigned(a.realized, true)} cls={upDown(a.realized)} />
        <Stat label="평가" value={fmtSigned(a.unrealized, true)} cls={upDown(a.unrealized)} />
      </div>

      <div className="t-sm muted" style={{ marginBottom: 8, fontWeight: 600 }}>보유 종목</div>
      {holdings.length > 0 ? (
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 8 }}>
          {holdings.map(h => (
            <HoldingCard key={h.code} h={h} onClick={() => nav && nav.openHolding && nav.openHolding(h.code)} />
          ))}
        </div>
      ) : (
        <div className="t-sm dim" style={{ padding: "8px 0", marginBottom: 8 }}>이 계좌에는 보유 종목이 없습니다.</div>
      )}
    </div>
  );
}

function HoldingCard({ h, onClick }) {
  const isUs = h.market !== "KRX";
  // The API now ships valueKrw / costKrw / plKrw so we never have to guess
  // whether `qty * live` is in KRW or USD. avg / live are still per-share
  // in their native unit (USD for US, KRW for KRX) for the secondary line.
  return (
    <div className="card" style={{ padding: 14, cursor: onClick ? "pointer" : "default" }} onClick={onClick}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <div className="t-base" style={{ fontWeight: 700 }}>{h.ticker}</div>
          <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0, marginTop: 2 }}>
            {h.qty}주 · 평단 {isUs ? `$${(h.avg||0).toFixed(2)}` : `₩${fmtKRW(h.avg)}`} · 현재가 {isUs ? `$${(h.live||0).toFixed(2)}` : `₩${fmtKRW(h.live)}`}
          </div>
        </div>
        {onClick && <span className="t-md dim" style={{ marginLeft: 8 }}>›</span>}
      </div>
      <div className="num" style={{ fontSize: 20, fontWeight: 800, marginTop: 8 }}>
        ₩{fmtKRW(h.valueKrw)}
      </div>
      <div className={`num t-sm ${upDown(h.plKrw)}`} style={{ fontWeight: 700, marginTop: 4 }}>
        {fmtSigned(h.plKrw, true)} · {fmtPct(h.plPct)}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// HOLDING DETAIL — tap a holding from Accounts → opens this screen
// Sections: live price + P/L, position summary, realized sale history,
//           dividends received for this ticker
// ═══════════════════════════════════════════════════════════════════
function HoldingDetailScreen({ nav, code }) {
  const D = window.KIS_DATA.get();
  const h = D.holdings.find(x => x.code === code);
  if (!h) {
    return (
      <div className="kis-screen">
        <AppBar title="종목 없음" leading="‹" onLeading={() => nav.back && nav.back()} />
        <div style={{ padding: "24px 20px", color: "var(--fg-tertiary)" }}>
          이 종목 코드 ({code})에 대한 보유 데이터가 없어요. KIS 데이터 새로고침 후
          다시 시도하세요.
        </div>
      </div>
    );
  }
  const isUs = h.market !== "KRX";
  // KRW totals come from the API (valueKrw / costKrw / plKrw); avg / live
  // stay per-share (USD for US, KRW for KRX) for the price hero.
  const valueKrw = h.valueKrw;
  const costKrw  = h.costKrw;
  const plKrw    = h.plKrw;

  // sales for this ticker
  const sales = isUs
    ? D.usSales.filter(s => s.symbol === h.code)
    : D.krxSales.filter(s => s.ticker === h.code || s.name === h.ticker);

  // Dividend filter — the API populates `r.ticker` from the resolved-events
  // `symbol` field (a human-readable Korean ETF name for KRX, a brokerage
  // label for US holdings). Match against the holding's code, ticker, or
  // display name with substring tolerance because the names aren't always
  // identical (e.g. "RISE 미국나스닥100" vs "KB RISE 미국나스닥100증권상장지수
  // 투자신탁(주식)" for the same instrument).
  const matchesHolding = (s) => {
    if (!s) return false;
    if (s === h.code || s === h.ticker || s === h.name) return true;
    const a = s.replace(/\s+/g, "");
    const tk = (h.ticker || "").replace(/\s+/g, "");
    const nm = (h.name   || "").replace(/\s+/g, "");
    return (tk && (a.includes(tk) || tk.includes(a)))
        || (nm && (a.includes(nm) || nm.includes(a)));
  };
  const dividends = D.ledger.filter(r => r.tag === "dividend"
    && (matchesHolding(r.ticker) || (r.note && matchesHolding(r.note))));

  return (
    <div className="kis-screen">
      <AppBar
        title={h.ticker}
        leading="‹"
        onLeading={() => nav.back && nav.back()}
      />

      {/* Hero: current price + change since avg */}
      <div style={{ padding: "0 20px 8px" }}>
        <div className="t-sm muted">{h.market} · {h.qty}주 보유</div>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 4 }}>
          <div className="num" style={{ fontSize: 32, fontWeight: 800, letterSpacing: "-0.03em" }}>
            {isUs ? `$${(h.live||0).toFixed(2)}` : `₩${fmtKRW(h.live)}`}
          </div>
          <span className={`chip chip-${upDown(plKrw)}`}>{fmtPct(h.plPct)}</span>
        </div>
        <div className={`num t-md ${upDown(plKrw)}`} style={{ fontWeight: 700, marginTop: 4 }}>
          평단 대비 {(() => {
            const d = (h.live || 0) - (h.avg || 0);
            const sign = d >= 0 ? "+" : "−";
            const abs = Math.abs(d);
            return isUs
              ? `${sign}$${abs.toFixed(2)}`
              : `${sign}₩${fmtKRW(abs)}`;
          })()}
        </div>
      </div>

      {/* Position summary */}
      <SectionHead title="내 포지션" more="" />
      <div style={{ padding: "0 20px" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <Stat label="평가금액" value={`₩${fmtKRW(valueKrw, true)}`} />
          <Stat label="평가손익" value={fmtSigned(plKrw, true)} cls={upDown(plKrw)} />
          <Stat label="평단가" value={isUs ? `$${(h.avg||0).toFixed(2)}` : `₩${fmtKRW(h.avg)}`} />
          <Stat label="총 매입가" value={`₩${fmtKRW(costKrw, true)}`} />
        </div>
      </div>

      {/* Sales history */}
      {sales.length > 0 && (
        <>
          <SectionHead title="매도 이력" more={`${sales.length}건`} />
          <div className="list">
            {sales.map((s, i) => (
              <div key={i} className="row-item">
                <div className="flow-icon wd">−</div>
                <div className="body">
                  <span className="t-base" style={{ fontWeight: 600 }}>매도 {s.qty}주</span>
                  <span className="t-sm dim">{s.date}</span>
                </div>
                <div className="right">
                  <span className={`num t-md ${upDown(s.plKrw)}`} style={{ fontWeight: 700 }}>
                    {fmtSigned(s.plKrw, true)}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {/* Dividends */}
      {dividends.length > 0 && (
        <>
          <SectionHead title="받은 배당" more="" />
          <div className="list">
            {dividends.map((r, i) => (
              <div key={i} className="row-item">
                <div className="flow-icon div">₩</div>
                <div className="body">
                  <span className="t-base" style={{ fontWeight: 600 }}>배당</span>
                  <span className="t-sm dim">{r.date}{r.note ? ` · ${r.note}` : ""}</span>
                </div>
                <div className="right">
                  {r.amountUsd != null ? (
                    <>
                      <span className={`num t-md ${upDown(r.amountUsd)}`} style={{ fontWeight: 700 }}>
                        {r.amountUsd >= 0 ? "+" : "−"}${Math.abs(r.amountUsd).toFixed(2)}
                      </span>
                      <span className="t-sm dim num">≈ {r.amountKrw >= 0 ? "+" : "−"}₩{fmtKRW(Math.abs(r.amountKrw), true)}</span>
                    </>
                  ) : (
                    <span className={`num t-md ${upDown(r.amountKrw)}`} style={{ fontWeight: 700 }}>
                      {fmtSigned(r.amountKrw, true)}
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      <div style={{ height: 24 }} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// TAX — Korean capital gains tax page (original Streamlit Tax page)
// Sections: gauge + harvest calculator preview + year history
// ═══════════════════════════════════════════════════════════════════
function TaxScreen({ nav }) {
  const D = window.KIS_DATA.get();
  const t = D.tax;
  // Clamp the deduction usage to [0, annualDeduction] — a YTD LOSS would
  // otherwise produce negative usage (`-40% 사용`) and `headroom > 250만`,
  // i.e. nonsense that suggests you've gained extra deduction. Codex R10
  // #3 finding. The signed YTD itself is still rendered above so the user
  // sees the loss, but the gauge math reflects only realized GAINS.
  const ytdGain = Math.max(0, t.usYtdRealized);
  const taxable = Math.max(0, ytdGain - t.annualDeduction);
  const taxOwed = Math.round(taxable * t.rate);
  const headroom = Math.max(0, t.annualDeduction - ytdGain);
  const pct = t.annualDeduction > 0
    ? Math.min(100, (ytdGain / t.annualDeduction) * 100)
    : 0;
  const overLimit = ytdGain > t.annualDeduction;

  return (
    <div className="kis-screen">
      <AppBar title={`세금 ${t.currentYear}`} leading="" />

      <div style={{ padding: "0 20px 8px" }}>
        <div className="t-sm muted">미국 실현손익 YTD</div>
        <div className="num" style={{ fontSize: 30, fontWeight: 800 }}>
          ₩{fmtKRW(t.usYtdRealized)}
        </div>
        <div className="t-sm dim" style={{ marginTop: 4 }}>
          250만원 비과세 한도 중 {pct.toFixed(0)}% 사용
        </div>

        {/* Gauge bar */}
        <div style={{ marginTop: 12, height: 12, background: "var(--surface-pressed)", border: "1px solid var(--border)", borderRadius: 999, overflow: "hidden", position: "relative" }}>
          <div style={{
            width: `${Math.min(100, pct)}%`, height: "100%",
            // Over the tax-free limit → amber WARNING (not blue: blue is the
            // loss/decline color everywhere else and reads as benign here).
            background: overLimit ? "var(--amber)" : "var(--up)",
            transition: "width 0.6s var(--ease-out)",
          }} />
          {/* Deduction-limit reference line, pinned just inside the right edge
              (the gauge's full scale == the 250만 limit). left:100% put it
              outside the overflow:hidden box, so it never rendered. */}
          <div style={{ position: "absolute", right: 0, top: 0, height: "100%", width: 2, background: "var(--amber)" }} />
        </div>
        <div className="t-xs dim" style={{ marginTop: 6, textTransform: "none", letterSpacing: 0 }}>
          한도 ₩{fmtKRW(t.annualDeduction, true)}
        </div>
      </div>

      <div style={{ padding: "16px 20px 0" }}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <Stat label="비과세 한도" value={`₩${fmtKRW(t.annualDeduction, true)}`} />
          <Stat label="남은 한도" value={`₩${fmtKRW(headroom, true)}`} cls={headroom > 0 ? "up" : "down"} />
          <Stat label="과세 대상" value={`₩${fmtKRW(taxable, true)}`} />
          <Stat label="예상 세금" value={`₩${fmtKRW(taxOwed, true)}`} cls={taxOwed > 0 ? "down" : ""} />
        </div>
      </div>

      {/* Harvest calculator hint + per-position recommendations.
          Algorithm ported from dashboard/app.py:1142-1208 — fill the
          ₩2.5M annual deduction by selling integer shares of a US position
          with embedded gains, then rebuy next trading day to step up
          cost basis tax-free. Korea has no wash-sale rule so this works.*/}
      {headroom > 0 && (
        <div style={{ padding: "16px 16px 0" }}>
          <div className="card-elev" style={{
            padding: 14, border: "1px solid rgba(180, 83, 9, 0.30)",
            background: "linear-gradient(135deg, rgba(180,83,9,0.08), rgba(180,83,9,0.02))",
          }}>
            <div className="t-xs" style={{ color: "var(--amber)", marginBottom: 4 }}>HARVEST</div>
            <div className="t-base" style={{ fontWeight: 700 }}>이번 연도 ₩{fmtKRW(headroom, true)} 한도 미사용</div>
            <div className="t-sm dim" style={{ marginTop: 4, textTransform: "none", letterSpacing: 0, lineHeight: 1.5 }}>
              연말 매도→다음날 재매수로 비과세 평단 step-up 가능. 12/26까지.
              아래 후보 중 <b>한 종목</b>의 표시된 수량을 매도하세요.
            </div>
            {(t.harvestCandidates && t.harvestCandidates.length > 0) ? (
              <div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
                {t.harvestCandidates.map((c, i) => (
                  <div key={c.symbol + ":" + c.account} className="card" style={{
                    padding: 12, background: "var(--surface)",
                    border: i === 0 ? "1px solid rgba(180,83,9,0.45)" : "1px solid var(--border)",
                  }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 4 }}>
                      <div className="t-base" style={{ fontWeight: 700 }}>
                        {c.symbol}
                        {i === 0 && <span style={{ marginLeft: 8, fontSize: 10, color: "var(--amber)", fontWeight: 800 }}>★ 추천</span>}
                      </div>
                      <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0 }}>{c.account}</div>
                    </div>
                    <div className="num" style={{ fontSize: 22, fontWeight: 800, color: "var(--up)" }}>
                      {c.qtyToSell}주 매도
                    </div>
                    <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0, marginTop: 2 }}>
                      {c.qtyHeld}주 보유 · 평단 ${(c.costUsd || 0).toFixed(2)} → 현재 ${(c.liveUsd || 0).toFixed(2)}
                      {" "}({fmtPct(c.gainPctUsd)})
                    </div>
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 6, marginTop: 10 }}>
                      <div>
                        <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0 }}>실현이익</div>
                        <div className="num t-sm" style={{ fontWeight: 700 }}>₩{fmtKRW(c.realizedKrw, true)}</div>
                      </div>
                      <div>
                        <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0 }}>왕복 수수료</div>
                        <div className="num t-sm down" style={{ fontWeight: 700 }}>−₩{fmtKRW(c.feeKrw, true)}</div>
                      </div>
                      <div>
                        <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0 }}>세금 절감</div>
                        <div className="num t-sm up" style={{ fontWeight: 700 }}>₩{fmtKRW(c.taxSavedKrw, true)}</div>
                      </div>
                      <div>
                        <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0 }}>순이익</div>
                        <div className={`num t-sm ${upDown(c.netBenefitKrw)}`} style={{ fontWeight: 800 }}>
                          {fmtSigned(c.netBenefitKrw, true)}
                        </div>
                      </div>
                    </div>
                    {!c.fillsHeadroom && (
                      <div className="t-xs" style={{ marginTop: 8, color: "var(--amber)", lineHeight: 1.4, textTransform: "none", letterSpacing: 0 }}>
                        ⚠ 보유 전부 팔아도 한도가 ₩{fmtKRW(headroom - c.realizedKrw, true)} 남음 — 다른 종목과 합쳐야 채움
                      </div>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <div className="t-sm dim" style={{ marginTop: 10, textTransform: "none", letterSpacing: 0 }}>
                현재 평가이익이 있는 미국 종목이 없어 harvest할 게 없어요.
              </div>
            )}
          </div>
        </div>
      )}

      <SectionHead title="연도별 실현손익" more="" />
      <div style={{ padding: "0 20px" }}>
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr style={{ background: "var(--surface-elevated)" }}>
                <th style={th}>연도</th>
                <th style={th}>국내</th>
                <th style={th}>미국</th>
                <th style={th}>합계</th>
              </tr>
            </thead>
            <tbody>
              {D.yearPL.map(y => (
                <tr key={y.year} style={{ borderTop: "1px solid var(--border)" }}>
                  <td style={td}>{y.year}</td>
                  <td style={{ ...td, color: y.korean >= 0 ? "var(--up)" : "var(--down)" }}>
                    {fmtSigned(y.korean, true)}
                  </td>
                  <td style={{ ...td, color: y.us >= 0 ? "var(--up)" : "var(--down)" }}>
                    {fmtSigned(y.us, true)}
                  </td>
                  <td style={{ ...td, fontWeight: 700, color: (y.korean + y.us) >= 0 ? "var(--up)" : "var(--down)" }}>
                    {fmtSigned(y.korean + y.us, true)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div style={{ height: 24 }} />
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// CASH FLOW — original Streamlit "Cash flow" page
// Sections: deposits/withdrawals/net summary, transfers list, dividend/interest/fee ledger
// ═══════════════════════════════════════════════════════════════════
function CashFlowScreen({ nav }) {
  const D = window.KIS_DATA.get();
  const [filter, setFilter] = React.useState("all");
  const ts = D.transfersSum;
  // Lifetime totals come from the API's `ledgerTotals` (computed off the
  // unsliced data). The `ledger` array itself is capped at 50 rows for the
  // list UI, so summing it client-side under-counts. Fall back to summing
  // when totals weren't sent (older API response).
  const lt = D.ledgerTotals || {};
  const divTotal = lt.dividend != null ? lt.dividend
    : D.ledger.filter(r => r.tag === "dividend").reduce((s, r) => s + Math.abs(r.amountKrw), 0);
  const intTotal = lt.interest != null ? lt.interest
    : D.ledger.filter(r => r.tag === "interest").reduce((s, r) => s + Math.abs(r.amountKrw), 0);
  const feeTotal = lt.fee != null ? lt.fee
    : D.ledger.filter(r => r.tag === "fee").reduce((s, r) => s + Math.abs(r.amountKrw), 0);

  const filters = [
    { id: "all",      label: "전체" },
    { id: "transfer", label: "입출금" },
    { id: "dividend", label: "배당" },
    { id: "interest", label: "이자" },
    { id: "fee",      label: "수수료" },
  ];

  const showTransfers = filter === "all" || filter === "transfer";
  const showLedger    = filter === "all" || ["dividend", "interest", "fee"].includes(filter);
  const ledgerList    = filter === "all" ? D.ledger : D.ledger.filter(r => r.tag === filter);

  return (
    <div className="kis-screen">
      <AppBar title="자금 흐름" leading="" />

      <div style={{ padding: "0 20px 8px" }}>
        <div className="t-sm muted">현금 이동 (출금만 기록)</div>
        <div className="num" style={{ fontSize: 24, fontWeight: 800, color: "var(--down)" }}>
          {fmtKRW(ts.withdrawals)}원
        </div>
        <div className="t-xs dim" style={{ marginTop: 4, textTransform: "none", letterSpacing: 0, lineHeight: 1.4 }}>
          입금은 매수−매도로 자동 추정. 출금만 직접 기록하면 됨.
        </div>
      </div>

      {/* Filter chips */}
      <div style={{
        padding: "12px 20px 4px", display: "flex", gap: 6,
        overflowX: "auto", scrollbarWidth: "none",
      }}>
        {filters.map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            padding: "8px 14px", borderRadius: 999,
            border: filter === f.id ? "1px solid var(--accent)" : "1px solid var(--border)",
            background: filter === f.id ? "var(--accent)" : "var(--surface)",
            color: filter === f.id ? "#fff" : "var(--fg-secondary)",
            fontSize: 13, fontWeight: 700, cursor: "pointer",
            fontFamily: "inherit", whiteSpace: "nowrap", flexShrink: 0,
          }}>{f.label}</button>
        ))}
      </div>

      {/* Summary cards */}
      <div style={{ padding: "12px 20px 0" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
          <Stat label="배당" value={`₩${fmtKRW(divTotal, true)}`} cls="up" />
          <Stat label="이자" value={`₩${fmtKRW(intTotal, true)}`} cls="up" />
          <Stat label="수수료" value={`₩${fmtKRW(feeTotal, true)}`} cls="down" />
        </div>
      </div>

      {showTransfers && (
        <>
          <SectionHead title="기록된 출금" more={`${D.transfers.length}건`} />
          <div className="list">
            {D.transfers.map((t, i) => <TransferRow key={i} t={t} />)}
          </div>
        </>
      )}

      {showLedger && (
        <>
          <SectionHead title={filter === "all" ? "배당 / 이자 / 수수료" : ({ dividend: "배당 내역", interest: "이자 내역", fee: "수수료 내역" })[filter]} more={`${ledgerList.length}건`} />
          <div className="list">
            {ledgerList.map((r, i) => <LedgerRow key={i} r={r} />)}
          </div>
        </>
      )}
      <div style={{ height: 24 }} />
    </div>
  );
}

function TransferRow({ t }) {
  return (
    <div className="row-item">
      <FlowIcon category={t.type === "deposit" ? "deposit" : "withdrawal"} />
      <div className="body">
        <span className="t-base" style={{ fontWeight: 600 }}>{t.type === "deposit" ? "입금" : "출금"}</span>
        <span className="t-sm dim">{t.date}{t.note ? ` · ${t.note}` : ""}</span>
      </div>
      <div className="right">
        <span className={`num t-md ${t.amountKrw >= 0 ? "up" : "down"}`} style={{ fontWeight: 700 }}>
          {t.amountKrw >= 0 ? "+" : "−"}₩{fmtKRW(Math.abs(t.amountKrw), true)}
        </span>
      </div>
    </div>
  );
}

function LedgerRow({ r }) {
  const labels = { dividend: "배당", interest: "이자", fee: "수수료" };
  const cls = r.tag === "fee" ? "down" : "up";
  const sign = r.amountKrw >= 0 ? "+" : "−";
  // USD-originated rows (US dividends) carry both the original USD amount
  // and an FX-converted KRW. Show USD as the secondary line — the user
  // wanted to see that the dividend was paid in dollars, not just won.
  const isUsd = r.amountUsd != null;
  return (
    <div className="row-item">
      <div className={`flow-icon ${r.tag === "dividend" ? "div" : r.tag === "interest" ? "int" : "wd"}`}>
        {r.tag === "dividend" ? "₩" : r.tag === "interest" ? "%" : "F"}
      </div>
      <div className="body">
        <span className="t-base" style={{ fontWeight: 600 }}>
          {labels[r.tag]}{r.ticker ? ` · ${r.ticker}` : ""}
        </span>
        <span className="t-sm dim">{r.date}{r.note ? ` · ${r.note}` : ""}</span>
      </div>
      <div className="right">
        {isUsd ? (
          <>
            <span className={`num t-md ${cls}`} style={{ fontWeight: 700 }}>
              {r.amountUsd >= 0 ? "+" : "−"}${Math.abs(r.amountUsd).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            </span>
            <span className="t-sm dim num">≈ {sign}₩{fmtKRW(Math.abs(r.amountKrw), true)}</span>
          </>
        ) : (
          <span className={`num t-md ${cls}`} style={{ fontWeight: 700 }}>
            {sign}₩{fmtKRW(Math.abs(r.amountKrw), true)}
          </span>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════
// HISTORY — original "History" page with US/KRX sub-tabs
// Per-sale rows from realized trades
// ═══════════════════════════════════════════════════════════════════
function HistoryScreen({ nav }) {
  const D = window.KIS_DATA.get();
  const [sub, setSub] = React.useState("us");
  return (
    <div className="kis-screen">
      <AppBar title="거래 내역" leading="" />

      {/* Sub-tab pills */}
      <div style={{ padding: "4px 20px 12px", display: "flex", gap: 4 }}>
        {[
          { id: "us",  label: "미국 매도" },
          { id: "krx", label: "국내 매도" },
        ].map(s => (
          <button key={s.id} onClick={() => setSub(s.id)} style={{
            flex: 1, padding: "10px 14px", borderRadius: 12, border: "none",
            background: sub === s.id ? "var(--accent-bg)" : "transparent",
            color: sub === s.id ? "var(--accent)" : "var(--fg-tertiary)",
            fontSize: 14, fontWeight: 700, cursor: "pointer",
            fontFamily: "inherit",
          }}>{s.label}</button>
        ))}
      </div>

      {sub === "us" ? (
        <div style={{ padding: "0 20px" }}>
          <div className="t-sm muted" style={{ marginBottom: 8 }}>{D.usSales.length}건</div>
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
              <thead>
                <tr style={{ background: "var(--surface-elevated)" }}>
                  <th style={th}>날짜</th>
                  <th style={th}>종목</th>
                  <th style={{ ...th, textAlign: "right" }}>수량</th>
                  <th style={{ ...th, textAlign: "right" }}>실현손익</th>
                </tr>
              </thead>
              <tbody>
                {D.usSales.map((s, i) => (
                  <tr key={i} style={{ borderTop: "1px solid var(--border)" }}>
                    <td style={td}>{s.date.slice(5)}</td>
                    <td style={{ ...td, fontWeight: 600 }}>{s.symbol}</td>
                    <td style={{ ...td, textAlign: "right" }} className="num">{s.qty}</td>
                    <td style={{ ...td, textAlign: "right", fontWeight: 700, color: s.plKrw >= 0 ? "var(--up)" : "var(--down)" }} className="num">
                      {fmtSigned(s.plKrw, true)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ) : (
        <div style={{ padding: "0 20px" }}>
          <div className="t-sm muted" style={{ marginBottom: 8 }}>{D.krxSales.length}건</div>
          <div className="card" style={{ padding: 0, overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
              <thead>
                <tr style={{ background: "var(--surface-elevated)" }}>
                  <th style={th}>날짜</th>
                  <th style={th}>종목</th>
                  <th style={{ ...th, textAlign: "right" }}>수량</th>
                  <th style={{ ...th, textAlign: "right" }}>실현손익</th>
                </tr>
              </thead>
              <tbody>
                {D.krxSales.map((s, i) => (
                  <tr key={i} style={{ borderTop: "1px solid var(--border)" }}>
                    <td style={td}>{s.date.slice(5)}</td>
                    <td style={{ ...td, fontWeight: 600 }}>
                      <div>{s.name}</div>
                      <div className="t-xs dim" style={{ textTransform: "none", letterSpacing: 0 }}>{s.ticker}</div>
                    </td>
                    <td style={{ ...td, textAlign: "right" }} className="num">{s.qty}</td>
                    <td style={{ ...td, textAlign: "right", fontWeight: 700, color: s.plKrw >= 0 ? "var(--up)" : "var(--down)" }} className="num">
                      {fmtSigned(s.plKrw, true)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
      <div style={{ height: 24 }} />
    </div>
  );
}

// ── Inline table styles ─────────────────────────────────────
const th = {
  padding: "10px 12px", textAlign: "left",
  fontSize: 11, fontWeight: 700, color: "var(--fg-tertiary)",
  textTransform: "uppercase", letterSpacing: "0.04em",
};
const td = {
  padding: "10px 12px", fontSize: 13, color: "var(--fg)",
};

Object.assign(window, {
  HomeScreen,
  AccountsScreen,
  TaxScreen,
  CashFlowScreen,
  HistoryScreen,
  HoldingDetailScreen,
});
