'use client';

import { useEffect, useRef } from 'react';

interface ImageZoomModalProps {
  imageUrl: string | null;
  onClose: () => void;
}

export const ImageZoomModal = ({ imageUrl, onClose }: ImageZoomModalProps) => {
  const closeButtonRef = useRef<HTMLButtonElement>(null);
  const modalRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        onClose();
      }
    };

    if (imageUrl) {
      document.addEventListener('keydown', handleEscape);

      // Focus trap
      const previousActiveElement = document.activeElement as HTMLElement;
      closeButtonRef.current?.focus();

      // Disable body scroll
      document.body.style.overflow = 'hidden';

      return () => {
        document.removeEventListener('keydown', handleEscape);
        document.body.style.overflow = '';
        previousActiveElement?.focus();
      };
    }

    return () => {
      document.removeEventListener('keydown', handleEscape);
    };
  }, [imageUrl, onClose]);

  if (!imageUrl) return null;

  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (e.target === modalRef.current) {
      onClose();
    }
  };

  return (
    <div
      ref={modalRef}
      className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 sm:p-6 md:p-8"
      onClick={handleBackdropClick}
      role="dialog"
      aria-modal="true"
      aria-labelledby="modal-title"
    >
      <div className="absolute top-4 right-4 sm:top-6 sm:right-6 flex items-center gap-3">
        <span id="modal-title" className="sr-only">Full size image viewer</span>
        <span className="hidden sm:block text-white/70 text-sm font-medium">Press ESC to close</span>
        <button
          ref={closeButtonRef}
          onClick={onClose}
          className="w-11 h-11 sm:w-12 sm:h-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition-colors focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-black/90"
          aria-label="Close zoomed image"
        >
          <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
      <img
        src={imageUrl}
        alt="Full size view"
        className="max-w-full max-h-full object-contain rounded-lg"
        onClick={(e) => e.stopPropagation()}
      />
    </div>
  );
};
