/* ============================================================
   ルーター + マウント
   ============================================================ */
function Root() {
  const { route, currentUser, can, sessionExpired, logout, workspaceId, canManageWorkspaces, joinedWorkspaces } = useStore();
  if (route.screen === 'login') return <Login />;
  const screens = {
    dashboard: Dashboard, cases: CaseList, case: CaseDetail, triage: WorkspaceTriage,
    calendar: Calendar, customers: Customers, customer: CustomerDetail, integrations: IntegrationsScreen, settings: Settings,
    knowledge: KnowledgeScreen, apo: ApoScreen, apoLead: ApoLeadDetail, analytics: AnalyticsScreen,
    faq: FaqScreen, audit: AuditLogScreen, kpi: KpiReportScreen,
    proposalStudio: ProposalStudio, quoteStudio: QuoteStudio, skills:SkillsScreen,
  };
  // 設定・分析・監査・KPIは権限設定で許可されたロールのみ（既定は管理者のみ）。それ以外はダッシュボードへ（URL直打ちも遮断）
  const gated = (route.screen==='skills'&&currentUser.role!=='admin') || (route.screen === 'triage' && !can('workspaceTriage')) || (route.screen === 'settings' && !can('settings')&&!canManageWorkspaces) || (route.screen === 'analytics' && !can('viewAnalytics')) || (route.screen === 'audit' && !can('viewAuditLog')) || (route.screen === 'kpi' && !can('viewKpiReport'));
  const screenKey = gated ? 'dashboard' : route.screen;
  const noWorkspace=currentUser.role!=='admin'&&!joinedWorkspaces.length;
  const Screen = noWorkspace&&!['settings','faq'].includes(screenKey)?WorkspaceNoMembership:screens[screenKey] || Dashboard;
  return (
    <div>
      {/* セッション失効バナー：401検知後は保存が全て失敗するため、最上部で再ログインを強く促す */}
      {sessionExpired && (
        <div style={{ position: 'sticky', top: 0, zIndex: 400, background: '#b91c1c', color: '#fff', padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 12, fontSize: 13.5, fontWeight: 600 }}>
          <span style={{ flex: 1 }}>{t('auth.sessionExpired')}</span>
          <button onClick={logout}
            style={{ fontSize: 13, fontWeight: 700, padding: '7px 16px', borderRadius: 8, border: 'none', background: '#fff', color: '#b91c1c', cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap' }}>
            {t('auth.reLogin')}
          </button>
        </div>
      )}
      <ChangeBar />
      <GcalSyncBanner />
      <RcSyncBanner />
      <div style={{ display: 'flex', minHeight: '100vh', background: '#f6f7fa' }}>
        <Sidebar />
        <Screen key={workspaceId} />
        <CommandPalette />
      </div>
      <FaqChat key={workspaceId + currentUser.id} />
    </div>
  );
}

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