import React from 'react';
import ReactDOM from 'react-dom/client';
import { RouterProvider } from '@tanstack/react-router';
import { QueryClientProvider } from '@tanstack/react-query';
import { queryClient } from './lib/http/query-client';
import { setupInterceptors } from './lib/http/interceptors';
import { initSentry } from './lib/monitoring/sentry';
import { useUserStore } from './lib/store/user.store';
// Imported for its side effect: subscribes the reactive claims mirror to the
// token lifecycle BEFORE the first render, so claim-driven UI reacts to a
// background re-mint (X-KR-Reissue) rather than to whatever re-renders next.
import './lib/session/claims.store';
import { initNative } from './lib/native/native.init';
import { bootstrapPersistor } from './lib/offline/persister';
import { bootstrapNetworkListeners } from './lib/offline/network';
import { bootstrapConflictStore } from './lib/offline/conflict-store';
import { bootstrapSyncLifecycle } from './lib/offline/lifecycle';
import { bootstrapPwaRegister } from './lib/offline/pwa-register';
import { bootstrapPushNotifications } from './lib/notifications/push-notifications';
import { bootstrapAppConfig, isChatOperational } from './lib/store/app-config.store';
import { registerIcons } from '@ui/icons/icons.config';
import { bootstrapNativeDatePicker } from './lib/ui/native-date-picker';
import { RootErrorBoundary } from './components/shared/RootErrorBoundary';
import { router } from './router';

// WebView capability gate. index.html ran a classic (non-module) script that
// checks for oklch()/color-mix() support (Tailwind v4 requires WebView/Chrome
// 111+) and, if missing, rendered a plain update prompt into #root and set
// this flag. Abort the SPA bootstrap here so we neither overwrite that prompt
// nor run code/styles that assume a modern WebView. Throwing at module top
// level halts the rest of this module cleanly; the error is console-only.
if (
  typeof window !== 'undefined' &&
  (window as { __KR_UNSUPPORTED_WEBVIEW__?: boolean }).__KR_UNSUPPORTED_WEBVIEW__
) {
  throw new Error(
    'Kaizen Radiology: unsupported WebView - SPA bootstrap aborted (see index.html capability gate).',
  );
}

// Ionic's functional base only. Its two opinionated resets (normalize.css,
// typography.css) are loaded by styles/ionic-layer.css into a cascade layer
// that loses to every utility - see the note there; do not import them here.
import '@ionic/react/css/core.css';
import '@ionic/react/css/structure.css';
import '../libs/ui/src/theme/variables.css';
// ⚠️ Order is load-bearing, and each line is a different owner:
//   ionic-layer  declares the lowest cascade layer; must come first
//   global       ┐ the shared Kramos theme, synced from kaizenrounds-app
//   kaizen       ┘ (scripts/sync-kramos-theme.mjs) - never edited here
//   product      this product's accent hue - generated, the only colour we own
//   app          classes only this app's screens use, on tokens only
import './styles/ionic-layer.css';
import './styles/global.css';
import './styles/kaizen.css';
import './styles/product.css';
import './styles/app.css';

// Initialise error reporting before anything else so render errors are caught.
initSentry();
// Resilience for code-split routes. A dynamic import can fail when a new
// build deploys with new chunk hashes while this tab is still open — the
// old chunk URL 404s and the route white-screens. Vite emits
// `vite:preloadError` for exactly this. Reload to pick up the fresh index
// + chunks. The timestamp guard reloads at most once per ~10s window: a
// genuine deploy recovers, but if the reload can't fix it (offline with
// no SW cache) we stop instead of looping and let the error boundary show.
window.addEventListener('vite:preloadError', () => {
  const last = Number(sessionStorage.getItem('kr.preloadReloadAt') ?? '0');
  if (Date.now() - last < 10_000) return;
  sessionStorage.setItem('kr.preloadReloadAt', String(Date.now()));
  window.location.reload();
});
// Wire Axios interceptors (Bearer injection + 401 refresh) before first request.
setupInterceptors();

