// Main.jsx — 종합 대시보드 (메인).
// 부문 = 조직 부문(투자금융부·프로젝트금융부·기업고객부)
const DEPT_COLORS = {};(typeof DEPTS !== 'undefined' ? DEPTS : []).forEach((d) => {DEPT_COLORS[d.name] = d.color;});
const SECTOR_COLORS = DEPT_COLORS; // alias kept for legend lookups

function useDeptRisk() {
  return React.useMemo(() => DEPTS.map((d) => ({ key: d.name, label: d.name, value: d.risk, hold: d.hold, intensity: d.intensity, color: d.color })).
  sort((a, b) => b.value - a.value), []);
}

function HeroRisk({ deltaAmt, deltaPct, expand }) {
  if (!expand) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 4 }}>
        <div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 12, color: T.c500, letterSpacing: '.02em' }}>전체 위험액 (CVaR 99%, 1일)</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 7 }}>
          <span className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 38, color: T.c900, letterSpacing: '-.02em' }}>{KPI.totalRisk.toLocaleString()}</span>
          <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 16, color: T.c400 }}>억원</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
          <Delta v={deltaPct} suffix="%" digits={1} size={13} />
          <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 12, color: T.c500 }}>전일대비 {deltaAmt > 0 ? '+' : ''}{deltaAmt.toLocaleString()}억</span>
        </div>
        <div style={{ height: 1, background: T.line, margin: '12px 0 10px' }} />
        <div style={{ display: 'flex', gap: 18 }}>
          <div><div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500 }}>보유 평가액</div>
            <div className="num" style={{ fontFamily: T.font, fontWeight: 700, fontSize: 17, color: T.c800, marginTop: 3 }}>{(KPI.totalHold / 10000).toFixed(1)}<span style={{ fontSize: 11, color: T.c400, fontWeight: 600 }}> 조원</span></div></div>
          <div style={{ width: 1, background: T.line }} />
          <div><div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500 }}>위험액 비율</div>
            <div className="num" style={{ fontFamily: T.font, fontWeight: 700, fontSize: 17, color: T.c800, marginTop: 3 }}>{(KPI.totalRisk / KPI.totalHold * 100).toFixed(2)}<span style={{ fontSize: 11, color: T.c400, fontWeight: 600 }}> %</span></div></div>
        </div>
      </div>);

  }
  // expanded — fills the card width & height
  const LIMIT = 52000;
  const used = +(KPI.totalRisk / LIMIT * 100).toFixed(1);
  const total = DEPTS.reduce((s, d) => s + d.risk, 0);
  const stats = [
  { k: '보유 평가액', v: (KPI.totalHold / 10000).toFixed(1), u: '조원' },
  { k: '위험액 비율', v: (KPI.totalRisk / KPI.totalHold * 100).toFixed(2), u: '%' },
  { k: '위험 한도 소진율', v: used.toFixed(1), u: '%', kind: used >= 100 ? 'alert' : used >= 80 ? 'warn' : 'ok' }];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', gap: 20 }}>
      <div>
        <div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 12.5, color: T.c500, letterSpacing: '.02em', textAlign: "left" }}>전체 위험액
</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
          <span className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 46, color: T.c900, letterSpacing: '-.03em', lineHeight: 1 }}>{KPI.totalRisk.toLocaleString()}</span>
          <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 18, color: T.c400 }}>억원</span>
          <span style={{ marginLeft: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Delta v={deltaPct} suffix="%" digits={1} size={14} />
            <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 12.5, color: T.c500 }}>전일대비 {deltaAmt > 0 ? '+' : ''}{deltaAmt.toLocaleString()}억</span>
          </span>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        {stats.map((s, i) => <React.Fragment key={s.k}>
            {i > 0 && <div style={{ width: 1, alignSelf: 'stretch', background: T.line }} />}
            <div style={{ flex: 1, paddingLeft: i > 0 ? 18 : 0 }}>
              <div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500, whiteSpace: 'nowrap' }}>{s.k}</div>
              <div className="num" style={{ fontFamily: T.font, fontWeight: 700, fontSize: 21, color: s.kind ? STATUS[s.kind].fg : T.c800, marginTop: 5 }}>{s.v}<span style={{ fontSize: 11.5, color: T.c400, fontWeight: 600 }}> {s.u}</span></div>
            </div>
          </React.Fragment>
        )}
      </div>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 11, alignItems: "stretch", justifyContent: "center" }}>
        <div style={{ display: 'flex', alignItems: 'baseline' }}>
          <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c700 }}>부문별 위험액 분포</span>
          <span style={{ marginLeft: 'auto', fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c400 }}>합계 {total.toLocaleString()}억</span>
        </div>
        <div style={{ display: 'flex', height: 16, borderRadius: 8, overflow: 'hidden', background: T.c150 }}>
          {DEPTS.map((d) => <div key={d.name} style={{ width: d.risk / total * 100 + '%', background: d.color }} title={d.name} />)}
        </div>
        <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap' }}>
          {DEPTS.map((d) =>
          <div key={d.name} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
              <span style={{ width: 9, height: 9, borderRadius: 3, background: d.color, flex: 'none' }} />
              <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 12, color: T.c600 }}>{d.name}</span>
              <span className="num" style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c900 }}>{d.risk.toLocaleString()}억</span>
              <span style={{ fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c400 }}>{(d.risk / total * 100).toFixed(1)}%</span>
            </div>
          )}
        </div>
      </div>
    </div>);

}

