'use client';

/**
 * ImageWithFallback Component (packages/ui)
 * 
 * Resilient image renderer that gracefully handles 404s, backend storage path errors,
 * and external image load failures with a smooth local fallback transition.
 */

import React, { useState, useEffect } from 'react';

export interface ImageWithFallbackProps extends Omit<React.ImgHTMLAttributes<HTMLImageElement>, 'src'> {
  src?: string | null;
  fallbackSrc?: string;
  unoptimized?: boolean;
}

const DEFAULT_FALLBACK = '/placeholder-service.svg';
const SVG_FALLBACK =
  'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300" fill="%23f3f4f6"><rect width="400" height="300" fill="%23FAF7F2"/><text x="50%" y="45%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-weight="bold" font-size="16" fill="%232C2825">SHINECODE</text><text x="50%" y="58%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="11" fill="%238C827A">LUXURY BEAUTY</text></svg>';

export function ImageWithFallback({
  src,
  fallbackSrc = DEFAULT_FALLBACK,
  alt = '',
  className = '',
  loading = 'lazy',
  ...props
}: ImageWithFallbackProps) {
  const initialSrc = typeof src === 'string' && src.trim() ? src : fallbackSrc;
  const [imgSrc, setImgSrc] = useState<string>(initialSrc);
  const [hasError, setHasError] = useState<boolean>(!src);

  useEffect(() => {
    if (typeof src === 'string' && src.trim()) {
      setImgSrc(src);
      setHasError(false);
    } else {
      setImgSrc(fallbackSrc);
      setHasError(true);
    }
  }, [src, fallbackSrc]);

  return (
    <img
      src={hasError ? (imgSrc || fallbackSrc) : imgSrc}
      alt={alt}
      loading={loading}
      className={`transition-opacity duration-300 ${hasError ? 'opacity-95' : 'opacity-100'} ${className}`}
      onError={() => {
        if (!hasError) {
          setHasError(true);
          setImgSrc(fallbackSrc);
        } else if (imgSrc !== SVG_FALLBACK) {
          // If local fallback file fails for any reason, use inline SVG
          setImgSrc(SVG_FALLBACK);
        }
      }}
      {...props}
    />
  );
}
