import React, { Suspense } from 'react';
import { Box, Spinner } from 'folds';
import {
  Navigate,
  Outlet,
  Route,
  createBrowserRouter,
  createHashRouter,
  createRoutesFromElements,
  redirect,
  useParams,
} from 'react-router-dom';

import { ClientConfig } from '../hooks/useClientConfig';
import { AuthLayout, Login, Register, ResetPassword } from './auth';
import {
  BOTS_PATH,
  CHANNELS_PATH,
  CHANNELS_ROOM_EVENT_PATH,
  CHANNELS_ROOM_PATH,
  CHANNELS_SPACE_PATH,
  CHANNELS_THREAD_PATH,
  DIRECT_PATH,
  EXPLORE_PATH,
  HOME_PATH,
  LOGIN_PATH,
  REGISTER_PATH,
  RESET_PASSWORD_PATH,
  SETTINGS_PATH,
  SPACE_PATH,
  _CREATE_PATH,
  _FEATURED_PATH,
  _JOIN_PATH,
  _LOBBY_PATH,
  _ROOM_PATH,
  _SEARCH_PATH,
  _SERVER_PATH,
  CREATE_PATH,
  USER_LINK_HOST,
  USER_LINK_PATH,
  DirectCreateSearchParams,
} from './paths';
import {
  getAppPathFromHref,
  getDirectCreatePath,
  getExploreFeaturedPath,
  getHomePath,
  getLoginPath,
  getOriginBaseUrl,
  getSpaceLobbyPath,
  withSearchParam,
} from './pathUtils';
import { getMxIdServer, isUserId } from '../utils/matrix';
import { ClientBindAtoms, ClientLayout, ClientRoot } from './client';
import { HomeRouteRoomProvider } from './client/home';
import { Direct, DirectCreate, DirectRouteRoomProvider } from './client/direct';
import { ChannelPickPlaceholder } from './client/channels/ChannelPickPlaceholder';
// Bots/Channels LISTING tabs are eager (not React.lazy) — see the code-split
// comment below. Imported from the concrete source files (not the barrels) so
// the eager edge doesn't drag the still-lazy BotExperienceHost chunk into boot.
import { Bots } from './client/bots/Bots';
import { Channels, ChannelsRootNav } from './client/channels/Channels';
import { RouteSpaceProvider, Space, SpaceRouteRoomProvider, SpaceSearch } from './client/space';
import { setAfterLoginRedirectPath } from './afterLoginRedirectPath';
import { WelcomePage } from './client/WelcomePage';
import { PageRoot } from '../components/page';
import { ScreenSize } from '../hooks/useScreenSize';
import { MobileFriendlyPageNav } from './MobileFriendly';
import { ClientInitStorageAtom } from './client/ClientInitStorageAtom';
import { ClientNonUIFeatures } from './client/ClientNonUIFeatures';
import { AuthRouteThemeManager, UnAuthRouteThemeManager } from './ThemeManager';
import { ReceiveSelfDeviceVerification } from '../components/DeviceVerification';
import { AutoRestoreBackupOnVerification } from '../components/BackupRestore';
import { RoomSettingsRenderer } from '../features/room-settings';
import { ClientRoomsNotificationPreferences } from './client/ClientRoomsNotificationPreferences';
import { SpaceSettingsRenderer } from '../features/space-settings';
import { CreateRoomModalRenderer } from '../features/create-room';
import { CreateSpaceModalRenderer } from '../features/create-space';
import { SearchModalRenderer } from '../features/search';
import { useShareTargetReceiver } from '../hooks/useShareTargetReceiver';
import { SettingsScreen } from '../features/settings/SettingsScreen';
import { getFallbackSession } from '../state/sessions';
import { CallEmbedProvider } from '../components/CallEmbedProvider';
import { useIncomingRtcNotifications } from '../hooks/useIncomingRtcNotifications';
import { useCallerAutoHangup } from '../hooks/useCallerAutoHangup';
import { usePendingCallActionConsumer } from '../hooks/usePendingCallActionConsumer';
import { HorseshoeContainer } from './HorseshoeContainer';
import { useAppUrlOpen } from '../hooks/useAppUrlOpen';
import { ChannelsModeProvider } from '../hooks/useChannelsMode';
import { MobileTabsLayout } from '../components/mobile-tabs-pager';

