import dynamic from 'next/dynamic';
import type { ComponentType } from 'react';
import type { CheckoutVariantId, CheckoutVariantProps } from './types';

type VariantLoader = () => Promise<{
  default: ComponentType<CheckoutVariantProps>;
}>;

const variantLoaders: Record<CheckoutVariantId, VariantLoader> = {
  'multi-step': () => import('./multi-step'),
  'one-page': () => import('./one-page'),
  accordion: () => import('./one-page'),
  'basket-and-checkout': () => import('./basket-and-checkout')
};

/**
 * Variants that embed the basket inside the checkout page. In these modes the
 * basket page redirects to checkout, so checkout must never redirect back to
 * the basket page — that would create an infinite redirect loop.
 */
export const UNIFIED_VARIANTS: ReadonlySet<string> = new Set([
  'basket-and-checkout'
]);

export const getCheckoutVariant = (variant: CheckoutVariantId | undefined) => {
  const loader = variantLoaders[variant ?? 'multi-step'] ?? variantLoaders['multi-step'];

  return dynamic(loader, { ssr: false });
};

export const isKnownVariant = (value: unknown): value is CheckoutVariantId =>
  typeof value === 'string' && value in variantLoaders;