function CountCards({ vertical }) {
  const cards = [
  { label: '전체 보유 종목', value: KPI.accounts, unit: '종목', icon: 'briefcase', kind: 'neutral', sub: `정상 ${KPI.normal} · 채권 ${BONDS.length} · 주식 ${STOCKS.length}` },
  { label: '유보 종목', value: KPI.jubo, unit: '종목', icon: 'flag', kind: 'neutral', sub: '-15% 이상 손실 발생' },
  { label: '주의 종목', value: KPI.juui, unit: '종목', icon: 'alert', kind: 'warn', sub: '-12% 이상 손실 발생' },
  { label: '위험 종목', value: KPI.danger, unit: '종목', icon: 'alert', kind: 'alert', sub: '매도 권장 신호 발생' }];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: vertical ? '1fr' : '1fr 1fr 1fr 1fr', gap: 12 }}>
      {cards.map((c) => {const s = STATUS[c.kind];
        return <Card key={c.label} pad="16px 18px">
          <div style={{ display: 'flex', alignItems: 'center', gap: "30px", justifyContent: "center" }}>
            <div style={{ flex: 'none', display: 'flex', alignItems: 'baseline', gap: 4 }}>
              <span className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 30, color: c.kind === 'neutral' ? T.c900 : s.fg, letterSpacing: '-.02em' }}>{c.value}</span>
              <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 13, color: T.c400 }}>{c.unit}</span>
            </div>
            <div style={{ width: 1, alignSelf: 'stretch', background: T.line, margin: '2px 0' }} />
            <div style={{ minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 4 }}>
              <div style={{ fontFamily: T.font, fontWeight: 700, fontSize: 13, color: T.c700 }}>{c.label}</div>
              <div style={{ fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c400, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{c.sub}</div>
            </div>
          </div>
        </Card>;
      })}
    </div>);

}

function RiskViz({ mode, sectors }) {
  const total = sectors.reduce((s, d) => s + d.value, 0);
  if (mode === 'gauge') {
    const LIMIT = 52000; // 위험액 한도(억)
    const pct = +(total / LIMIT * 100).toFixed(1);
    return (
      <div style={{ padding: '14px 18px 18px' }}>
        <Gauge value={pct} min={0} max={120} threshold={100} okMin={0} warnMin={80} unit="%" size={236} />
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 2 }}>
          <Pill kind={pct >= 100 ? 'alert' : pct >= 80 ? 'warn' : 'ok'} dot>{pct >= 100 ? '한도 초과' : pct >= 80 ? '한도 임박' : '한도 내 정상'}</Pill>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14, padding: '0 8px' }}>
          <div><div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500 }}>위험액 한도</div><div className="num" style={{ fontFamily: T.font, fontWeight: 700, fontSize: 15, color: T.c800 }}>{LIMIT.toLocaleString()} 억</div></div>
          <div style={{ textAlign: 'right' }}><div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500 }}>한도 잔여</div><div className="num" style={{ fontFamily: T.font, fontWeight: 700, fontSize: 15, color: T.ok }}>{(LIMIT - total).toLocaleString()} 억</div></div>
        </div>
      </div>);

  }
  if (mode === 'heatmap') {
    return (
      <div style={{ padding: '16px 18px 18px' }}>
        <HeatMap data={sectors.map((s) => ({ label: s.label, value: s.value, intensity: s.intensity }))} h={196} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 13 }}>
          <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500 }}>위험강도 낮음</span>
          <div style={{ flex: 1, height: 7, borderRadius: 4, background: 'linear-gradient(90deg,#F8E8E8,#B01E24)' }} />
          <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500 }}>높음</span>
        </div>
      </div>);

  }
  return (
    <div style={{ padding: '18px 20px 20px' }}>
      <HBars data={sectors.map((s) => ({ label: s.label, value: s.value, color: s.color, sub: `${(s.value / total * 100).toFixed(1)}% · 강도 ${(s.intensity * 100).toFixed(2)}%` }))} />
    </div>);

}