// Dev-only diagnostic handle: lets a debugging session read the query cache at
// runtime. Which entries HYDRATED from IndexedDB versus refetched is invisible
// any other way - no screenshot, no test and no log line distinguishes them,
// and that distinction is the whole diagnosis for an offline-read report.
// Never present in a production bundle.
if (import.meta.env.DEV) {
  (window as unknown as Record<string, unknown>)['__RADIOLOGY_QC'] = queryClient;
}
// Hydrate the TanStack Query cache from IndexedDB so the first paint after
// a cold start shows last-known data instead of skeletons. The persistor
// also writes mutations back on a 1s throttle.
bootstrapPersistor(queryClient);
// One-time wiring of `online`/`offline` events + Capacitor Network plugin.
// Sets the network store (useNetwork()) which the OfflineBanner + sync
// service both subscribe to.
void bootstrapNetworkListeners();
// Mirror any persisted offline conflicts from IDB into the in-memory
// Zustand store so list surfaces (badges, Sync Status) can subscribe
// without polling. Safe to call repeatedly — idempotent.
void bootstrapConflictStore();
// Hook Capacitor app lifecycle (resume/pause) + tab visibility +
// network-online events to drive automatic /sync/pull + flushQueue
// cycles. The foreground tick is a 60s opportunistic refresh that
// stops as soon as the app is backgrounded.
void bootstrapSyncLifecycle();
// Register the service worker (production web only — skipped in dev,
// skipped inside Capacitor native shell). Surfaces an "Update available"
// Sonner toast with a manual Reload action so the user picks the moment
// to swap to a new build; we never auto-refresh mid-round.
void bootstrapPwaRegister();
void bootstrapPushNotifications();
// Fetch the runtime app-config (operational toggles: chat / AI / OTP provider)
// from meridian GET /api/auth/config. This is a TOP-LAYER gate, separate from
// subscription feature_flags — it lets ops flip features for web AND native
// (APK/iOS) without a rebuild/store release. Re-runs syncChat once the config
// resolves so the chat gate reflects the live deployment state.
void bootstrapAppConfig().then(() => syncChat(useUserStore.getState().isLoggedIn));
registerIcons();
// Open native date/time pickers on click (not just the tiny indicator).
bootstrapNativeDatePicker();
// Rehydrate session from localStorage — mirrors NgRx ROOT_EFFECTS_INIT effect.
useUserStore.getState().rehydrate();
initNative();

// Tie the Mattermost chat session to KR auth state. A single subscription
// covers every auth path (password login, OTP, rehydrate, logout) so chat
// bootstraps once when logged in and tears down on logout.
//
// chat-bootstrap is dynamic-imported so the whole MM client + websocket +
// event-bridge graph stays out of the eager `index` chunk. Pre-login users
// never download it; post-login users fetch the chat chunk on demand.
let chatActive = false;
function syncChat(isLoggedIn: boolean): void {
  // Two-layer off-switch: the build-time hard switch (VITE_CHAT_ENABLED=false)
  // AND the runtime app-config gate (GET /api/auth/config → chat.enabled). When
  // either is off we never import the bootstrap — no token exchange, no
  // WebSocket. The runtime gate is what lets ops disable chat on native shells
  // without a store release. (Subscription feature_flags.chat is a further
  // per-workspace gate enforced where chat UI renders.)
  if (!isChatOperational()) {
    // If chat was previously active and the runtime gate has since closed,
    // tear it down so the WebSocket doesn't linger.
    if (chatActive) {
      chatActive = false;
      void import('./lib/chat/chat-bootstrap').then((m) => m.teardownChat());
    }
    return;
  }
  if (isLoggedIn && !chatActive) {
    chatActive = true;
    void import('./lib/chat/chat-bootstrap').then((m) => m.bootstrapChat());
  } else if (!isLoggedIn && chatActive) {
    chatActive = false;
    void import('./lib/chat/chat-bootstrap').then((m) => m.teardownChat());
  }
}
syncChat(useUserStore.getState().isLoggedIn);
useUserStore.subscribe((state) => syncChat(state.isLoggedIn));

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <RootErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <RouterProvider router={router} />
      </QueryClientProvider>
    </RootErrorBoundary>
  </React.StrictMode>,
);
