// EquityFactor.jsx — 주식 리스크 요인 분석: 국가 → 섹터 → 종목 탑다운 기여 분해.

// 색상 헬퍼
function efCountryColor(c, i) { return COUNTRY_HUE[c] || PAL[i % PAL.length]; }

// ── 탑다운 요인 분석 섹션 (주식 포트폴리오 관리 내) ──
function EquityFactorSection({ pf }) {
  const [country, setCountry] = React.useState('전체');
  const m = summarize(pf);
  const hc = React.useMemo(() => holdContribs(pf), [pf]);
  const byCountry = React.useMemo(() => groupContribs(pf, (u) => u.country), [pf]);
  React.useEffect(() => { if (country !== '전체' && !byCountry.some((c) => c.key === country)) setCountry('전체'); }, [pf]);

  const scoped = country === '전체' ? hc : hc.filter((r) => r.country === country);
  const scopedAmt = scoped.reduce((s, r) => s + r.amt, 0);
  // 섹터별 (선택 국가 범위 내)
  const bySector = React.useMemo(() => {
    const g = {};
    scoped.forEach((r) => { if (!g[r.sector]) g[r.sector] = { key: r.sector, amt: 0, w: 0 }; g[r.sector].amt += r.amt; g[r.sector].w += r.w; });
    return Object.values(g).sort((a, b) => b.amt - a.amt);
  }, [pf, country]);

  return (
    <Card>
      <CardHead title="리스크 요인 분석" sub="리스크가 집중된 국가·섹터·종목을 한눈에 파악해 헤징 대상을 선별" icon="layers" reg="기여 위험액 합 = 전체 CVaR" />
      <div style={{ padding: '18px 22px 22px', display: 'flex', flexDirection: 'column', gap: 18 }}>

        {/* ① 국가별 리스크 현황 */}
        <div>
          <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 10 }}>
            <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c700 }}>① 국가별 리스크 기여도</span>
            <span className="num" style={{ marginLeft: 'auto', fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c400 }}>전체 위험액 {Math.round(m.risk).toLocaleString()}억</span>
          </div>
          <div style={{ display: 'flex', height: 16, borderRadius: 8, overflow: 'hidden', background: T.c150 }}>
            {byCountry.map((c, i) => <div key={c.key} style={{ width: c.frac * 100 + '%', background: efCountryColor(c.key, i), opacity: country === '전체' || country === c.key ? 1 : .28, transition: 'opacity .15s' }} title={c.key} />)}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Math.min(byCountry.length + 1, 6)}, 1fr)`, gap: 8, marginTop: 10 }}>
            <button onClick={() => setCountry('전체')} style={{ textAlign: 'left', border: '1.5px solid ' + (country === '전체' ? T.blue : T.line), background: country === '전체' ? T.blueSurface : T.white, borderRadius: 10, padding: '10px 12px', cursor: 'pointer' }}>
              <div style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12, color: country === '전체' ? T.blue600 : T.c800 }}>전체</div>
              <div className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 17, color: T.c900, marginTop: 4 }}>{Math.round(m.risk).toLocaleString()}<span style={{ fontSize: 10.5, fontWeight: 600, color: T.c400 }}>억</span></div>
              <div style={{ fontFamily: T.font, fontWeight: 500, fontSize: 10.5, color: T.c400, marginTop: 2 }}>{pf.holds.length}종목 · 100%</div>
            </button>
            {byCountry.map((c, i) => { const on = country === c.key;
              return <button key={c.key} onClick={() => setCountry(on ? '전체' : c.key)} style={{ textAlign: 'left', border: '1.5px solid ' + (on ? T.blue : T.line), background: on ? T.blueSurface : T.white, borderRadius: 10, padding: '10px 12px', cursor: 'pointer' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 3, background: efCountryColor(c.key, i), flex: 'none' }} />
                  <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12, color: on ? T.blue600 : T.c800 }}>{c.key}</span>
                </div>
                <div className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 17, color: T.c900, marginTop: 4 }}>{Math.round(c.amt).toLocaleString()}<span style={{ fontSize: 10.5, fontWeight: 600, color: T.c400 }}>억</span></div>
                <div style={{ fontFamily: T.font, fontWeight: 500, fontSize: 10.5, color: T.c400, marginTop: 2 }}>기여 {(c.frac * 100).toFixed(1)}% · 비중 {c.w.toFixed(1)}%</div>
              </button>; })}
          </div>
        </div>

        {/* ② 섹터별 + ③ 종목별 */}
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1.35fr)', gap: 18, alignItems: 'start' }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 10 }}>
              <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c700 }}>② 섹터별 리스크 기여도</span>
              <span style={{ marginLeft: 'auto', fontFamily: T.font, fontWeight: 600, fontSize: 11, color: country === '전체' ? T.c400 : T.blue }}>{country === '전체' ? '전체 국가' : country + ' 범위'}</span>
            </div>
            <HBars data={bySector.map((s) => ({ label: s.key, value: Math.round(s.amt), color: SECTOR_HUE[s.key] || T.blue, sub: `비중 ${s.w.toFixed(1)}% · 기여 ${(s.amt / (scopedAmt || 1) * 100).toFixed(1)}%` }))} unit="억" />
          </div>
          <div>
            <div style={{ display: 'flex', alignItems: 'baseline', marginBottom: 10 }}>
              <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c700 }}>③ 종목별 리스크 기여도</span>
              <span className="num" style={{ marginLeft: 'auto', fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c400 }}>{scoped.length}종목 · 기여 위험액 {Math.round(scopedAmt).toLocaleString()}억</span>
            </div>
            <div style={{ border: '1px solid ' + T.line, borderRadius: 10, overflow: 'hidden' }}>
              <DataTable dense maxH={330} initialSort={{ k: 'amt', dir: 'desc' }}
                rows={scoped.map((r) => ({ ...r, _key: r.id }))}
                cols={[
                  { k: 'name', t: '종목', w: '24%', render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontWeight: 700, color: T.c900 }}><span style={{ width: 7, height: 7, borderRadius: 9, background: SECTOR_HUE[r.sector] || T.c400 }} />{r.name}</span> },
                  { k: 'country', t: '국가', w: 62, render: (r) => <span style={{ color: T.c500 }}>{r.country}</span> },
                  { k: 'sector', t: '섹터', render: (r) => <span style={{ color: T.c500 }}>{r.sector}</span> },
                  { k: 'w', t: '비중', num: true, render: (r) => <span className="num" style={{ color: T.c600 }}>{r.w.toFixed(1)}%</span>, sortVal: (r) => r.w },
                  { k: 'amt', t: '기여 위험액', num: true, render: (r) => <b className="num" style={{ color: T.c900 }}>{Math.round(r.amt).toLocaleString()}억</b>, sortVal: (r) => r.amt },
                  { k: 'frac', t: '기여율', num: true, render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8, justifyContent: 'flex-end' }}><MiniBar pct={r.frac * 100 * 2.2} color={r.frac > 0.2 ? T.alert : r.frac > 0.12 ? T.warn : T.c400} w={52} /><span className="num" style={{ color: T.c700, width: 42, textAlign: 'right', fontWeight: 700 }}>{(r.frac * 100).toFixed(1)}%</span></span>, sortVal: (r) => r.frac },
                ]} />
            </div>
          </div>
        </div>
      </div>
    </Card>);
}

// ── 모니터링(주식) 탭용 하이라이트: 국가·섹터·종목 Top 기여 요약 ──
function EquityFactorHighlight({ onMore }) {
  const pf = React.useMemo(() => firmPortfolio('주식'), []);
  const m = summarize(pf);
  const byCountry = groupContribs(pf, (u) => u.country).slice(0, 3);
  const bySector = groupContribs(pf, (u) => u.sector).slice(0, 3);
  const byStock = holdContribs(pf).slice(0, 3);
  const Col = ({ title, rows, colorOf }) => (
    <div style={{ flex: 1, minWidth: 0 }}>
      <div style={{ fontFamily: T.font, fontWeight: 700, fontSize: 11.5, color: T.c500, marginBottom: 8, textAlign: 'left' }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column' }}>
        {rows.map((r, i) =>
          <div key={r.key} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6.5px 0', borderBottom: i < rows.length - 1 ? '1px solid ' + T.c150 : 'none' }}>
            <span className="num" style={{ fontFamily: T.font, fontWeight: 700, fontSize: 10.5, color: T.c400, width: 12 }}>{i + 1}</span>
            <span style={{ width: 8, height: 8, borderRadius: 3, background: colorOf(r, i), flex: 'none' }} />
            <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.key}</span>
            <span className="num" style={{ marginLeft: 'auto', fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c900 }}>{(r.frac * 100).toFixed(0)}%</span>
          </div>)}
      </div>
    </div>);
  return (
    <Card>
      <CardHead title="리스크 요인 하이라이트" sub="트레이딩 데스크 주식 포트폴리오 기준 · 국가/섹터/종목 기여 Top 3" icon="layers"
        right={<Btn variant="ghost" size="sm" iconR="chevRight" onClick={onMore}>주식 포트폴리오에서 상세 분석</Btn>} />
      <div style={{ padding: '14px 22px 16px', display: 'flex', gap: 0, alignItems: 'stretch' }}>
        <Col title="국가별 기여" rows={byCountry} colorOf={(r, i) => efCountryColor(r.key, i)} />
        <div style={{ width: 1, background: T.line, margin: '0 20px' }} />
        <Col title="섹터별 기여" rows={bySector} colorOf={(r) => SECTOR_HUE[r.key] || T.blue} />
        <div style={{ width: 1, background: T.line, margin: '0 20px' }} />
        <Col title="종목별 기여" rows={byStock.map((r) => ({ key: r.name, frac: r.frac, sector: r.sector }))} colorOf={(r) => SECTOR_HUE[r.sector] || T.blue} />
        <div style={{ width: 1, background: T.line, margin: '0 20px' }} />
        <div style={{ flex: .9, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 4 }}>
          <div style={{ fontFamily: T.font, fontWeight: 600, fontSize: 11, color: T.c500, textAlign: 'left' }}>데스크 주식 위험액 (CVaR)</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
            <span className="num" style={{ fontFamily: T.font, fontWeight: 800, fontSize: 24, color: T.c900, letterSpacing: '-.02em' }}>{Math.round(m.risk).toLocaleString()}</span>
            <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12, color: T.c400 }}>억</span>
          </div>
          <div style={{ fontFamily: T.font, fontWeight: 500, fontSize: 10.5, color: T.c400, textAlign: 'left' }}>평가액 {fmtEok(pf.value)} · 담당 {peopleOf('주식').length}명</div>
        </div>
      </div>
    </Card>);
}

Object.assign(window, { EquityFactorSection, EquityFactorHighlight, efCountryColor });