// 주요 시장 지표 (전일대비) — 리스크 요인 모니터링
function genSpark(seed, end, vol) {let r = seed >>> 0;const rnd = () => {r = Math.imul(r, 1103515245) + 12345 >>> 0;return r / 4294967296;};const n = 22,arr = new Array(n);let v = end;for (let i = n - 1; i >= 0; i--) {arr[i] = v;v = v * (1 + (rnd() - 0.5) * vol);}return arr;}
const MARKET = [
{ label: '美 국채 10년물', sub: 'UST 10Y', value: '4.28', num: 4.28, unit: '%', delta: 0.03, dunit: '%p', ddig: 2, seed: 11, vol: 0.012 },
{ label: '신용 스프레드', sub: 'IG OAS', value: '92', num: 92, unit: 'bp', delta: 2, dunit: 'bp', ddig: 0, seed: 23, vol: 0.030 },
{ label: '원/달러 환율', sub: 'USD/KRW', value: '1,382.5', num: 1382.5, unit: '원', delta: 4.2, dunit: '원', ddig: 1, seed: 37, vol: 0.006 },
{ label: 'SOFR 금리', sub: 'USD O/N', value: '4.31', num: 4.31, unit: '%', delta: -0.01, dunit: '%p', ddig: 2, seed: 53, vol: 0.008 }];

function MarketIndicators({ cols = 2 }) {
  return (
    <div style={{ flex: 1, padding: '14px 16px 16px', display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, gridAutoRows: '1fr', gap: 12 }}>
      {MARKET.map((m) => {const c = dirColor(m.delta);const series = genSpark(m.seed, m.num, m.vol);
        return (
          <div key={m.label} style={{ border: '1px solid ' + T.line, borderRadius: 10, padding: '12px 14px 8px', background: T.c50, display: 'flex', flexDirection: 'column', gap: 6, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c700, whiteSpace: 'nowrap' }}>{m.label}</span>
              <span style={{ fontFamily: T.mono, fontSize: 9.5, color: T.c400 }}>{m.sub}</span>
              <span style={{ marginLeft: 'auto' }}><Delta v={m.delta} suffix={m.dunit} digits={m.ddig} size={11.5} /></span>
            </div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 3 }}>
              <span className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 22, color: T.c900, letterSpacing: '-.02em' }}>{m.value}</span>
              <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11.5, color: T.c400 }}>{m.unit}</span>
            </div>
            <div style={{ flex: 1, display: 'flex', alignItems: 'flex-end', minHeight: 46 }}>
              <Spark data={series} color={c} full w={240} h={52} style={{ width: '100%' }} />
            </div>
          </div>);
      })}
    </div>);
}

