/* eslint-disable react-refresh/only-export-components */

import { type ComponentType, lazy, type LazyExoticComponent } from 'react';

import { normalizeAppPath } from './appPageRoutes';

type AppRouteComponent = LazyExoticComponent<
  ComponentType<Record<string, unknown>>
>;

export type AppRouteMatch =
  | {
      kind: 'puzzle-playground';
    }
  | {
      kind: 'big-fish-playground';
    }
  | {
      kind: 'match3d-playground';
    }
  | {
      kind: 'game';
    };

export type ResolvedAppRoute = {
  kind: AppRouteMatch['kind'];
  loadingEyebrow: string;
  loadingText: string;
  Component: AppRouteComponent;
  componentProps?: Record<string, unknown>;
};

const GameApp = lazy(() => import('../AuthenticatedApp')) as AppRouteComponent;
const BigFishPlaygroundApp = lazy(() => import('../BigFishPlaygroundApp')) as AppRouteComponent;
const Match3DPlaygroundApp = lazy(() => import('../Match3DPlaygroundApp')) as AppRouteComponent;
const PuzzlePlaygroundApp = lazy(() => import('../PuzzlePlaygroundApp')) as AppRouteComponent;

function normalizeRoutePath(pathname: string) {
  return normalizeAppPath(pathname);
}

export function matchAppRoute(pathname: string): AppRouteMatch {
  const normalizedPath = normalizeRoutePath(pathname);

  if (normalizedPath === '/puzzle') {
    return {
      kind: 'puzzle-playground',
    };
  }

  if (normalizedPath === '/big-fish') {
    return {
      kind: 'big-fish-playground',
    };
  }

  if (normalizedPath === '/match3d') {
    return {
      kind: 'match3d-playground',
    };
  }

  return {
    kind: 'game',
  };
}

export function resolveAppRoute(pathname: string): ResolvedAppRoute {
  const matchedRoute = matchAppRoute(pathname);

  if (matchedRoute.kind === 'puzzle-playground') {
    return {
      kind: 'puzzle-playground',
      loadingEyebrow: '正在载入拼图',
      loadingText: '正在进入拼图关卡...',
      Component: PuzzlePlaygroundApp,
    };
  }

  if (matchedRoute.kind === 'big-fish-playground') {
    return {
      kind: 'big-fish-playground',
      loadingEyebrow: '正在载入大鱼',
      loadingText: '正在进入玩法...',
      Component: BigFishPlaygroundApp,
    };
  }

  if (matchedRoute.kind === 'match3d-playground') {
    return {
      kind: 'match3d-playground',
      loadingEyebrow: '正在载入抓大鹅',
      loadingText: '正在进入消除关卡...',
      Component: Match3DPlaygroundApp,
    };
  }

  return {
    kind: 'game',
    loadingEyebrow: '正在载入游戏',
    loadingText: '正在载入冒险...',
    Component: GameApp,
  };
}
