/* ========================================================================
   APP ROOT — frame, router, boot
   Page modules register themselves on window.PAGES[pageKey]; the router
   renders the registered component (or a placeholder while porting).
   ======================================================================== */

window.PAGES = window.PAGES || {};

function PlaceholderPage() {
  useAppState();
  return (
    <div className="body" style={{ paddingRight: 32 }}>
      <div
        className="card"
        style={{
          margin: '0 auto', alignSelf: 'flex-start', marginTop: 96,
          padding: '40px 48px', textAlign: 'center', maxWidth: 420,
        }}
      >
        <Icon name="construction" size={32} style={{ color: 'var(--muted-foreground)' }} />
        <div style={{ font: '600 16px/1.4 var(--font-body)', marginTop: 12 }}>
          {PAGE_TITLES[state.page] || state.page}
        </div>
        <div style={{ font: '400 13px/1.5 var(--font-body)', color: 'var(--muted-foreground)', marginTop: 4 }}>
          This page hasn't been ported to the React build yet.
        </div>
      </div>
    </div>
  );
}

function App() {
  useAppState();
  const Page = window.PAGES[state.page] || PlaceholderPage;
  const MODES = {
    opportunities: 'inbox', 'saved-opportunities': 'inbox',
    agents: 'agent', templates: 'templates', account: 'templates',
    territories: 'templates', worksheets: 'worksheets',
  };
  const mode = state.page === 'search'
    ? (state.detailRecord ? 'detail' : '')
    : state.page === 'worksheets'
      ? (state.worksheetId && state.worksheetRecord && state.worksheetRecord.sheetId === state.worksheetId ? 'ws-detail' : 'worksheets')
      : state.page === 'custom-filters'
        ? (state.customFilterId ? 'detail' : '')
        : (MODES[state.page] || '');
  return (
    <div className="app-frame" data-mode={mode}>
      <AppSidebar />
      <div className="main-content">
        <AppHeader />
        <Page />
        {window.TerritoryBannerLayer ? <window.TerritoryBannerLayer /> : null}
      </div>
      <HelperTipLayer />
      {/* Global overlays — single instances shared by every page */}
      {window.EditorPopover ? <window.EditorPopover /> : null}
      {window.FilterEditorModal ? <window.FilterEditorModal /> : null}
      {window.AssignModal ? <window.AssignModal /> : null}
      {window.CriterionEditorModal ? <window.CriterionEditorModal /> : null}
      {window.AgentGuardModal ? <window.AgentGuardModal /> : null}
    </div>
  );
}

/* ---- boot ---------------------------------------------------------------- */
reconcileSavedSearches();
applyTerritorySeeding(!!(window.TWEAKS && window.TWEAKS.salesforceIntegrated));

const __root = ReactDOM.createRoot(document.getElementById('root'));
__root.render(<App />);
window.__pursuitBooted = true;