// ── AI 리스크 리포트 (타이핑 생성 애니메이션) ──────────────────────────────
function AIReport({ deltaPct, deltaAmt }) {
  const dir = deltaPct >= 0 ? '증가' : '감소';
  const topDept = DEPTS.slice().sort((a, b) => b.risk - a.risk)[0];
  const topPct = (topDept.risk / DEPTS.reduce((s, d) => s + d.risk, 0) * 100).toFixed(0);

  // 두 단락 텍스트 (plain — bold 태그 없이 타이핑 후 하이라이트 오버레이)
  const PARA1 = `간밤 미국 시장에서는 국채 10년물 금리가 4.28%로 소폭 상승하고 IG 신용 스프레드가 +2bp 확대되며 위험 선호가 다소 위축됐어요. SOFR 단기금리는 4.31%로 안정적이나, 원/달러 환율이 1,382.5원까지 오르며 환 변동성이 재차 확대되는 흐름이에요. 금리 상방 압력과 원화 약세가 동반되면서 보유 채권의 평가손과 해외자산 환산 부담이 함께 커질 수 있는 국면으로, 듀레이션이 긴 외화채권과 신용 민감 종목을 중심으로 시장 리스크가 누적되고 있어요.`;
  const PARA2 = `포트폴리오 전체 위험액은 ${KPI.totalRisk.toLocaleString()}억으로 전일 대비 ${deltaPct >= 0 ? '+' : ''}${deltaPct}% (${deltaAmt > 0 ? '+' : ''}${deltaAmt.toLocaleString()}억) ${dir}했고, 부문별로는 ${topDept.name}의 위험액 비중이 ${topPct}%로 가장 높아 해외채권 변동성에 대한 민감도가 큰 상태예요. 위험 한도 소진율은 73.9% 수준이에요.`;
  const FULL = PARA1 + '\n\n' + PARA2;

  const SPEED = 28; // ms per char
  const [visLen, setVisLen] = React.useState(0);
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    setVisLen(0); setDone(false);
    const id = setInterval(() => {
      setVisLen(n => {
        const next = n + 3; // 3글자씩 진행
        if (next >= FULL.length) { clearInterval(id); setDone(true); return FULL.length; }
        return next;
      });
    }, SPEED);
    return () => clearInterval(id);
  }, []);

  // visible 텍스트 분리 (단락 경계 기준)
  const visible = FULL.slice(0, visLen);
  const p1Visible = visible.slice(0, Math.min(visible.length, PARA1.length));
  const p2Visible = visible.length > PARA1.length + 2
    ? visible.slice(PARA1.length + 2)
    : '';
  const showP2 = visible.length > PARA1.length;
  const cursorInP1 = !showP2 && !done;
  const cursorInP2 = showP2 && !done;

  const Cursor = () => (
    <span style={{ display: 'inline-block', width: 2, height: '1.1em', background: T.blue,
      verticalAlign: 'text-bottom', marginLeft: 1, borderRadius: 1,
      animation: 'ai-blink .6s steps(1) infinite' }} />
  );

  return (
    <Card style={{ display: 'flex', flexDirection: 'column' }}>
      <style>{`@keyframes ai-blink { 0%,49%{opacity:1} 50%,100%{opacity:0} }`}</style>
      <CardHead title="AI 리스크 리포트" sub="시황·포트폴리오 상황 자동 요약" icon="sparkles"
        right={done
          ? <Pill kind="blue" icon="sparkles">AI 생성 완료</Pill>
          : <span style={{ display:'inline-flex', alignItems:'center', gap:6,
              fontFamily:T.font, fontWeight:700, fontSize:11.5, color:T.blue }}>
              <span style={{ display:'inline-block', width:8, height:8, borderRadius:999,
                background:T.blue, animation:'ai-blink .8s steps(1) infinite' }} />
              생성 중...
            </span>}
      />
      <div style={{ padding: '18px 22px 18px', flex: 1, display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* 단락 1 */}
        <p style={{ margin: 0, fontFamily: T.font, fontWeight: 500, fontSize: 13.5, color: T.c700,
          lineHeight: 1.75, textAlign: 'left', wordBreak: 'keep-all', minHeight: '3.5em' }}>
          {p1Visible}{cursorInP1 && <Cursor />}
        </p>

        {/* 구분선 — 단락1 완료 후 등장 */}
        {showP2 && <div style={{ height: 1, background: T.line }} />}

        {/* 단락 2 */}
        {showP2 && (
          <p style={{ margin: 0, fontFamily: T.font, fontWeight: 500, fontSize: 13.5, color: T.c700,
            lineHeight: 1.75, textAlign: 'left', wordBreak: 'keep-all', minHeight: '3.5em' }}>
            {p2Visible}{cursorInP2 && <Cursor />}
          </p>
        )}

        {/* 주의 문구 — 완료 후 등장 */}
        {done && (
          <div style={{ marginTop: 'auto', paddingTop: 4, display: 'flex', alignItems: 'center', gap: 9 }}>
            <Icon name="info" size={14} color={T.c400} />
            <span style={{ fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c400 }}>
              본 리포트는 자동 생성된 참고 자료로, 투자 판단의 근거가 아니에요. · 기준 {FIRM.asOf}
            </span>
          </div>
        )}
      </div>
    </Card>);
}

