import { useState } from 'react';
import { cn } from '@/lib/utils';

interface WebpImageProps extends React.ImgHTMLAttributes<HTMLImageElement> {
  /** Base path without extension, e.g., "/img/button/button_claim" */
  src: string;
  /** Alt text for accessibility */
  alt: string;
  /** Additional CSS classes */
  className?: string;
  /** Whether to use priority loading (for LCP images) */
  priority?: boolean;
  /** Width for the image */
  width?: number;
  /** Height for the image */
  height?: number;
  /** Whether to skip WebP and use PNG directly */
  skipWebp?: boolean;
}

/**
 * WebpImage Component
 * 
 * Automatically serves WebP format with PNG fallback.
 * Reduces image size significantly while maintaining quality.
 * 
 * @example
 * ```tsx
 * <WebpImage
 *   src="/img/button/button_claim"
 *   alt="Claim Button"
 *   width={309}
 *   height={68}
 *   className="h-8 object-contain"
 * />
 * ```
 */
export function WebpImage({
  src,
  alt,
  className,
  priority = false,
  width,
  height,
  skipWebp = false,
  style,
  ...props
}: WebpImageProps) {
  const [useFallback, setUseFallback] = useState(false);

  // Determine the actual paths
  const hasExtension = src.match(/\.(png|webp|jpg|jpeg)$/i);
  const basePath = hasExtension ? src.replace(/\.(png|webp|jpg|jpeg)$/i, '') : src;
  
  const webpSrc = `${basePath}.webp`;
  const fallbackSrc = `${basePath}.png`;

  // If skipWebp or already failed to load WebP, use fallback
  const actualSrc = skipWebp || useFallback ? fallbackSrc : webpSrc;

  return (
    <img
      src={actualSrc}
      alt={alt}
      width={width}
      height={height}
      loading={priority ? 'eager' : 'lazy'}
      decoding={priority ? 'sync' : 'async'}
      onError={() => {
        if (!skipWebp && !useFallback) {
          setUseFallback(true);
        }
      }}
      className={cn(className)}
      style={{
        ...style,
        // Prevent layout shift
        aspectRatio: width && height ? `${width}/${height}` : undefined,
      }}
      {...props}
    />
  );
}

interface PictureImageProps extends WebpImageProps {
  /** Whether to use picture element with source */
  usePicture?: boolean;
}

/**
 * PictureImage Component
 * 
 * Uses <picture> element with WebP source and PNG fallback.
 * Better for SEO and older browser support.
 * 
 * @example
 * ```tsx
 * <PictureImage
 *   src="/img/button/button_claim"
 *   alt="Claim Button"
 *   width={309}
 *   height={68}
 *   className="h-8 object-contain"
 * />
 * ```
 */
export function PictureImage({
  src,
  alt,
  className,
  priority = false,
  width,
  height,
  style,
  ...props
}: PictureImageProps) {
  const hasExtension = src.match(/\.(png|webp|jpg|jpeg)$/i);
  const basePath = hasExtension ? src.replace(/\.(png|webp|jpg|jpeg)$/i, '') : src;
  
  const webpSrc = `${basePath}.webp`;
  const pngSrc = `${basePath}.png`;

  return (
    <picture>
      <source srcSet={webpSrc} type="image/webp" />
      <img
        src={pngSrc}
        alt={alt}
        width={width}
        height={height}
        loading={priority ? 'eager' : 'lazy'}
        decoding={priority ? 'sync' : 'async'}
        className={cn(className)}
        style={{
          ...style,
          aspectRatio: width && height ? `${width}/${height}` : undefined,
        }}
        {...props}
      />
    </picture>
  );
}

/**
 * BackgroundImage Component
 * 
 * For background images with WebP support via CSS.
 * 
 * @example
 * ```tsx
 * <BackgroundImage
 *   src="/img/step/bg"
 *   className="w-full h-32"
 * />
 * ```
 */
interface BackgroundImageProps extends React.HTMLAttributes<HTMLDivElement> {
  /** Base path without extension */
  src: string;
  /** Additional CSS classes */
  className?: string;
  /** Background size */
  size?: 'cover' | 'contain' | string;
  /** Background position */
  position?: string;
  /** Background repeat */
  repeat?: string;
}

export function BackgroundImage({
  src,
  className,
  size = 'cover',
  position = 'center',
  repeat = 'no-repeat',
  style,
  ...props
}: BackgroundImageProps) {
  const hasExtension = src.match(/\.(png|webp|jpg|jpeg)$/i);
  const basePath = hasExtension ? src.replace(/\.(png|webp|jpg|jpeg)$/i, '') : src;
  
  const webpUrl = `${basePath}.webp`;
  const pngUrl = `${basePath}.png`;

  return (
    <div
      className={cn(className)}
      style={{
        ...style,
        backgroundImage: `url(${webpUrl}), url(${pngUrl})`,
        backgroundSize: size,
        backgroundPosition: position,
        backgroundRepeat: repeat,
      }}
      {...props}
    />
  );
}
