// Shell.jsx — IBK 리스크 인사이트 chrome: brand header + tab bar.

function IBKBrand() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
      <div style={{ width: 38, height: 38, borderRadius: 10, background: 'linear-gradient(135deg,#0A4FA3 0%,#003B7E 60%,#072044 100%)', position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 8px rgba(0,59,126,.32)', overflow: 'hidden' }}>
        <span style={{ position: 'absolute', top: -7, right: -7, width: 20, height: 20, borderRadius: 6, background: 'var(--ibk-cyan,#00A0E0)', opacity: .92 }} />
        <span style={{ fontFamily: T.font, fontWeight: 800, fontSize: 14, color: '#fff', letterSpacing: '.01em', position: 'relative', zIndex: 1 }}>IBK</span>
      </div>
      <div style={{ lineHeight: 1.1 }}>
        <div style={{ fontFamily: T.font, fontWeight: 800, fontSize: 15.5, color: T.navy, letterSpacing: '-.01em' }}>리스크 인사이트<span style={{ fontWeight: 600, fontSize: 11.5, color: T.c400, marginLeft: 7, letterSpacing: 0 }}>Risk Insight</span></div>
        <div style={{ fontFamily: T.font, fontWeight: 500, fontSize: 11, color: T.c500, marginTop: 2 }}>IBK 기업은행 · 유가증권 리스크 모니터링</div>
      </div>
    </div>);

}

// ── 전체 검색 오버레이 ─────────────────────────────────────────────────────────
function SearchOverlay({ onSelect, onClose }) {
  const [q, setQ] = React.useState('');
  const inputRef = React.useRef(null);

  React.useEffect(() => { inputRef.current && inputRef.current.focus(); }, []);

  // Esc 닫기
  React.useEffect(() => {
    const h = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);

  const results = React.useMemo(() => {
    const s = q.trim().toLowerCase();
    if (!s) return { stocks: [], bonds: [] };
    const stocks = [
      ...(typeof STOCKS !== 'undefined' ? STOCKS : []),
      ...(typeof STOCK_RECO !== 'undefined' ? STOCK_RECO.map(r => ({
        ticker: r.ticker, name: r.name, sector: r.sector,
        status: (typeof STOCK_RISK_MAP !== 'undefined' && STOCK_RISK_MAP[r.ticker]?.status) || '적정',
        _reco: r,
      })) : []),
    ].filter(s2 => !q || s2.name.toLowerCase().includes(s) || s2.ticker.toLowerCase().includes(s))
     .slice(0, 8);
    const bonds = (typeof BONDS !== 'undefined' ? BONDS : [])
      .filter(b => b.name.toLowerCase().includes(s) || b.isin.toLowerCase().includes(s) ||
                   (b.ledger && b.ledger.toLowerCase().includes(s)))
      .slice(0, 8);
    return { stocks, bonds };
  }, [q]);

  const total = results.stocks.length + results.bonds.length;

  const selectStock = (s) => {
    const item = s._reco ? recoToItem(s._reco) : {
      asset: '주식', isin: s.ticker, name: s.name, ccy: 'KRW',
      type: s.sector, status: s.status,
      cvar: s.risk ? +(s.risk / 100).toFixed(4) : 0.05,
      dod:  s.dod  ? +(s.dod  / 100).toFixed(4) : 0,
      pending: false, stock: s,
    };
    onSelect(item); onClose();
  };
  const selectBond = (b) => {
    onSelect({ 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 });
    onClose();
  };

  const Row = ({ icon, label, sub, badge, onClick }) => (
    <div onClick={onClick} style={{ display:'flex', alignItems:'center', gap:12,
      padding:'9px 16px', cursor:'pointer', borderRadius:8 }}
      onMouseEnter={e=>e.currentTarget.style.background=T.c100}
      onMouseLeave={e=>e.currentTarget.style.background='transparent'}>
      <div style={{ width:32, height:32, borderRadius:8, background:T.c100,
        display:'flex', alignItems:'center', justifyContent:'center', color:T.c500, flex:'none' }}>
        <Icon name={icon} size={16} />
      </div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontFamily:T.font, fontWeight:600, fontSize:13, color:T.c900,
          overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{label}</div>
        <div style={{ fontFamily:T.mono, fontSize:10.5, color:T.c400, marginTop:1 }}>{sub}</div>
      </div>
      {badge && <span style={{ fontFamily:T.font, fontWeight:700, fontSize:10.5,
        color: badge==='위험'?T.alert : badge==='주의'?T.warn : T.c400,
        background: badge==='위험'?T.alertS : badge==='주의'?T.warnS : T.c100,
        border:`1px solid ${badge==='위험'?T.alertL:badge==='주의'?T.warnL:T.c200}`,
        borderRadius:999, padding:'1px 8px' }}>{badge}</span>}
    </div>
  );

  return (
    <div style={{ position:'fixed', inset:0, zIndex:9999, display:'flex', alignItems:'flex-start', justifyContent:'center', paddingTop:72 }}>
      {/* 배경 딤 */}
      <div onClick={onClose} style={{ position:'absolute', inset:0, background:'rgba(15,23,34,.32)', backdropFilter:'blur(2px)' }} />
      {/* 패널 */}
      <div style={{ position:'relative', width:580, background:T.white, borderRadius:14,
        boxShadow:'0 12px 40px rgba(15,23,34,.18), 0 0 0 1px '+T.line,
        display:'flex', flexDirection:'column', overflow:'hidden', maxHeight:'70vh' }}>
        {/* 검색 입력 */}
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'14px 18px',
          borderBottom:'1px solid '+T.line }}>
          <Icon name="search" size={18} color={T.c400} />
          <input ref={inputRef} value={q} onChange={e=>setQ(e.target.value)}
            placeholder="종목명·티커·ISIN 검색..."
            style={{ flex:1, border:0, outline:'none', fontFamily:T.font, fontWeight:500,
              fontSize:14.5, color:T.c900, background:'transparent' }} />
          {q && <button onClick={()=>setQ('')} style={{ border:0, background:'none',
            cursor:'pointer', color:T.c400, display:'flex', padding:2 }}>
            <Icon name="x" size={16} /></button>}
          <kbd style={{ fontFamily:T.mono, fontSize:11, color:T.c400,
            border:'1px solid '+T.c250, borderRadius:5, padding:'2px 7px' }}>ESC</kbd>
        </div>
        {/* 결과 */}
        <div style={{ overflow:'auto', padding:'8px 8px 12px' }}>
          {!q && (
            <div style={{ padding:'28px 0', textAlign:'center',
              fontFamily:T.font, fontWeight:500, fontSize:13, color:T.c400 }}>
              종목명, 티커, ISIN으로 검색하세요
            </div>
          )}
          {q && total === 0 && (
            <div style={{ padding:'28px 0', textAlign:'center',
              fontFamily:T.font, fontWeight:500, fontSize:13, color:T.c400 }}>
              "{q}" 검색 결과가 없어요
            </div>
          )}
          {results.stocks.length > 0 && <>
            <div style={{ padding:'6px 16px 4px', fontFamily:T.font, fontWeight:700,
              fontSize:10.5, color:T.c400, letterSpacing:'.06em', textTransform:'uppercase' }}>
              주식 ({results.stocks.length})
            </div>
            {results.stocks.map(s => <Row key={s.ticker} icon="trendUp"
              label={s.name} sub={s.ticker} badge={s.status}
              onClick={() => selectStock(s)} />)}
          </>}
          {results.bonds.length > 0 && <>
            <div style={{ padding:'10px 16px 4px', fontFamily:T.font, fontWeight:700,
              fontSize:10.5, color:T.c400, letterSpacing:'.06em', textTransform:'uppercase' }}>
              채권 ({results.bonds.length})
            </div>
            {results.bonds.map(b => <Row key={b.isin+b.ledger} icon="bond"
              label={b.name} sub={`${b.isin} · ${b.ccy}`} badge={b.status !== '정상' ? b.status : null}
              onClick={() => selectBond(b)} />)}
          </>}
        </div>
      </div>
    </div>
  );
}

