'use client';

import React, { useState, useEffect } from 'react';
import { X, Maximize2 } from 'lucide-react';

interface LightboxImageProps {
  src: string;
  alt: string;
  position?: string;
  zoom?: number;
  className?: string;
}

export default function LightboxImage({ 
  src, 
  alt, 
  position = "50% 50%", 
  zoom = 1,
  className = "w-full h-full object-cover" 
}: LightboxImageProps) {
  const [isOpen, setIsOpen] = useState(false);

  // Close on Escape key
  useEffect(() => {
    const handleEsc = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setIsOpen(false);
    };
    window.addEventListener('keydown', handleEsc);
    return () => window.removeEventListener('keydown', handleEsc);
  }, []);

  // Prevent scroll when open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = 'unset';
    }
    return () => { document.body.style.overflow = 'unset'; };
  }, [isOpen]);

  return (
    <>
      <div 
        className="relative group cursor-zoom-in w-full h-full overflow-hidden"
        onClick={() => setIsOpen(true)}
      >
        <img
          src={src}
          alt={alt}
          className={className}
          style={{ 
            objectPosition: position,
            transform: `scale(${zoom})`,
            transformOrigin: position
          }}
        />
        <div className="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all flex items-center justify-center opacity-0 group-hover:opacity-100">
          <div className="bg-white/20 backdrop-blur-md p-3 rounded-full text-white scale-90 group-hover:scale-100 transition-all">
            <Maximize2 className="w-6 h-6" />
          </div>
        </div>
      </div>

      {/* Lightbox Overlay */}
      {isOpen && (
        <div 
          className="fixed inset-0 z-[9999] bg-black/95 flex items-center justify-center p-4 md:p-12 animate-in fade-in duration-300"
          onClick={() => setIsOpen(false)}
        >
          <button 
            className="absolute top-6 right-6 p-3 bg-white/10 hover:bg-white/20 text-white rounded-full transition-colors z-[10000]"
            onClick={(e) => {
              e.stopPropagation();
              setIsOpen(false);
            }}
          >
            <X className="w-6 h-6" />
          </button>

          <div 
            className="relative w-full h-full flex items-center justify-center cursor-zoom-out"
          >
            <img
              src={src}
              alt={alt}
              className="max-w-full max-h-full object-contain shadow-2xl animate-in zoom-in-95 duration-300"
            />
            
            {/* Legend / Caption */}
            <div className="absolute bottom-0 left-0 right-0 p-6 bg-gradient-to-t from-black/80 to-transparent text-white text-center">
              <p className="text-lg font-medium">{alt}</p>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
