// ─── 앱 루트 / 셸 ───
const { useState: aUseState } = React;

const NAV = [
  { id: 'chat', label: 'Smart BI', icon: I.chat, crumb: '데이터를 AI로 분석하고 컴포넌트로 저장하세요' },
  { id: 'dashboard', label: '대시보드', icon: I.grid, crumb: '저장한 컴포넌트로 나만의 대시보드를 구성하세요' },
  { id: 'components', label: '컴포넌트', icon: I.layers, crumb: '저장된 분석 컴포넌트 라이브러리' },
  { id: 'upload', label: '데이터 추가', icon: I.upload, crumb: '사전정의된 유형으로 데이터를 업로드하세요' },
];

// 대시보드 사전정의 (탭별 레이아웃 & 컴포넌트)
function initDashboards(library) {
  const byId = (id) => library.find((c) => c.id === id);
  const mk = (pfx, layout) => layout.map((l, i) => ({ ...byId(l.id), ...l, srcId: l.id, id: l.id + '-' + pfx + i }));
  return [
    {
      id: 'pension', name: '연금 ETF 모니터링', star: true,
      items: mk('p', [
        { id: 'cmp-ind-top10',     x: 0,   y: 0,   w: 560, h: 400 },
        { id: 'cmp-mgr-share',     x: 600, y: 0,   w: 560, h: 400 },
        { id: 'cmp-monthly-trend', x: 0,   y: 440, w: 560, h: 360 },
        { id: 'cmp-netbuy-sheet',  x: 600, y: 440, w: 560, h: 360 },
      ]),
    },
    {
      id: 'flow', name: '자금 흐름 일일 점검',
      items: mk('f', [
        { id: 'cmp-flow-daily', x: 0,   y: 0,   w: 720, h: 400 },
        { id: 'cmp-mgr-share',  x: 760, y: 0,   w: 400, h: 400 },
        { id: 'cmp-flow-sheet', x: 0,   y: 440, w: 720, h: 400 },
        { id: 'cmp-inst-top10', x: 760, y: 440, w: 400, h: 400 },
      ]),
    },
  ];
}