function Header({ onSearch }) {
  const [open, setOpen] = React.useState(false);

  // ⌘K / Ctrl+K 단축키
  React.useEffect(() => {
    const h = (e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); setOpen(true); } };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);

  return (
    <>
    {open && <SearchOverlay onSelect={onSearch} onClose={() => setOpen(false)} />}
    <header style={{ height: 58, flex: 'none', background: 'rgba(255,255,255,.92)', backdropFilter: 'blur(10px)', borderBottom: '1px solid ' + T.line,
      display: 'flex', alignItems: 'center', gap: 16, padding: '0 22px', position: 'sticky', top: 0, zIndex: 30 }}>
      <IBKBrand />
      <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div onClick={() => setOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: 8, background: T.c100, border: '1px solid ' + T.line, borderRadius: 9, padding: '7px 12px', width: 248, cursor: 'pointer' }}>
          <Icon name="search" size={15} color={T.c400} />
          <span style={{ fontFamily: T.font, fontWeight: 500, fontSize: 12.5, color: T.c400, flex: 1 }}>종목명·티커·ISIN 검색</span>
          <span style={{ fontFamily: T.mono, fontSize: 10, color: T.c400, border: '1px solid ' + T.c250, borderRadius: 4, padding: '1px 5px' }}>⌘K</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, background: T.okS, border: '1px solid ' + T.okL, borderRadius: 9, padding: '6px 11px' }}>
          <span style={{ width: 7, height: 7, borderRadius: 999, background: T.ok }} />
          <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 11.5, color: T.ok }}>실시간 </span>
        </div>
        <button style={{ position: 'relative', border: '1px solid ' + T.line, background: T.white, borderRadius: 9, padding: 8, cursor: 'pointer', color: T.c600, display: 'flex' }}>
          <Icon name="bell" size={17} />
          <span style={{ position: 'absolute', top: 6, right: 7, width: 7, height: 7, borderRadius: 999, background: T.alert, border: '1.5px solid #fff' }} />
        </button>
        <div style={{ width: 1, height: 24, background: T.line }} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
          <div style={{ width: 32, height: 32, borderRadius: 999, background: 'linear-gradient(135deg,#0A4FA3,#003B7E)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontFamily: T.font, fontWeight: 700, fontSize: 12 }}>김</div>
          <div style={{ lineHeight: 1.2 }}>
            <div style={{ fontFamily: T.font, fontWeight: 700, fontSize: 12.5, color: T.c800 }}>김진호</div>
            <div style={{ fontFamily: T.font, fontWeight: 500, fontSize: 10.5, color: T.c500 }}>리스크총괄부</div>
          </div>
        </div>
      </div>
    </header>
    </>);

}

