// @design-system: domain/DealImageGallery
/**
 * DealImageGallery - controlled main image viewer with thumbnail strip.
 *
 * Used on the deal detail page to display deal artwork:
 * - Full-width main image (aspect-ratio 4/3 on mobile, 16/9 on desktop)
 * - Prev/Next navigation buttons
 * - Image counter (n of total)
 * - Horizontal thumbnail strip for quick switching
 *
 * Fully controlled: parent owns `activeIndex` + `onChangeIndex`.
 * Respects prefers-reduced-motion for transitions.
 *
 * @example
 * <DealImageGallery
 *   images={images}
 *   activeIndex={activeImageIndex}
 *   onChangeIndex={setActiveImageIndex}
 * />
 */

'use client';

import { useEffect, useId, useState } from 'react';
import { cn } from '@/lib/cn';
import { Icon } from '@/components/ui/icons/Icon';
import { Image } from '@/components/ui/primitives/Image';
import { useT } from '@/lib/i18n/react';

export interface DealGalleryImage {
  id: string;
  src: string;
  alt: string;
}

export interface DealImageGalleryProps {
  images: DealGalleryImage[];
  /** Index of the currently displayed image. */
  activeIndex: number;
  /** Called with the new index when the user navigates. */
  onChangeIndex: (index: number) => void;
  className?: string;
  /** When true, main image loads eagerly (above fold). @default false */
  prioritizeFirst?: boolean;
  sharedElementName?: string;
}

function usePrefersReducedMotion(): boolean {
  const [prefersReducedMotion, setPrefersReducedMotion] = useState(true);

  useEffect(() => {
    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
    const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
    const sync = () => setPrefersReducedMotion(mediaQuery.matches);
    sync();
    mediaQuery.addEventListener('change', sync);
    return () => mediaQuery.removeEventListener('change', sync);
  }, []);

  return prefersReducedMotion;
}

export function DealImageGallery({
  images,
  activeIndex,
  onChangeIndex,
  className,
  prioritizeFirst = false,
  sharedElementName,
}: DealImageGalleryProps) {
  const t = useT('deal_detail');
  const galleryId = useId();
  const prefersReducedMotion = usePrefersReducedMotion();

  if (images.length === 0) return null;

  const total = images.length;
  const safeIndex = Math.max(0, Math.min(activeIndex, total - 1));
  const active = images[safeIndex]!;
  const viewTransitionName =
    !prefersReducedMotion && safeIndex === 0 && sharedElementName ? sharedElementName : 'none';

  const goPrev = () => onChangeIndex((activeIndex - 1 + total) % total);
  const goNext = () => onChangeIndex((activeIndex + 1) % total);

  return (
    <div className={cn('flex flex-col', className)} role="region" aria-label={t('gallery_label')}>
      {/* Main image */}
      <div
        data-shared-transition="deal-detail-hero"
        className="bg-surface-inset relative aspect-[4/3] w-full overflow-hidden"
        style={{ viewTransitionName }}
      >
        <Image
          src={active.src}
          alt={active.alt}
          width={1200}
          height={900}
          loading={prioritizeFirst && activeIndex === 0 ? 'eager' : 'lazy'}
          fetchpriority={prioritizeFirst && activeIndex === 0 ? 'high' : 'auto'}
          className="absolute inset-0 h-full w-full object-cover"
        />

        {/* Prev / Next buttons - only shown when multiple images */}
        {total > 1 && (
          <>
            <button
              type="button"
              onClick={goPrev}
              aria-label={t('image_prev')}
              className={cn(
                'absolute start-2 top-1/2 z-10 flex -translate-y-1/2 items-center justify-center',
                'h-9 w-9 rounded-full',
                'bg-surface-overlay/80 text-text-primary backdrop-blur-sm',
                'shadow-[var(--shadow-sm)]',
                'transition-colors duration-[var(--duration-fast)]',
                'hover:bg-surface-overlay',
                'focus-visible:outline-brand-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
              )}
            >
              <Icon name="ChevronLeft" size="sm" mirror />
            </button>

            <button
              type="button"
              onClick={goNext}
              aria-label={t('image_next')}
              className={cn(
                'absolute end-2 top-1/2 z-10 flex -translate-y-1/2 items-center justify-center',
                'h-9 w-9 rounded-full',
                'bg-surface-overlay/80 text-text-primary backdrop-blur-sm',
                'shadow-[var(--shadow-sm)]',
                'transition-colors duration-[var(--duration-fast)]',
                'hover:bg-surface-overlay',
                'focus-visible:outline-brand-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
              )}
            >
              <Icon name="ChevronRight" size="sm" mirror />
            </button>
          </>
        )}

        {/* Counter badge - bottom-end corner */}
        {total > 1 && (
          <div
            aria-live="polite"
            aria-atomic="true"
            className="absolute end-3 bottom-3 rounded-full bg-black/50 px-2.5 py-1 text-xs font-medium text-white backdrop-blur-sm"
          >
            {t('image_n_of_total')
              .replace('{n}', String(activeIndex + 1))
              .replace('{total}', String(total))}
          </div>
        )}
      </div>

      {/* Thumbnail strip - only shown when 2+ images */}
      {total > 1 && (
        <div
          role="list"
          aria-label={t('gallery_thumbnails')}
          className="flex [scrollbar-width:none] gap-2 overflow-x-auto px-4 py-3 [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden"
          id={`${galleryId}-thumbnails`}
        >
          {images.map((img, index) => (
            <button
              key={img.id}
              type="button"
              onClick={() => onChangeIndex(index)}
              aria-label={`${t('gallery_thumbnail_n').replace('{n}', String(index + 1))}`}
              aria-current={index === activeIndex ? 'true' : undefined}
              className={cn(
                'relative h-16 w-16 shrink-0 overflow-hidden rounded-md',
                'transition-all duration-[var(--duration-fast)]',
                'focus-visible:outline-brand-primary-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
                index === activeIndex
                  ? 'ring-2 ring-[var(--color-brand-primary-500)] ring-offset-1'
                  : 'opacity-60 hover:opacity-100',
              )}
            >
              <Image
                src={img.src}
                alt=""
                decorative
                aria-hidden
                loading="lazy"
                fetchpriority="auto"
                className="h-full w-full object-cover"
              />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