function Main({ t, openDetail }) {
  const [view, setView] = React.useState(t.trendDefault || '부문별');
  const heroLayout = t.mainLayout !== 'KPI 행형';
  const deltaAmt = Math.round(TREND.total.at(-1) - TREND.total.at(-2));
  const deltaPct = +((TREND.total.at(-1) / TREND.total.at(-2) - 1) * 100).toFixed(1);
  const trendSeries = view === '부문별' ? TREND.dept : TREND.asset;
  const trendColors = view === '부문별' ? DEPT_COLORS : { '해외채권': '#0A4FA3', '국내채권': '#00A0E0', '국내주식': '#E0922A', '해외주식': '#6D5BD0' };

  const flaggedTable =
  <Card>
      <CardHead title="관리 종목 현황" sub="채권: 위험·주의·유보 전체 · 주식: 위험만 표시" icon="flag"
    right={<div style={{ display: 'flex', gap: 6 }}>
      <Pill kind="alert" small dot>위험 {FLAGGED.filter(r=>r.status==='위험').length}</Pill>
      <Pill kind="warn" small dot>주의 {FLAGGED.filter(r=>r.status==='주의').length}</Pill>
      <Pill kind="neutral" small dot>유보 {FLAGGED.filter(r=>r.status==='유보').length}</Pill>
    </div>} />
      <DataTable dense onRow={(r) => openDetail(r)}
    initialSort={null}
    rows={FLAGGED.map((r, i) => ({ ...r, _key: r.isin + i }))}
    cols={[
    { k: 'asset', t: '구분', w: 60, render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontWeight: 600, color: T.c700 }}><Icon name={r.asset === '주식' ? 'trendUp' : 'bond'} size={13} color={T.c400} />{r.asset}</span>, sortVal: (r) => r.asset },
    { k: 'isin', t: 'ISIN', render: (r) => <span className="mono" style={{ fontFamily: T.mono, fontSize: 11, color: T.c500 }}>{r.isin}</span> },
    { k: 'ledger', t: '원장번호', render: (r) => <span className="mono" style={{ fontFamily: T.mono, fontSize: 10.5, color: T.c400 }}>{r.ledger}</span> },
    { k: 'name', t: '종목명', w: '19%', render: (r) => <span style={{ fontWeight: 600, color: T.c900 }}>{r.name}</span> },
    { k: 'ccy', t: '통화', w: 52, render: (r) => <span style={{ color: T.c500 }}>{r.ccy}</span> },
    { k: 'type', t: '유형', render: (r) => <span style={{ color: T.c500 }}>{r.type}</span> },
    { k: 'cvar', t: 'CVaR', num: true, render: (r) => r.pending ? <span style={{ color: T.c400 }}>산출 보류</span> : <b className="num" style={{ color: r.cvar < 0 ? T.down : T.c800 }}>{(r.cvar * 100).toFixed(2)}%</b>, sortVal: (r) => r.cvar == null ? -Infinity : Math.abs(r.cvar) },
    { k: 'dod', t: 'CVaR 전일대비', num: true, render: (r) => r.pending ? <span style={{ color: T.c300 }}>—</span> : <Delta v={r.dod * 100} suffix="%p" digits={2} size={12} />, sortVal: (r) => r.dod == null ? 0 : r.dod },
    { k: 'status', t: '분류', w: 70, render: (r) => <StatusPill status={r.status} small />, sortVal: (r) => ({ 위험: 0, 주의: 1, 유보: 2 })[r.status] ?? 3 },
    { k: 'note', t: '사유', w: '15%', sortable: false, render: (r) => <span style={{ fontFamily: T.font, fontWeight: 500, fontSize: 11.5, color: r.status === '위험' ? T.alert : r.status === '주의' ? T.warn : T.c500, whiteSpace: 'nowrap' }}>{r.note || '—'}</span> }]
    } />
    </Card>;


  const trendCard =
  <Card>
      <CardHead title="위험액 일별 추이" sub={`최근 30영업일 · ${view} 위험액(억원)`} icon="barChart"
    right={<Segmented options={['부문별', '자산별']} value={view} onChange={setView} size="sm" />} />
      <div style={{ padding: '18px 18px 10px' }}>
        <MultiTrend days={TREND.days} series={trendSeries} colors={trendColors} mode={view === '자산별' ? 'stack' : 'line'} unit="억" />
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', marginTop: 6, paddingLeft: 6 }}>
          {Object.keys(trendSeries).map((k) =>
        <span key={k} style={{ display: 'flex', alignItems: 'center', gap: 7, fontFamily: T.font, fontWeight: 600, fontSize: 11.5, color: T.c500 }}>
              <span style={{ width: 14, height: view === '자산별' ? 10 : 3, borderRadius: view === '자산별' ? 2 : 2, background: trendColors[k] }} />{k}</span>
        )}
          <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 6, fontFamily: T.font, fontWeight: 600, fontSize: 11.5, color: T.warn }}>
            <Icon name="alert" size={13} /> {view === '부문별' ? '기업고객부 위험액 상승 (해외채권 비중 영향)' : '해외채권 위험액 상승 (외화채 변동 영향)'}</span>
        </div>
      </div>
    </Card>;


  const marketCard =
  <Card style={{ display: 'flex', flexDirection: 'column' }}>
      <CardHead title="주요 시장 지표 변화" sub="리스크 요인 모니터링 · 전일대비" icon="trendUp" right={<Pill kind="neutral" icon="clock">5분 지연</Pill>} />
      <MarketIndicators cols={4} />
    </Card>;


  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      {/* banner */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 13, background: T.white, border: '1px solid ' + T.line, borderRadius: 12, padding: '11px 18px', boxShadow: T.shCard || '0 1px 2px rgba(15,23,34,.04)' }}>
        <Pill kind="warn" dot>점검 권고</Pill>
        <span style={{ fontFamily: T.font, fontWeight: 500, fontSize: 13, color: T.c600 }}>
          전체 위험액은 전일 대비 <b style={{ color: deltaPct >= 0 ? T.up : T.down }}>{deltaPct >= 0 ? '+' : ''}{deltaPct}% ({deltaAmt > 0 ? '+' : ''}{deltaAmt.toLocaleString()}억)</b> {deltaPct >= 0 ? '증가' : '감소'}했어요. 현재 <b style={{ color: T.alert }}>위험 {KPI.danger}건</b> · <b style={{ color: T.warn }}>주의 {KPI.juui}건</b> · <b style={{ color: T.c600 }}>유보 {KPI.jubo}건</b>이 분류되어 있어요.
        </span>
        <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
          <Pill kind="neutral" icon="clock">기준 {FIRM.asOf}</Pill>
          <Btn variant="secondary" size="sm" icon="refresh">새로고침</Btn>
        </span>
      </div>

      {heroLayout ?
      <React.Fragment>
          {marketCard}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.1fr', gap: 16, alignItems: 'stretch' }}>
            <Card style={{ display: 'flex', flexDirection: 'column' }}>
              <CardHead title="위험액 현황" sub={FIRM.basis} icon="won" />
              <div style={{ padding: '18px 22px 20px', flex: 1, display: 'flex' }}><HeroRisk deltaAmt={deltaAmt} deltaPct={deltaPct} expand /></div>
            </Card>
            <AIReport deltaPct={deltaPct} deltaAmt={deltaAmt} />
          </div>
          <CountCards />
          {trendCard}
          {flaggedTable}
        </React.Fragment> :

      <React.Fragment>
          {marketCard}
          <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr 1fr 1fr 1fr', gap: 12 }}>
            <Card pad="15px 18px"><HeroRisk deltaAmt={deltaAmt} deltaPct={deltaPct} /></Card>
            <CountCardsInline />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 16, alignItems: 'start' }}>
            {trendCard}
            <AIReport deltaPct={deltaPct} deltaAmt={deltaAmt} />
          </div>
          {flaggedTable}
        </React.Fragment>
      }
    </div>);

}

