// DeskStatus.jsx — 부서·담당자별 리스크 현황 (모니터링 탭 공용, 관리자/리스크 부서 뷰).

function DeskStatus({ asset, onOpen }) {
  const people = peopleOf(asset);
  const depts = deptsOf(asset);
  const rows = React.useMemo(() => people.map((p) => {
    const m = summarize(p.pf);
    const lim = dealerLimit(p.emp);
    return { _key: p.emp, emp: p.emp, name: p.name, title: p.title, dept: p.dept, team: p.team,
      value: p.pf.value, ret: m.ret, risk: m.risk, limit: p.pf.limit, util: m.util,
      delta: Math.round(kospiDelta(p.pf)), lim, zc: stopCounts(p.pf) };
  }), [asset]);
  const totalDelta = React.useMemo(() => Math.round(people.reduce((s, p) => s + kospiDelta(p.pf), 0)), [asset]);
  const deptCards = React.useMemo(() => depts.map((d) => {
    const m = summarize(deptPortfolio(d, asset));
    const n = people.filter((p) => p.dept === d).length;
    return { d, n, risk: m.risk, util: m.util, value: m.value };
  }), [asset]);
  const utilPill = (u) => u >= 100 ? 'alert' : u >= 80 ? 'warn' : 'ok';

  return (
    <Card>
      <CardHead title="부서·담당자별 리스크 현황" sub={`${asset} 담당 딜러 전원의 리스크 현황을 한 화면에서 비교해 이상 징후를 빠르게 식별 · 행 클릭으로 포트폴리오 이동`} icon="building"
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {asset === '주식' && <Pill kind="blue">총 델타(KOSPI) {totalDelta.toLocaleString()}억</Pill>}
          <Pill kind="neutral" icon="clock">기준 {FIRM.asOf}</Pill>
        </div>} />
      {/* 부서 요약 */}
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${deptCards.length},1fr)`, gap: 10, padding: '14px 18px', borderBottom: '1px solid ' + T.line }}>
        {deptCards.map((c) => (
          <div key={c.d} style={{ border: '1px solid ' + T.line, borderRadius: 10, padding: '11px 14px', background: T.c50, display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 32, height: 32, borderRadius: 8, background: T.blueSurface, display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.blue, flex: 'none' }}><Icon name="building" size={16} /></div>
            <div style={{ minWidth: 0, textAlign: 'left' }}>
              <div style={{ fontFamily: T.font, fontWeight: 700, fontSize: 13.5, color: T.c900, whiteSpace: 'nowrap' }}>{c.d} <span style={{ fontWeight: 500, fontSize: 11, color: T.c400 }}>· {c.n}명</span></div>
              <div style={{ fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c500, marginTop: 2, whiteSpace: 'nowrap' }}>위험액 <b className="num" style={{ color: T.c800 }}>{Math.round(c.risk).toLocaleString()}억</b> · 평가 {fmtEok(c.value)}</div>
            </div>
            <div style={{ marginLeft: 'auto', flex: 'none' }}><Pill kind={utilPill(c.util)} small dot>{c.util.toFixed(0)}%</Pill></div>
          </div>))}
      </div>
      <DataTable dense initialSort={{ k: 'util', dir: 'desc' }} onRow={onOpen ? (r) => onOpen({ emp: r.emp }) : undefined}
        rows={rows}
        cols={[
        { k: 'name', t: '담당자', w: '15%', render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9 }}>
            <span style={{ width: 26, height: 26, borderRadius: 999, background: T.c150, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', color: T.c600, fontFamily: T.font, fontWeight: 700, fontSize: 11 }}>{r.name[0]}</span>
            <span style={{ fontWeight: 700, color: T.c900 }}>{r.name} <span style={{ fontWeight: 500, fontSize: 10.5, color: T.c400 }}>{r.title}</span></span></span> },
        { k: 'dept', t: '부서 · 팀', w: '20%', render: (r) => <span style={{ color: T.c500 }}>{r.dept} · {r.team}</span> },
        { k: 'emp', t: '사번', render: (r) => <span className="mono" style={{ fontFamily: T.mono, fontSize: 10.5, color: T.c400 }}>{r.emp}</span> },
        { k: 'value', t: '평가액', num: true, render: (r) => <span className="num" style={{ fontWeight: 600, color: T.c800 }}>{r.value.toLocaleString()}억</span>, sortVal: (r) => r.value },
        { k: 'ret', t: '수익률(연)', num: true, render: (r) => <Delta v={r.ret} suffix="%" digits={1} size={12} />, sortVal: (r) => r.ret },
        { k: 'risk', t: '위험액(CVaR)', num: true, render: (r) => <b className="num" style={{ color: T.c900 }}>{Math.round(r.risk).toLocaleString()}억</b>, sortVal: (r) => r.risk },
        ...(asset === '주식' ? [
        { k: 'delta', t: '델타(KOSPI)', num: true, render: (r) => <b className="num" style={{ color: T.c800 }}>{r.delta.toLocaleString()}억</b>, sortVal: (r) => r.delta }] : []),
        { k: 'stop', t: '손절 구간 도달', num: true, render: (r) => {const f = r.zc[1] + r.zc[2] + r.zc[3] + r.zc[4];
            if (!f) return <Pill kind="ok" small dot>정상</Pill>;
            return <span style={{ display: 'inline-flex', gap: 4, justifyContent: 'flex-end' }}>{STOP_ZONES.slice(1).filter((z) => r.zc[z.v] > 0).map((z) => <Pill key={z.v} kind={z.kind} small>{z.l} {r.zc[z.v]}</Pill>)}</span>;},
          sortVal: (r) => r.zc[4] * 1000 + r.zc[3] * 100 + r.zc[2] * 10 + r.zc[1] },
        { k: 'sa', t: 'SA 한도', num: true, render: (r) => r.lim ? <span className="num" style={{ color: limUtil(r.lim.sa) >= 100 ? T.alert : limUtil(r.lim.sa) >= 80 ? T.warn : T.c600 }}>{r.lim.sa[0]}/{r.lim.sa[1]}억 <span style={{ fontSize: 11, color: T.c400 }}>({limUtil(r.lim.sa).toFixed(0)}%)</span></span> : <span style={{ color: T.c300 }}>—</span>, sortVal: (r) => r.lim ? limUtil(r.lim.sa) : 0 },
        { k: 'inv', t: '투자한도', num: true, render: (r) => r.lim ? <span className="num" style={{ color: limUtil(r.lim.invest) >= 100 ? T.alert : limUtil(r.lim.invest) >= 80 ? T.warn : T.c600 }}>{limUtil(r.lim.invest).toFixed(0)}%</span> : <span style={{ color: T.c300 }}>—</span>, sortVal: (r) => r.lim ? limUtil(r.lim.invest) : 0 },
        ...(asset === '주식' ? [
        { k: 'ratio', t: '비율한도(시총)', num: true, render: (r) => r.lim && r.lim.ratio ? <span className="num" style={{ color: (r.lim.ratio.max / r.lim.ratio.cap * 100) >= 100 ? T.alert : (r.lim.ratio.max / r.lim.ratio.cap * 100) >= 80 ? T.warn : T.c600 }}>{r.lim.ratio.max.toFixed(2)}/{r.lim.ratio.cap.toFixed(1)}%</span> : <span style={{ color: T.c300 }}>—</span>, sortVal: (r) => r.lim && r.lim.ratio ? r.lim.ratio.max / r.lim.ratio.cap : 0 }] : []),
        { k: 'util', t: '한도 소진율', num: true, render: (r) => <span style={{ display: 'inline-flex', alignItems: 'center', gap: 9, justifyContent: 'flex-end' }}>
            <span style={{ width: 72 }}><LimitMeter pct={r.util} h={7} /></span>
            <b className="num" style={{ width: 46, textAlign: 'right', color: r.util >= 100 ? T.alert : r.util >= 80 ? T.warn : T.c800 }}>{r.util.toFixed(1)}%</b></span>, sortVal: (r) => r.util },
        { k: 'st', t: '상태', w: 86, render: (r) => <Pill kind={utilPill(r.util)} small dot>{r.util >= 100 ? '한도 초과' : r.util >= 80 ? '한도 임박' : '정상'}</Pill>, sortVal: (r) => -r.util }]
        } />
    </Card>);
}
Object.assign(window, { DeskStatus });
