import { PLAN_FILTER_STATUSES, type PlanFilterStatus } from '../../../features/planBoard';
import type { PlanSidebarKey, PlaySidebarKey, TopMenuKey } from '../types';
import { resolveSavedLayoutMenuKey } from './constants';

export type MainViewInitialNavigation = {
  activeTopMenu: TopMenuKey;
  selectedPlanMenu: PlanSidebarKey;
  selectedPlayMenu: PlaySidebarKey;
  initialSelectedPlanId: number | null;
  initialSelectedWorkId: string | null;
};

export function resolveInitialNavigation(): MainViewInitialNavigation {
  if (typeof window === 'undefined') {
    return {
      activeTopMenu: 'chat',
      selectedPlanMenu: 'all',
      selectedPlayMenu: 'layout',
      initialSelectedPlanId: null,
      initialSelectedWorkId: null,
    };
  }

  const params = new URLSearchParams(window.location.search);
  const topMenuParam = params.get('topMenu');
  const requestedTopMenu: TopMenuKey =
    topMenuParam === 'docs' || topMenuParam === 'apis' || topMenuParam === 'plans' || topMenuParam === 'chat' || topMenuParam === 'play'
      ? topMenuParam
      : 'chat';
  const planFilterParam = params.get('planFilter');
  const selectedPlanMenu =
    planFilterParam === 'release'
      ? 'release'
      : planFilterParam && PLAN_FILTER_STATUSES.includes(planFilterParam as PlanFilterStatus)
        ? (planFilterParam as PlanFilterStatus)
        : 'all';
  const planIdParam = params.get('planId');
  const parsedPlanId = planIdParam ? Number(planIdParam) : null;
  const playSectionParam = params.get('playSection');
  const playLayoutIdParam = params.get('playLayoutId');

  return {
    activeTopMenu: requestedTopMenu,
    selectedPlanMenu,
    selectedPlayMenu:
      playSectionParam === 'layout'
        ? 'layout'
        : playSectionParam === 'apps'
          ? 'apps'
          : playSectionParam === 'test'
            ? 'test'
          : playSectionParam === 'cbt'
            ? 'cbt'
            : playSectionParam === 'layout-record' && playLayoutIdParam
              ? resolveSavedLayoutMenuKey(playLayoutIdParam)
              : 'layout',
    initialSelectedPlanId: Number.isFinite(parsedPlanId) ? parsedPlanId : null,
    initialSelectedWorkId: params.get('workId'),
  };
}
