'use client';

import React, { useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { X } from 'lucide-react';

interface VideoModalProps {
  isOpen: boolean;
  onClose: () => void;
  /**
   * Fully-qualified HTTPS URL to the video asset (e.g. CloudFront URL pointing to S3 object).
   */
  videoUrl: string;
  title?: string;
  /**
   * Whether the video should start playing automatically when the modal opens.
   * Defaults to false to avoid unnecessary bandwidth usage for large CDN-hosted videos.
   */
  autoPlay?: boolean;
}

export const VideoModal: React.FC<VideoModalProps> = ({
  isOpen,
  onClose,
  videoUrl,
  title,
  autoPlay = false,
}) => {
  // Lock page scroll when modal is open.
  // - "Modern" part: toggle a dataset on <html>, letting CSS handle overflow.
  // - Robust fallback: also freeze <body> position to prevent iOS/Safari scroll bleed.
  useEffect(() => {
    const body = document.body;
    const html = document.documentElement;

    const prevHtmlDataset = html.dataset.modalOpen;
    const prevHtmlOverflow = html.style.overflow;

    const prevBodyOverflow = body.style.overflow;
    const prevBodyPosition = body.style.position;
    const prevBodyTop = body.style.top;
    const prevBodyLeft = body.style.left;
    const prevBodyRight = body.style.right;
    const prevBodyWidth = body.style.width;
    const prevBodyPaddingRight = body.style.paddingRight;

    const scrollY = window.scrollY || html.scrollTop || body.scrollTop || 0;

    const lock = () => {
      // Prefer CSS-driven scroll lock
      html.dataset.modalOpen = 'true';

      // Fallback/extra safety: also set overflow inline (in case CSS isn't loaded yet)
      html.style.overflow = 'hidden';
      body.style.overflow = 'hidden';

      // Compensate for the missing scrollbar to avoid layout shift in browsers
      // that don't support `scrollbar-gutter: stable`.
      const scrollbarWidth = window.innerWidth - html.clientWidth;
      if (scrollbarWidth > 0) body.style.paddingRight = `${scrollbarWidth}px`;

      // Freeze scroll position (important for iOS/Safari where overflow hidden isn't enough)
      body.style.position = 'fixed';
      body.style.top = `-${scrollY}px`;
      body.style.left = '0';
      body.style.right = '0';
      body.style.width = '100%';
    };

    const unlock = () => {
      if (prevHtmlDataset === undefined) delete html.dataset.modalOpen;
      else html.dataset.modalOpen = prevHtmlDataset;

      html.style.overflow = prevHtmlOverflow;
      body.style.overflow = prevBodyOverflow;
      body.style.position = prevBodyPosition;
      body.style.top = prevBodyTop;
      body.style.left = prevBodyLeft;
      body.style.right = prevBodyRight;
      body.style.width = prevBodyWidth;
      body.style.paddingRight = prevBodyPaddingRight;

      // Restore scroll position
      window.scrollTo(0, scrollY);
    };

    if (isOpen) lock();
    return () => {
      if (isOpen) unlock();
    };
  }, [isOpen]);

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 z-[60] bg-slate-900/80 backdrop-blur-md flex items-center justify-center p-4 md:p-8"
          >
            {/* Modal Container */}
            <motion.div
              initial={{ scale: 0.95, opacity: 0, y: 20 }}
              animate={{ scale: 1, opacity: 1, y: 0 }}
              exit={{ scale: 0.95, opacity: 0, y: 20 }}
              transition={{ type: "spring", damping: 25, stiffness: 300 }}
              onClick={(e) => e.stopPropagation()}
              className="relative w-full max-w-6xl bg-black rounded-2xl overflow-hidden shadow-2xl shadow-black/50 aspect-video ring-1 ring-white/10"
            >
              {/* Header/Close */}
              <div className="absolute top-0 left-0 right-0 z-20 p-4 flex justify-between items-start bg-gradient-to-b from-black/60 to-transparent pointer-events-none">
                {title && (
                  <h3 className="text-white/90 font-medium text-lg pl-2 drop-shadow-md">{title}</h3>
                )}
                <button 
                  onClick={onClose}
                  className="pointer-events-auto bg-black/20 hover:bg-white/20 backdrop-blur-sm text-white rounded-full p-2 transition-colors border border-white/10"
                >
                  <X size={24} />
                </button>
              </div>

              {/* Video Player */}
              <div className="w-full h-full flex items-center justify-center bg-black">
                <video
                  key={videoUrl}
                  src={videoUrl}
                  controls
                  preload="none" // don't download video data until user actually interacts
                  autoPlay={autoPlay}
                  // Some browsers require muted for autoplay to work without user gesture
                  muted={autoPlay}
                  playsInline
                  className="w-full h-full object-contain"
                >
                  Your browser does not support the video tag.
                </video>
              </div>
            </motion.div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
};