function TabBar({ tabs, active, onSelect, onClose }) {
  return (
    <div style={{ flex: 'none', height: 46, background: T.white, borderBottom: '1px solid ' + T.line, display: 'flex', alignItems: 'flex-end', gap: 2, padding: '0 18px', position: 'sticky', top: 58, zIndex: 20, overflowX: 'auto' }}>
      {tabs.map((t) => {const on = t.id === active;const closeable = t.kind === 'detail';
        return (
          <button key={t.id} onClick={() => onSelect(t.id)} style={{ border: 0, background: 'none', cursor: 'pointer', position: 'relative',
            display: 'flex', alignItems: 'center', gap: 8, padding: '0 14px', height: 38, marginBottom: -1,
            borderTopLeftRadius: 9, borderTopRightRadius: 9,
            borderTop: '1px solid ' + (on ? T.line : 'transparent'), borderLeft: '1px solid ' + (on ? T.line : 'transparent'), borderRight: '1px solid ' + (on ? T.line : 'transparent'),
            background: on ? T.white : 'transparent', whiteSpace: 'nowrap' }}>
            {on && <span style={{ position: 'absolute', left: 0, right: 0, top: -1, height: 2.5, background: T.blue, borderRadius: 2 }} />}
            {t.icon && <Icon name={t.icon} size={15} color={on ? T.blue : T.c500} stroke={2} />}
            <span style={{ fontFamily: T.font, fontWeight: on ? 700 : 600, fontSize: 13, color: on ? T.c900 : T.c500 }}>{t.label}</span>
            {t.badge != null && <span style={{ fontFamily: T.font, fontWeight: 700, fontSize: 10.5, color: on ? T.blue : T.c400, background: on ? T.blueSurface : T.c100, borderRadius: 999, padding: '1px 7px' }}>{t.badge}</span>}
            {closeable && <span onClick={(e) => {e.stopPropagation();onClose(t.id);}} style={{ display: 'flex', marginLeft: 2, marginRight: -4, padding: 3, borderRadius: 5, color: T.c400 }}
            onMouseEnter={(e) => {e.currentTarget.style.background = T.c150;e.currentTarget.style.color = T.c700;}}
            onMouseLeave={(e) => {e.currentTarget.style.background = 'transparent';e.currentTarget.style.color = T.c400;}}><Icon name="x" size={13} stroke={2.4} /></span>}
          </button>);

      })}
    </div>);

}

function Shell({ tabs, active, onSelect, onClose, onSearch, children }) {
  return (
    <div style={{ minHeight: '100vh', background: T.c100, display: 'flex', flexDirection: 'column', textAlign: "center" }}>
      <Header onSearch={onSearch} />
      <TabBar tabs={tabs} active={active} onSelect={onSelect} onClose={onClose} />
      <main style={{ flex: 1, padding: '22px 26px 64px', maxWidth: 1440, width: '100%', margin: '0 auto' }}>{children}</main>
      <footer style={{ flex: 'none', borderTop: '1px solid ' + T.line, padding: '14px 26px', display: 'flex', alignItems: 'center', gap: 14, color: T.c400, fontFamily: T.font, fontWeight: 500, fontSize: 11 }}>
        <span style={{ fontWeight: 700, color: T.c500 }}>IBK 기업은행 리스크 인사이트</span>
        <span></span><span></span>
        <span style={{ marginLeft: 'auto' }}>데이터 기준 {FIRM.asOf} · 본 화면은 내부 리스크관리 목적의 시뮬레이션입니다.</span>
      </footer>
    </div>);

}
Object.assign(window, { Shell });
