import { useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { ArrowLeft, ExternalLink } from '../../lib/icons'
import { useYoutubeViewer } from '../../stores/youtube-viewer-store'

/**
 * Full-window in-app YouTube player. Replaces the per-row
 * `<a target="_blank">` opens for trailers / featurettes / behind-the-
 * scenes clips so users don't get yanked into a browser. Uses the
 * youtube-nocookie embed with full controls + sound enabled, sized to
 * the viewport with a black backdrop and a Back button in the top-left.
 *
 * Esc closes. Clicking the dimmed area outside the player closes too.
 */
export default function YoutubeViewerModal() {
  const open = useYoutubeViewer(s => s.open)
  const videoKey = useYoutubeViewer(s => s.videoKey)
  const title = useYoutubeViewer(s => s.title)
  const subtitle = useYoutubeViewer(s => s.subtitle)
  const close = useYoutubeViewer(s => s.close)

  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') close()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [open, close])

  return (
    <AnimatePresence>
      {open && videoKey && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.22 }}
          onClick={close}
          className="fixed inset-0 z-[90] bg-black/95 backdrop-blur-md flex flex-col"
        >
          {/* Top bar: back + title + open-on-youtube link */}
          <div
            onClick={e => e.stopPropagation()}
            className="shrink-0 flex items-center gap-3 px-5 py-3 border-b border-white/8"
          >
            <button
              onClick={close}
              aria-label="Back"
              className="inline-flex items-center gap-1.5 h-9 px-3 rounded-full bg-white/8 hover:bg-white/12 ring-1 ring-white/10 hover:ring-white/20 text-[12.5px] text-white font-medium tracking-tight transition focus-ring"
            >
              <ArrowLeft size={13} stroke={2} />
              Back
            </button>
            <div className="min-w-0 flex-1">
              <p className="text-[13.5px] text-white font-semibold tracking-tight truncate">{title || 'Video'}</p>
              {subtitle && (
                <p className="text-[11px] text-white/55 truncate uppercase tracking-[0.12em] font-medium">
                  {subtitle}
                </p>
              )}
            </div>
            <a
              href={`https://www.youtube.com/watch?v=${videoKey}`}
              target="_blank"
              rel="noopener noreferrer"
              onClick={e => e.stopPropagation()}
              className="inline-flex items-center gap-1.5 h-9 px-3 rounded-full text-[11.5px] text-white/65 hover:text-white hover:bg-white/8 transition focus-ring"
              title="Open on YouTube"
            >
              YouTube
              <ExternalLink size={11} stroke={2} />
            </a>
          </div>

          {/* Player area - black to mask any letterbox the video itself
              has. The iframe is centered and capped at 16:9 aspect with
              the viewport as bound. */}
          <motion.div
            initial={{ opacity: 0, scale: 0.98 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.98 }}
            transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
            onClick={e => e.stopPropagation()}
            className="flex-1 min-h-0 grid place-items-center p-4"
          >
            <div className="w-full h-full max-w-[min(100vw-32px,calc((100vh-160px)*16/9))] aspect-video rounded-xl overflow-hidden bg-black ring-1 ring-white/8 shadow-[0_30px_80px_-20px_rgba(0,0,0,0.85)]">
              <iframe
                key={videoKey}
                src={`https://www.youtube-nocookie.com/embed/${videoKey}?autoplay=1&rel=0&modestbranding=1&iv_load_policy=3&playsinline=1`}
                title={title}
                allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
                allowFullScreen
                className="w-full h-full border-0"
              />
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  )
}
