// Bonds.jsx — 채권 메인.
const DOM_COLORS = { '국채': '#0A4FA3', '공사·공단채': '#00A0E0', '특수채': '#6D5BD0', '금융채(은행채)': '#11865B' };
const COUNTRY_COLORS = ['#0A4FA3', '#00A0E0', '#6D5BD0', '#11865B', '#E0922A', '#C8363C', '#4F6272', '#8B5CF6', '#0E8C8C'];

function fmtMat(d) {return d ? d.replace(/-/g, '.') : '—';}
function ddayMat(d) {if (!d) return null;return Math.round((new Date(d) - new Date('2026-06-04')) / 86400000);}

function Bonds({ openDetail }) {
  const p = PORTFOLIO.bond;
  const [q, setQ] = React.useState('');
  const [region, setRegion] = React.useState('전체');
  const [status, setStatus] = React.useState('전체');

  const domComp = React.useMemo(() => Object.entries(DOM_COMP).sort((a, b) => b[1] - a[1]).
  map(([label, value]) => ({ label: label.replace('(은행채)', ''), value, color: DOM_COLORS[label] || '#94A3B8' })), []);
  const forComp = React.useMemo(() => Object.entries(FOR_COMP).sort((a, b) => b[1] - a[1]).
  map(([label, value], i) => ({ label, value, color: COUNTRY_COLORS[i % COUNTRY_COLORS.length] })), []);
  const domHold = Object.values(DOM_COMP).reduce((s, v) => s + v, 0);
  const forHold = Object.values(FOR_COMP).reduce((s, v) => s + v, 0);
  const domN = BONDS.filter((b) => !b.foreign).length,forN = BONDS.filter((b) => b.foreign).length;

  const statusCounts = { 전체: BONDS.length, 정상: BONDS.filter((b) => b.status === '정상').length, 유보: BONDS.filter((b) => b.status === '유보').length, 주의: BONDS.filter((b) => b.status === '주의').length, 위험: BONDS.filter((b) => b.status === '위험').length };

  const rows = BONDS.filter((b) => {
    if (region === '국내' && b.foreign) return false;
    if (region === '해외' && !b.foreign) return false;
    if (status !== '전체' && b.status !== status) return false;
    if (q) {const s = q.toLowerCase();if (!(b.name.toLowerCase().includes(s) || b.isin.toLowerCase().includes(s) || String(b.ledger).toLowerCase().includes(s))) return false;}
    return true;
  }).map((b) => ({ ...b, _key: b.isin, dday: ddayMat(b.maturity), item: { asset: '채권', isin: b.isin, ledger: b.ledger, name: b.name, ccy: b.ccy, type: b.cat, cvar: b.cvar, dod: b.dod, status: b.status, pending: b.pending, bond: b } }));

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <PortfolioHero p={p} retLabel="포트폴리오 수익률(YTM)" />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'stretch' }}>
        <Card style={{ display: 'flex', flexDirection: 'column' }}>
          <CardHead title="국내채권 구성" sub="채권 유형별 보유 비중" icon="building"
          right={<RegTag>{domN}종 · {(domHold / 10000).toFixed(1)}조</RegTag>} />
          <div style={{ padding: '18px 20px 20px', flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <Donut data={domComp} size={168} thick={25} centerTop="국내" centerBig={domN} unit="종" />
          </div>
        </Card>
        <Card style={{ display: 'flex', flexDirection: 'column' }}>
          <CardHead title="해외채권 구성" sub="국가별 보유 비중" icon="globe"
          right={<RegTag>{forN}종 · {(forHold / 10000).toFixed(1)}조</RegTag>} />
          <div style={{ padding: '18px 20px 20px', flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            <Donut data={forComp} size={168} thick={25} centerTop="해외" centerBig={forN} unit="종" />
          </div>
        </Card>
      </div>

      <Card>
        <CardHead title="보유 채권" sub={`국내 ${domN}종 · 해외 ${forN}종 · 총 ${BONDS.length}종`} icon="bond"
        right={<Search value={q} onChange={setQ} placeholder="종목명·ISIN·원장번호" w={236} />} />
        <div style={{ padding: '12px 16px', borderBottom: '1px solid ' + T.line, display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
          <Segmented options={['전체', '국내', '해외']} value={region} onChange={setRegion} size="sm" />
          <div style={{ width: 1, height: 22, background: T.line }} />
          <Chips value={status} onChange={setStatus} options={[
          { v: '전체', l: '전체', count: statusCounts.전체 }, { v: '위험', l: '위험', count: statusCounts.위험 }, { v: '주의', l: '주의', count: statusCounts.주의 }, { v: '유보', l: '유보', count: statusCounts.유보 }, { v: '정상', l: '정상', count: statusCounts.정상 }]} />
          <span style={{ marginLeft: 'auto', fontFamily: T.font, fontWeight: 500, fontSize: 11.5, color: T.c400 }}>{rows.length}종 표시</span>
        </div>
        <DataTable dense onRow={(r) => openDetail(r.item)}
        initialSort={{ k: 'cvar', dir: 'desc' }}
        rows={rows} maxH={560}
        cols={[
        { 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: '20%', render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontWeight: 600, color: T.c900 }}>{r.foreign && <Icon name="globe" size={12} color={T.c400} />}{r.name}</span> },
        { k: 'ccy', t: '통화', w: 54, render: (r) => <span style={{ color: T.c500, fontWeight: 600 }}>{r.ccy}</span> },
        { k: 'cat', t: '유형', render: (r) => <span style={{ color: T.c500 }}>{r.foreign ? `외화채·${r.country}` : r.cat}</span>, sortVal: (r) => r.cat },
        { k: 'maturity', t: '만기', render: (r) => {const dd = r.dday;return <span style={{ color: T.c600 }}><span className="num">{fmtMat(r.maturity)}</span> {dd != null && (dd >= 0 ?
              <span style={{ fontSize: 10.5, color: dd < 90 ? T.warn : T.c400 }}>D-{dd}</span> :
              <span style={{ fontSize: 10.5, color: T.c300 }}>경과</span>)}</span>;}, sortVal: (r) => r.maturity },
        { 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 : r.cvar >= 0.06 ? T.warn : 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: 72, render: (r) => <StatusPill status={r.status} small />, sortVal: (r) => ({ 위험: 0, 주의: 1, 유보: 2 })[r.status] ?? 3 }]
        } />
      </Card>
    </div>);

}
Object.assign(window, { Bonds, fmtMat, ddayMat, DOM_COLORS, COUNTRY_COLORS });
