// @design-system: layout/CheckoutShell
// Registered at /design-system#checkoutshell-layout

import { type ReactNode } from 'react';
import { cn } from '@/lib/cn';
import { useT } from '@/lib/i18n/react';
import { Icon } from '@/components/ui/icons/Icon';
import { Button } from '@/components/ui/primitives/Button';
import { stepIndicatorVariants, stepLabelVariants } from './variants';

export interface CheckoutStep {
  id: string;
  /** Localised label shown under the step indicator (pre-translated string). */
  label: string;
  href?: string;
}

export interface CheckoutShellProps {
  steps: CheckoutStep[];
  activeStepId: string;
  children: ReactNode;
  className?: string;
  onBack?: () => void;
  backHref?: string;
  backLabel?: string;
}

type StepStatus = 'active' | 'completed' | 'upcoming';

function getStatus(steps: CheckoutStep[], step: CheckoutStep, activeStepId: string): StepStatus {
  const activeIdx = steps.findIndex((s) => s.id === activeStepId);
  const stepIdx = steps.findIndex((s) => s.id === step.id);
  if (stepIdx < activeIdx) return 'completed';
  if (stepIdx === activeIdx) return 'active';
  return 'upcoming';
}

/**
 * CheckoutShell — layout shell hosting a horizontal step-nav + content area.
 * The payment form mounts as step content — the shell does not own it.
 *
 * @example
 * <CheckoutShell
 *   steps={[
 *     { id: 'cart',    label: t('step_cart') },
 *     { id: 'details', label: t('step_details') },
 *     { id: 'payment', label: t('step_payment') },
 *   ]}
 *   activeStepId="details"
 * >
 *   {children}
 * </CheckoutShell>
 */
export function CheckoutShell({
  steps,
  activeStepId,
  children,
  className,
  onBack,
  backHref,
  backLabel,
}: CheckoutShellProps) {
  const t = useT('checkout_shell');
  const activeIdx = steps.findIndex((step) => step.id === activeStepId);
  const previousStep = activeIdx > 0 ? steps[activeIdx - 1] : null;
  const resolvedBackHref = backHref ?? previousStep?.href;
  const canGoBack = activeIdx > 0 && (typeof onBack === 'function' || Boolean(resolvedBackHref));
  const resolvedBackLabel = backLabel ?? t('back_to_previous_step');
  const backButton = !canGoBack ? (
    <div aria-hidden className="h-9 w-9 shrink-0" />
  ) : onBack ? (
    <Button
      variant="ghost"
      size="sm"
      className="min-w-0 shrink-0"
      data-testid="checkout-shell-back"
      onClick={() => {
        onBack();
      }}
    >
      <Icon name="ChevronRight" size="sm" mirror aria-hidden />
      <span className="truncate">{resolvedBackLabel}</span>
    </Button>
  ) : (
    <a
      href={resolvedBackHref}
      data-testid="checkout-shell-back"
      className={cn(
        'text-text-primary hover:bg-surface-hover inline-flex h-9 min-w-0 shrink-0 items-center gap-2 rounded-md px-3 text-sm font-medium',
        'focus-visible:ring-brand-primary-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1',
      )}
    >
      <Icon name="ChevronRight" size="sm" mirror aria-hidden />
      <span className="truncate">{resolvedBackLabel}</span>
    </a>
  );

  return (
    <div className={cn('bg-surface-page flex min-h-dvh flex-col', className)}>
      {/* Step nav */}
      <nav
        aria-label={t('steps_nav_label')}
        className="bg-surface-glass border-border-default sticky top-0 z-[var(--z-sticky)] border-b shadow-sm backdrop-blur-[var(--glass-blur-md)]"
      >
        <div className="mx-auto flex max-w-lg items-center gap-3 px-4 py-3">
          {backButton}
          <ol className="flex min-w-0 flex-1 items-center justify-between" data-testid="checkout-shell-steps">
          {steps.map((step, idx) => {
            const status = getStatus(steps, step, activeStepId);
            const isCurrent = status === 'active';
            const stepLabel = step.label;

            const indicator = (
              <span className={cn(stepIndicatorVariants({ status }), 'size-7')}>
                {status === 'completed' ? (
                  <svg
                    aria-hidden
                    viewBox="0 0 16 16"
                    className="size-3.5"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth={2.5}
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="M3 8l3.5 3.5L13 4.5" />
                  </svg>
                ) : (
                  <span>{idx + 1}</span>
                )}
              </span>
            );

            const isLast = idx === steps.length - 1;
            return (
              <li key={step.id} className="flex flex-1 items-center">
                <div className="flex flex-col items-center gap-1">
                  <span
                    aria-current={isCurrent ? 'step' : undefined}
                    aria-label={
                      isCurrent
                        ? `${t('step_current_aria')}: ${stepLabel}`
                        : status === 'completed'
                          ? `${t('step_completed_aria')}: ${stepLabel}`
                          : `${t('step_upcoming_aria')}: ${stepLabel}`
                    }
                  >
                    {step.href && status === 'completed' ? (
                      <a
                        href={step.href}
                        className="focus-visible:outline-brand-primary-500 rounded-full focus-visible:outline-2 focus-visible:outline-offset-2"
                      >
                        {indicator}
                      </a>
                    ) : (
                      indicator
                    )}
                  </span>
                  <span className={stepLabelVariants({ status })}>{stepLabel}</span>
                </div>
                {!isLast && (
                  <div
                    aria-hidden
                    className={cn(
                      'mx-2 h-px flex-1',
                      status === 'completed' ? 'bg-success-500' : 'bg-border-default',
                    )}
                  />
                )}
              </li>
            );
          })}
          </ol>
        </div>
      </nav>

      {/* Content */}
      <main id="main" className="mx-auto w-full max-w-lg flex-1 px-4 py-6">
        {children}
      </main>
    </div>
  );
}
