'use client'

import { useEffect, useRef } from 'react'

interface Props {
  url: string
  name: string
  onClose: () => void
}

export default function VideoPlayerModal({ url, name, onClose }: Props) {
  const overlayRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handleKey)
    document.body.style.overflow = 'hidden'
    return () => {
      document.removeEventListener('keydown', handleKey)
      document.body.style.overflow = ''
    }
  }, [onClose])

  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === overlayRef.current) onClose()
  }

  return (
    <div
      ref={overlayRef}
      className="fixed inset-0 z-50 flex flex-col items-center justify-center p-4 gap-3"
      style={{ backgroundColor: 'rgba(0,0,0,0.9)' }}
      onClick={handleOverlayClick}
    >
      {/* Toolbar */}
      <div className="flex items-center justify-between w-full max-w-4xl">
        <span className="text-sm truncate max-w-[80%]" style={{ color: 'var(--text-secondary)' }}>
          {name}
        </span>
        <button
          onClick={onClose}
          className="w-8 h-8 rounded-full flex items-center justify-center text-sm flex-shrink-0 transition-colors"
          style={{ backgroundColor: 'var(--surface)', color: 'var(--text-primary)' }}
          onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface-hover)')}
          onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface)')}
          aria-label="Close"
        >
          ✕
        </button>
      </div>

      {/* Video */}
      <video
        src={url}
        controls
        autoPlay
        className="w-full max-w-4xl max-h-[80vh] rounded-lg"
        style={{ backgroundColor: '#000' }}
        onClick={(e) => e.stopPropagation()}
      />
    </div>
  )
}