// 컴포넌트가 사용 중인 대시보드 배지 (호버 시 목록)
function UsageBadge({ comp, dashboards }) {
  const used = dashboards.filter((d) => d.items.some((it) => it.srcId === comp.id));
  return (
    <div className="usage-wrap">
      <span className={'chip' + (used.length ? '' : ' gray')}>{I.grid}{used.length ? `대시보드 ${used.length}개에서 사용 중` : '미사용'}</span>
      {used.length > 0 && (
        <div className="usage-pop">
          <div className="cap">사용 중인 대시보드</div>
          {used.map((d) => (
            <div className="row" key={d.id}>
              {I.grid}{d.name}
              <span className="n">{d.items.filter((it) => it.srcId === comp.id).length}개 배치</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ComponentsView({ library, dashboards, openSettings, onDelete }) {
  return (
    <div className="upload-view" style={{ maxWidth: 1160 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16 }}>
        <div>
          <h3 className="section-title">컴포넌트 라이브러리</h3>
          <p className="section-sub" style={{ margin: 0 }}>Smart BI에서 저장한 분석 결과입니다. 사용 현황을 확인하고 설정을 편집할 수 있어요.</p>
        </div>
        <span className="chip" style={{ marginLeft: 'auto' }}>{library.length}개</span>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 14 }}>
        {library.map((c) => (
          <div className="card" key={c.id} style={{ overflow: 'visible' }}>
            <div className="dash-card-head" style={{ padding: '14px 15px 10px' }}>
              <span className="vic" style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--blue-50)', color: 'var(--blue-600)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{VIEW_ICON[c.view]}</span>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div className="t" style={{ fontSize: 14, fontWeight: 700 }}>{c.title}</div>
                <div className="d" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 1 }}>{c.source} · 저장 {c.savedAt}</div>
              </div>
              <div style={{ display: 'flex', gap: 4 }}>
                <button className="ico-btn" style={{ width: 30, height: 30, borderRadius: 8, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => openSettings(c)} title="설정">{I.settings}</button>
                <button className="ico-btn" style={{ width: 30, height: 30, borderRadius: 8, color: 'var(--ink-3)', display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={() => onDelete(c)} title="삭제">{I.trash}</button>
              </div>
            </div>
            <div style={{ padding: '4px 16px 14px', height: 230, overflow: 'hidden' }}><ComponentView comp={c} /></div>
            <div style={{ display: 'flex', alignItems: 'center', padding: '0 15px 15px' }}>
              <UsageBadge comp={c} dashboards={dashboards} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function App() {
  const [tab, setTab] = aUseState('chat');
  const [push, toastHost] = useToasts();
  const [dataset, setDataset] = aUseState(window.BI.DATASETS[0]);

  // 컴포넌트 라이브러리 (챗 저장 → 추가)
  const [library, setLibrary] = aUseState(window.BI.SAVED_COMPONENTS);
  const [savedFromChat, setSavedFromChat] = aUseState([]);

  // 대시보드 상태 (탭별)
  const [dashboards, setDashboards] = aUseState(() => initDashboards(window.BI.SAVED_COMPONENTS));
  const [activeDashId, setActiveDashId] = aUseState('pension');
  const [editing, setEditing] = aUseState(false);
  const [showAdd, setShowAdd] = aUseState(false);

  const activeDash = dashboards.find((d) => d.id === activeDashId);
  const setDashItems = (updater) => {
    setDashboards((ds) => ds.map((d) => d.id === activeDashId
      ? { ...d, items: typeof updater === 'function' ? updater(d.items) : updater }
      : d));
  };

  // 업로드 히스토리
  const [uploadHistory, setUploadHistory] = aUseState(window.BI.UPLOAD_HISTORY);

  // 설정/삭제 모달
  const [settingsComp, setSettingsComp] = aUseState(null);
  const [deleteComp, setDeleteComp] = aUseState(null);

  const saveFromChat = (comp, msgId) => {
    const id = 'cmp-chat-' + Date.now().toString(36).slice(-5);
    const newComp = { id, title: comp.title, desc: comp.desc, view: comp.view, source: comp.dataset || dataset.name, savedAt: new Date().toISOString().slice(0, 10), kind: comp.kind, subject: comp.subject, result: comp, config: comp.config || { topN: 10, theme: 'blue' } };
    setLibrary((l) => [newComp, ...l]);
    setSavedFromChat((s) => [...s, msgId]);
    push('컴포넌트로 저장했어요 · 라이브러리에서 확인하세요');
  };

  const saveSettings = (updated) => {
    setLibrary((l) => l.map((c) => c.id === updated.id ? { ...c, ...updated } : c));
    setDashboards((ds) => ds.map((d) => ({ ...d, items: d.items.map((c) => c.id === updated.id ? { ...c, ...updated } : c) })));
    setSettingsComp(null);
    push('설정을 저장했어요');
  };

  const confirmDelete = () => {
    const c = deleteComp;
    setLibrary((l) => l.filter((x) => x.id !== c.id));
    setDashboards((ds) => ds.map((d) => ({ ...d, items: d.items.filter((it) => it.srcId !== c.id) })));
    setDeleteComp(null);
    push(`'${c.title}' 컴포넌트를 삭제했어요`);
  };

  const cur = NAV.find((n) => n.id === tab);
  const deleteUsedIn = deleteComp ? dashboards.filter((d) => d.items.some((it) => it.srcId === deleteComp.id)) : [];

  return (
    <div className="app">
      <aside className="sidebar">
        <div className="sb-brand">
          <div className="sb-logo">S</div>
          <div><div className="nm">삼성자산운용</div><div className="sub">AI Business Intelligence</div></div>
        </div>
        <nav className="sb-nav">
          <div className="sb-section">분석</div>
          {NAV.slice(0, 3).map((n) => (
            <button key={n.id} className={'sb-item' + (tab === n.id ? ' active' : '')} onClick={() => setTab(n.id)}>
              {n.icon}{n.label}
              {n.id === 'components' && <span className="badge">{library.length}</span>}
            </button>
          ))}
          <div className="sb-section">데이터</div>
          {NAV.slice(3).map((n) => (
            <button key={n.id} className={'sb-item' + (tab === n.id ? ' active' : '')} onClick={() => setTab(n.id)}>{n.icon}{n.label}</button>
          ))}
        </nav>
        <div className="sb-foot">
          <div className="sb-avatar">김</div>
          <div style={{ flex: 1 }}><div className="nm">김지원</div><div className="role">디지털전략팀</div></div>
        </div>
      </aside>

      <main className="main">
        <div className="topbar">
          <h1>{cur.label}</h1>
          <span className="crumb">· {cur.crumb}</span>
          <div className="spacer"></div>
          {tab === 'chat' && <span className="chip gray">{I.db}{dataset.name}</span>}
        </div>
        <div className="content">
          {tab === 'chat' && <ChatView dataset={dataset} setDataset={setDataset} datasets={window.BI.DATASETS}
            onSaveComponent={saveFromChat} savedFromChat={savedFromChat} library={library} push={push} />}
          {tab === 'dashboard' && <DashboardView library={library} dashboards={dashboards} activeId={activeDashId}
            onSelectDash={setActiveDashId} items={activeDash.items} setItems={setDashItems}
            editing={editing} setEditing={setEditing} openSettings={setSettingsComp} push={push} showAdd={showAdd} setShowAdd={setShowAdd} />}
          {tab === 'components' && <ComponentsView library={library} dashboards={dashboards} openSettings={setSettingsComp} onDelete={setDeleteComp} />}
          {tab === 'upload' && <UploadView push={push} uploadHistory={uploadHistory} setUploadHistory={setUploadHistory} />}
        </div>
      </main>

      {settingsComp && <SettingsModal comp={settingsComp} onClose={() => setSettingsComp(null)} onSave={saveSettings} />}
      {deleteComp && (
        <Modal title="컴포넌트 삭제" icon={I.trash} onClose={() => setDeleteComp(null)}
          foot={<>
            <button className="btn btn-ghost" onClick={() => setDeleteComp(null)}>취소</button>
            <button className="btn btn-danger" onClick={confirmDelete}>{I.trash}삭제</button>
          </>}>
          <p style={{ margin: '0 0 12px', fontSize: 14 }}><b>'{deleteComp.title}'</b> 컴포넌트를 삭제할까요?</p>
          {deleteUsedIn.length > 0 ? (
            <div style={{ border: '1px solid #F2D9A6', background: '#FBF0DF', borderRadius: 10, padding: '12px 14px', fontSize: 12.5, color: 'var(--warn)', display: 'flex', gap: 9, alignItems: 'flex-start' }}>
              <span className="ic-16" style={{ display: 'flex', flex: '0 0 auto', marginTop: 1 }}>{I.alert}</span>
              <span>다음 {deleteUsedIn.length}개 대시보드에서도 함께 제거됩니다: <b>{deleteUsedIn.map((d) => d.name).join(', ')}</b></span>
            </div>
          ) : (
            <p style={{ margin: 0, fontSize: 12.5, color: 'var(--ink-3)' }}>사용 중인 대시보드가 없어 안전하게 삭제할 수 있어요.</p>
          )}
        </Modal>
      )}
      {toastHost}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