// KPI-row variant: three compact count cards rendered as grid siblings
function CountCardsInline() {
  const cards = [
  { label: '전체 보유 종목', value: KPI.accounts, unit: '종목', icon: 'briefcase', kind: 'neutral', sub: `정상 ${KPI.normal}` },
  { label: '유보 종목', value: KPI.jubo, unit: '종목', icon: 'flag', kind: 'neutral', sub: '-15% 손실' },
  { label: '주의 종목', value: KPI.juui, unit: '종목', icon: 'alert', kind: 'warn', sub: '-12% 손실' },
  { label: '위험 종목', value: KPI.danger, unit: '종목', icon: 'alert', kind: 'alert', sub: '매도 권장' }];

  return cards.map((c) => {const s = STATUS[c.kind];
    return <Card key={c.label} pad="14px 16px" style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 6 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <div style={{ width: 30, height: 30, borderRadius: 8, background: s.bg, border: '1px solid ' + s.line, display: 'flex', alignItems: 'center', justifyContent: 'center', color: s.fg, flex: 'none' }}><Icon name={c.icon} size={16} stroke={2} /></div>
        <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11.5, color: T.c500 }}>{c.label}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 25, color: c.kind === 'neutral' ? T.c900 : s.fg, letterSpacing: '-.02em' }}>{c.value}</span>
        <span style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11.5, color: T.c400 }}>{c.unit} · {c.sub}</span>
      </div>
    </Card>;
  });
}
Object.assign(window, { Main, SECTOR_COLORS });
