'use client';

/**
 * ImageWithFallback Component (apps/web)
 * 
 * Next.js Image wrapper that gracefully catches 404s, broken URLs,
 * and load errors, falling back seamlessly to a high-quality local image.
 */

import React, { useState } from 'react';
import Image, { type ImageProps } from 'next/image';

export interface ImageWithFallbackProps extends Omit<ImageProps, 'src'> {
  src?: string | null;
  fallbackSrc?: string;
}

const LOCAL_FALLBACK = '/images/fallback-placeholder.svg';

export function ImageWithFallback({
  src,
  fallbackSrc = LOCAL_FALLBACK,
  alt = '',
  className = '',
  unoptimized,
  ...props
}: ImageWithFallbackProps) {
  const [failedSrc, setFailedSrc] = useState<string | null>(null);

  const hasFailed = failedSrc === src || !src;
  const effectiveSrc = !hasFailed && typeof src === 'string' && src.trim() ? src : fallbackSrc;

  // For local network / API storage images or SVG files, bypass server-side Next.js optimization
  const isDirectImage =
    unoptimized ??
    (typeof effectiveSrc === 'string' &&
      (effectiveSrc.includes('192.168.') ||
        effectiveSrc.includes('localhost') ||
        effectiveSrc.includes('127.0.0.1') ||
        effectiveSrc.endsWith('.svg')));

  return (
    <Image
      {...props}
      src={effectiveSrc}
      alt={alt}
      className={className}
      unoptimized={isDirectImage}
      onError={() => {
        if (src) setFailedSrc(src);
      }}
    />
  );
}

export default ImageWithFallback;
