// App.jsx — tab routing, tweaks, detail-tab management.
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "mainLayout": "히어로형",
  "trendDefault": "부문별"
}/*EDITMODE-END*/;

const BASE_TABS = [
  { id:'main',   kind:'base', label:'종합',   icon:'gauge' },
  { id:'stock',  kind:'base', label:'주식',   icon:'trendUp', badge:STOCKS.length },
  { id:'bond',   kind:'base', label:'채권',   icon:'bond',    badge:BONDS.length },
  { id:'report', kind:'base', label:'보고서', icon:'fileText' },
];

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [details, setDetails] = React.useState([]); // [{id,item}]
  const [active, setActive] = React.useState('main');

  const openDetail = React.useCallback((item)=>{
    const id = 'd:'+item.isin;
    setDetails(ds => ds.some(d=>d.id===id) ? ds : [...ds, { id, item }]);
    setActive(id);
  },[]);
  const closeTab = React.useCallback((id)=>{
    setDetails(ds=>{ const idx=ds.findIndex(d=>d.id===id); const next=ds.filter(d=>d.id!==id);
      setActive(cur=>{ if(cur!==id) return cur; const fallback = next[idx]||next[idx-1]; return fallback?fallback.id:'bond'; });
      return next; });
  },[]);

  const tabs = [...BASE_TABS, ...details.map(d=>({ id:d.id, kind:'detail', label:d.item.name, icon:d.item.asset==='주식'?'trendUp':'bond' }))];
  const activeDetail = details.find(d=>d.id===active);

  let content;
  if(active==='main') content = <Main t={t} openDetail={openDetail}/>;
  else if(active==='stock') content = <Stocks openDetail={openDetail}/>;
  else if(active==='bond') content = <Bonds openDetail={openDetail}/>;
  else if(active==='report') content = <Report/>;
  else if(activeDetail) content = <Detail item={activeDetail.item} openDetail={openDetail}/>;
  else content = <Main t={t} openDetail={openDetail}/>;

  return (
    <React.Fragment>
      <Shell tabs={tabs} active={active} onSelect={setActive} onClose={closeTab} onSearch={openDetail}>{content}</Shell>
      <TweaksPanel>
        <TweakSection label="메인 대시보드"/>
        <TweakRadio label="레이아웃" value={t.mainLayout} options={['히어로형','KPI 행형']} onChange={v=>setTweak('mainLayout',v)}/>
        <TweakRadio label="추이 기본 보기" value={t.trendDefault} options={['부문별','자산별']} onChange={v=>setTweak('trendDefault',v)}/>
      </TweaksPanel>
    </React.Fragment>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
