'use client';

import { useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';

export type CheckoutStep = 'items' | 'summary' | 'negotiation' | 'event' | 'pay';

/**
 * Feature 054 (US3, T037) — Conditional Stepper ordering.
 *
 * Default order is `items → summary → event → pay` (4 steps). When the booking
 * lifecycle is `customer_review`, `negotiation` is inserted between `summary`
 * and `event`. Most checkouts never see negotiation; today's pre-US3 hard-coded
 * 5-step stepper implied otherwise (C1).
 */
const BASE_ORDER: CheckoutStep[] = ['items', 'summary', 'event', 'pay'];
const NEGOTIATION_ORDER: CheckoutStep[] = ['items', 'summary', 'negotiation', 'event', 'pay'];

/**
 * Loosely typed to accept any `Booking['lifecycle_status']` string the
 * backend may emit (`'draft' | 'submitted' | 'customer_review' | ...`).
 * Only the `customer_review` branch matters for the conditional ordering.
 */
export function resolveStepperOrder(lifecycleStatus?: string | null): CheckoutStep[] {
  return lifecycleStatus === 'customer_review' ? NEGOTIATION_ORDER : BASE_ORDER;
}

export function Stepper({
  current,
  lifecycleStatus,
}: {
  current: CheckoutStep;
  lifecycleStatus?: string | null;
}) {
  const t = useTranslations('checkout');
  const order = resolveStepperOrder(lifecycleStatus);
  const currentIndex = order.indexOf(current);

  return (
    <nav role="navigation" aria-label="Checkout steps">
      <ol className="mb-8 flex w-full items-center gap-2 text-xs font-medium" data-testid="checkout-stepper">
        {order.map((step, idx) => {
          const reached = idx <= currentIndex;
          const isActive = idx === currentIndex;
          return (
            <li
              key={step}
              className="flex flex-1 items-center gap-2"
              aria-current={isActive ? 'step' : undefined}
              data-step={step}
            >
              <span
                className={cn(
                  'flex h-7 w-7 items-center justify-center rounded-full border text-xs',
                  reached ? 'border-primary-600 bg-primary-600 text-white' : 'border-neutral-300 text-neutral-500',
                  isActive && 'ring-2 ring-primary-200',
                )}
              >
                {idx + 1}
              </span>
              <span className={cn('hidden sm:inline', reached ? 'text-neutral-900' : 'text-neutral-500')}>
                {t(`steps.${step}`)}
              </span>
              {idx < order.length - 1 && (
                <span className={cn('h-px flex-1', idx < currentIndex ? 'bg-primary-600' : 'bg-neutral-200')} />
              )}
            </li>
          );
        })}
      </ol>
    </nav>
  );
}