function IncomingCallsFeature() {
  useIncomingRtcNotifications();
  useCallerAutoHangup();
  usePendingCallActionConsumer();
  // Native CallStyle dismissal is owned by the Android ring registry:
  // VojoFirebaseMessagingService.removeIncomingRing (ownership-checked cancel)
  // fires on atom REMOVE via bridge, and MainActivity.onResume calls
  // cancelRenderedIncomingRings for the background→foreground handoff.
  // A JS-side dismiss hook here is redundant and risks a blind tag/id cancel
  // hitting a foreign ring in the same room slot.
  useAppUrlOpen();
  return null;
}

// Drains the native share-target slot on cold-start and listens for warm
// shareReceived events. Mounted alongside IncomingCallsFeature so it runs
// only after login (Matrix client + room list available) and stays alive
// for the whole authenticated session.
function ShareTargetFeature() {
  useShareTargetReceiver();
  return null;
}

// Deep-link entry for /u/<user>. `<user>` is either a bare localpart or a
// full MXID; we normalize to an MXID using USER_LINK_HOST (the deep-link's own
// host, NOT the logged-in user's homeserver — a user signed into matrix.org
// opening vojo.chat/u/test3 still means @test3:vojo.chat) and forward to the
// existing DirectCreate flow, which itself dedupes to any existing DM via
// getDMRoomFor.
function UserLinkRedirect() {
  const { userIdOrLocalPart } = useParams();
  if (!userIdOrLocalPart) return <Navigate to={getHomePath()} replace />;

  // react-router already percent-decodes path params, so do NOT decode again:
  // a second decodeURIComponent both throws (URIError) on a crafted link like
  // `/u/%25` — white-screening the app via the router error boundary — and is
  // semantically wrong (it un-escapes a further encoding layer).
  const raw = userIdOrLocalPart;
  const mxid = isUserId(raw) && getMxIdServer(raw) ? raw : `@${raw}:${USER_LINK_HOST}`;
  if (!isUserId(mxid)) return <Navigate to={getHomePath()} replace />;

  const params: DirectCreateSearchParams = { userId: mxid };
  return <Navigate to={withSearchParam(getDirectCreatePath(), params)} replace />;
}

// Route-level code-splitting. Each heavy page is loaded on first navigation
// instead of in the boot bundle — this pulls the timeline (Room), lobby,
// explore, create and the bot-experience host off first load. Imports point at
// the concrete source file (not the barrel) so each chunk stays tight.
// `routeSuspense` wraps every usage so only the content area shows the fallback
// while the chunk streams in — surrounding nav/chrome stays mounted.
//
// The Channels/Bots LISTING tabs are deliberately NOT here — they are imported
// eagerly (top of file). Code-splitting those two tiny chunks (~5.6 KB gz) won
// almost nothing on first load, but made every first switch to the tab suspend
// and paint a fallback in the nav column that reflowed the layout — a visible
// web-only "tab-switch flicker". Eager import restores the pre-split behavior.
// See `docs/ai/bugs.md`.
//
// NOTE: SettingsScreen is intentionally NOT lazy here. The settings UI
// (`features/settings/Settings`) is already pulled into the boot graph by
// `Direct` → `MobileSettingsHorseshoe` (the mobile settings sheet, mounted in
// the boot listing view), so a Router-level lazy split produces a Rollup
// "dynamically + statically imported" warning and zero size win. Splitting
// settings off boot requires lazy-loading `<Settings>` inside its two hosts
// (MobileSettingsHorseshoe + SettingsScreen) — deferred as a separate change.
const Room = React.lazy(() => import('../features/room/Room').then((m) => ({ default: m.Room })));
const Lobby = React.lazy(() =>
  import('../features/lobby/Lobby').then((m) => ({ default: m.Lobby }))
);
const Explore = React.lazy(() =>
  import('./client/explore/Explore').then((m) => ({ default: m.Explore }))
);
const FeaturedRooms = React.lazy(() =>
  import('./client/explore/Featured').then((m) => ({ default: m.FeaturedRooms }))
);
const PublicRooms = React.lazy(() =>
  import('./client/explore/Server').then((m) => ({ default: m.PublicRooms }))
);
const BotExperienceHost = React.lazy(() =>
  import('./client/bots/BotExperienceHost').then((m) => ({ default: m.BotExperienceHost }))
);
const Create = React.lazy(() =>
  import('./client/create/Create').then((m) => ({ default: m.Create }))
);

function RouteSuspenseFallback() {
  return (
    <Box grow="Yes" style={{ height: '100%' }} alignItems="Center" justifyContent="Center">
      <Spinner variant="Secondary" size="600" />
    </Box>
  );
}

const routeSuspense = (node: React.ReactNode) => (
  <Suspense fallback={<RouteSuspenseFallback />}>{node}</Suspense>
);

export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize) => {
  const { hashRouter } = clientConfig;
  const mobile = screenSize === ScreenSize.Mobile;

  const routes = createRoutesFromElements(
    <Route>
      <Route
        index
        loader={() => {
          if (getFallbackSession()) return redirect(getHomePath());
          const afterLoginPath = getAppPathFromHref(getOriginBaseUrl(), window.location.href);
          if (afterLoginPath) setAfterLoginRedirectPath(afterLoginPath);
          return redirect(getLoginPath());
        }}
      />
      <Route
        loader={() => {
          if (getFallbackSession()) {
            return redirect(getHomePath());
          }

          return null;
        }}
        element={
          <>
            <AuthLayout />
            <UnAuthRouteThemeManager />
          </>
        }
      >
        <Route path={LOGIN_PATH} element={<Login />} />
        <Route path={REGISTER_PATH} element={<Register />} />
        <Route path={RESET_PASSWORD_PATH} element={<ResetPassword />} />
      </Route>

      <Route
        loader={() => {
          const session = getFallbackSession();
          if (!session) {
            const afterLoginPath = getAppPathFromHref(
              getOriginBaseUrl(hashRouter),
              window.location.href
            );
            if (afterLoginPath) setAfterLoginRedirectPath(afterLoginPath);
            return redirect(getLoginPath());
          }
          return null;
        }}
        element={
          <AuthRouteThemeManager>
            <ClientRoot>
              <ClientInitStorageAtom>
                <ClientRoomsNotificationPreferences>
                  <ClientBindAtoms>
                    <ClientNonUIFeatures>
                      <CallEmbedProvider>
                        <HorseshoeContainer>
                          {/* Старый 66px SidebarNav-рельс удалён в Dawn remnant
                              sweep — его поверхности живут в сегментах Direct/
                              Channels/Bots. nav остаётся null. */}
                          <ClientLayout nav={null}>
                            <Outlet />
                          </ClientLayout>
                        </HorseshoeContainer>
                        <IncomingCallsFeature />
                        <ShareTargetFeature />
                      </CallEmbedProvider>
                      <SearchModalRenderer />
                      <CreateRoomModalRenderer />
                      <CreateSpaceModalRenderer />
                      <RoomSettingsRenderer />
                      <SpaceSettingsRenderer />
                      <ReceiveSelfDeviceVerification />
                      <AutoRestoreBackupOnVerification />
                    </ClientNonUIFeatures>
                  </ClientBindAtoms>
                </ClientRoomsNotificationPreferences>
              </ClientInitStorageAtom>
            </ClientRoot>
          </AuthRouteThemeManager>
        }
      >
        {/* Legacy /home/ tree — kept only as a redirect surface so cold-start
            push deep links and pre-P3c bookmarks resolve cleanly. The Home
            page itself is gone; HomeRouteRoomProvider redirects /home/{roomId}/
            into /direct/{roomId}/ on mount. See plan §6.7 / §8 P3c. */}
        <Route path={HOME_PATH}>
          <Route index element={<Navigate to={DIRECT_PATH} replace />} />
          <Route path={_CREATE_PATH} element={<Navigate to={getDirectCreatePath()} replace />} />
          <Route path={_JOIN_PATH} element={<Navigate to={DIRECT_PATH} replace />} />
          <Route path={_SEARCH_PATH} element={<Navigate to={DIRECT_PATH} replace />} />
          <Route
            path={_ROOM_PATH}
            element={<HomeRouteRoomProvider>{routeSuspense(<Room />)}</HomeRouteRoomProvider>}
          />
        </Route>
        {/* Mobile + Capacitor horizontal swipe pager. The layout-route
            wrapper has no path: at listing-root URLs it overrides
            rendering with `MobileTabsPager` (three panes mounted at
            once, slide via CSS transform); at detail URLs and on
            web/desktop/tablet it falls through to `<Outlet/>` and the
            wrapped routes render exactly as before. See
            `src/app/components/mobile-tabs-pager/`. */}
        <Route element={<MobileTabsLayout />}>
          <Route
            path={DIRECT_PATH}
            element={
              <PageRoot
                nav={
                  <MobileFriendlyPageNav path={DIRECT_PATH}>
                    <Direct />
                  </MobileFriendlyPageNav>
                }
              >
                <Outlet />
              </PageRoot>
            }
          >
            {mobile ? null : <Route index element={<WelcomePage />} />}
            <Route path={_CREATE_PATH} element={<DirectCreate />} />
            <Route
              path={_ROOM_PATH}
              element={<DirectRouteRoomProvider>{routeSuspense(<Room />)}</DirectRouteRoomProvider>}
            />
          </Route>
          {/* Bots reuses StreamHeader segments. /bots/* is reserved before SPACE_PATH so deep URLs don't fall to /:spaceIdOrAlias/. */}
          <Route
            path={BOTS_PATH}
            element={
              <PageRoot
                nav={
                  <MobileFriendlyPageNav path={BOTS_PATH}>
                    <Bots />
                  </MobileFriendlyPageNav>
                }
              >
                <Outlet />
              </PageRoot>
            }
          >
            {mobile ? null : <Route index element={<WelcomePage />} />}
            <Route path=":botId" element={routeSuspense(<BotExperienceHost />)} />
            {/* A single conversation (m.thread root) inside an assistant bot's control
                DM. Same element as :botId — BotExperienceHost reads :rootId to open the
                reused ThreadDrawer; without it the conversation list renders. */}
            <Route path=":botId/thread/:rootId" element={routeSuspense(<BotExperienceHost />)} />
          </Route>
          <Route path="/bots/*" element={<Navigate to={BOTS_PATH} replace />} />
          {/* Channels segment. /channels/* is reserved before SPACE_PATH so the
              generic /:spaceIdOrAlias/ catch-all doesn't swallow the prefix.
              Phase 1 routes resolve to a stubbed center pane; Phase 3 + Phase 4
              replace the left list and center timeline respectively. */}
          <Route
            path={CHANNELS_PATH}
            element={
              <ChannelsModeProvider value>
                <Outlet />
              </ChannelsModeProvider>
            }
          >
            <Route
              index
              element={
                <PageRoot
                  nav={
                    <MobileFriendlyPageNav path={CHANNELS_PATH}>
                      <ChannelsRootNav />
                    </MobileFriendlyPageNav>
                  }
                >
                  {mobile ? null : <WelcomePage />}
                </PageRoot>
              }
            />
            <Route
              path={CHANNELS_SPACE_PATH.slice(CHANNELS_PATH.length)}
              element={
                <RouteSpaceProvider>
                  <PageRoot
                    nav={
                      <MobileFriendlyPageNav path={CHANNELS_SPACE_PATH}>
                        <Channels />
                      </MobileFriendlyPageNav>
                    }
                  >
                    <Outlet />
                  </PageRoot>
                </RouteSpaceProvider>
              }
            >
              {mobile ? null : <Route index element={<ChannelPickPlaceholder />} />}
              <Route
                path={CHANNELS_ROOM_PATH.slice(CHANNELS_SPACE_PATH.length)}
                element={<SpaceRouteRoomProvider>{routeSuspense(<Room />)}</SpaceRouteRoomProvider>}
              >
                {/* Thread drawer URL — same Room element renders, drawer
                    opens by reading `:rootId` via useParams. The
                    SpaceRouteRoomProvider lives on the parent route and
                    stays mounted across the room↔thread URL flip. */}
                <Route
                  path={CHANNELS_THREAD_PATH.slice(CHANNELS_ROOM_PATH.length)}
                  element={null}
                />
                {/* Event-anchored URL — search/inbox/mention/push permalinks.
                    RR6 merges child params into the parent's useParams so
                    Room.tsx reads `eventId` without re-routing. */}
                <Route
                  path={CHANNELS_ROOM_EVENT_PATH.slice(CHANNELS_ROOM_PATH.length)}
                  element={null}
                />
              </Route>
            </Route>
          </Route>
        </Route>
        <Route
          path={SPACE_PATH}
          element={
            <RouteSpaceProvider>
              <PageRoot
                nav={
                  <MobileFriendlyPageNav path={SPACE_PATH}>
                    <Space />
                  </MobileFriendlyPageNav>
                }
              >
                <Outlet />
              </PageRoot>
            </RouteSpaceProvider>
          }
        >
          {mobile ? null : (
            <Route
              index
              loader={({ params }) => {
                const { spaceIdOrAlias } = params;
                if (spaceIdOrAlias) {
                  return redirect(getSpaceLobbyPath(spaceIdOrAlias));
                }
                return null;
              }}
              element={<WelcomePage />}
            />
          )}
          <Route path={_LOBBY_PATH} element={routeSuspense(<Lobby />)} />
          <Route path={_SEARCH_PATH} element={<SpaceSearch />} />
          <Route
            path={_ROOM_PATH}
            element={<SpaceRouteRoomProvider>{routeSuspense(<Room />)}</SpaceRouteRoomProvider>}
          />
        </Route>
        <Route
          path={EXPLORE_PATH}
          element={
            <PageRoot
              nav={
                <MobileFriendlyPageNav path={EXPLORE_PATH}>
                  {routeSuspense(<Explore />)}
                </MobileFriendlyPageNav>
              }
            >
              <Outlet />
            </PageRoot>
          }
        >
          {mobile ? null : (
            <Route
              index
              loader={() => redirect(getExploreFeaturedPath())}
              element={<WelcomePage />}
            />
          )}
          <Route path={_FEATURED_PATH} element={routeSuspense(<FeaturedRooms />)} />
          <Route path={_SERVER_PATH} element={routeSuspense(<PublicRooms />)} />
        </Route>
        <Route path={CREATE_PATH} element={routeSuspense(<Create />)} />
        {/* /settings shares the DIRECT_PATH shell — left page-nav stays
            the DM list, the right pane swaps the chat outlet for the
            Settings UI. The horseshoe rounded TL/BL on the right pane
            (commits 363bd9d / 74d32eb) inherits from PageRoot for free.
            On mobile MobileFriendlyPageNav hides the DM list since
            /settings/ ≠ DIRECT_PATH; SettingsScreen renders the
            bottom-up horseshoe sheet over the empty outlet area. */}
        <Route
          path={SETTINGS_PATH}
          element={
            <PageRoot
              nav={
                <MobileFriendlyPageNav path={DIRECT_PATH}>
                  <Direct />
                </MobileFriendlyPageNav>
              }
            >
              <SettingsScreen />
            </PageRoot>
          }
        />
        <Route path={USER_LINK_PATH} element={<UserLinkRedirect />} />
        {/* Legacy /inbox/ tree — invites moved inline into the Direct list,
            the Notifications aggregator was removed. Keep the route as a
            redirect so old push deep-links and bookmarks resolve cleanly. */}
        <Route path="/inbox/*" element={<Navigate to={DIRECT_PATH} replace />} />
      </Route>
      <Route path="/*" element={<p>Page not found</p>} />
    </Route>
  );

  if (hashRouter?.enabled) {
    return createHashRouter(routes, { basename: hashRouter.basename });
  }
  return createBrowserRouter(routes, {
    basename: import.meta.env.BASE_URL,
  });
};
