import { useEffect, useRef, useState } from 'react'
import Plyr from 'plyr'
import { mediaUrl } from '../api/client'
import AdSlot from './AdSlot'

/**
 * Advanced HTML5 player (Plyr): quality/speed/fullscreen/keyboard shortcuts.
 * Injects "Watch Ad Break" popups at the configured interval — playback pauses
 * until the user dismisses the ad.
 */
export default function Player({ video, onFirstPlay }) {
  const videoRef = useRef(null)
  const plyrRef = useRef(null)
  const nextBreakRef = useRef(Infinity)
  const firstPlayFired = useRef(false)
  const [adBreak, setAdBreak] = useState(false)

  const source = video.source
  const interval = video.ad_break?.enabled ? video.ad_break.interval : null

  useEffect(() => {
    if (!videoRef.current || source?.type !== 'file') return

    const player = new Plyr(videoRef.current, {
      settings: ['quality', 'speed', 'loop'],
      speed: { selected: 1, options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2] },
      keyboard: { focused: true, global: true },
      tooltips: { controls: true, seek: true },
    })
    plyrRef.current = player

    if (interval && interval > 0) nextBreakRef.current = interval

    const onPlay = () => {
      if (!firstPlayFired.current) {
        firstPlayFired.current = true
        onFirstPlay?.()
      }
    }

    const onTime = () => {
      const t = player.currentTime
      if (interval && t >= nextBreakRef.current) {
        nextBreakRef.current += interval
        player.pause()
        setAdBreak(true)
      }
    }

    player.on('playing', onPlay)
    player.on('timeupdate', onTime)

    return () => {
      player.off('playing', onPlay)
      player.off('timeupdate', onTime)
      player.destroy()
      plyrRef.current = null
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [source?.url])

  const resume = () => {
    setAdBreak(false)
    plyrRef.current?.play()
  }

  if (!source?.url) return null

  return (
    <div className="relative overflow-hidden rounded-2xl bg-black ring-1 ring-gray-200 dark:ring-gray-800">
      {source.type === 'file' ? (
        <video
          ref={videoRef}
          poster={mediaUrl(video.thumbnail)}
          playsInline
          controls
        >
          <source src={mediaUrl(source.url)} type="video/mp4" />
        </video>
      ) : (
        <div className="aspect-video">
          <iframe
            src={mediaUrl(source.url)}
            title={video.title}
            className="h-full w-full"
            allow="autoplay; fullscreen; picture-in-picture"
            allowFullScreen
          />
        </div>
      )}

      {/* In-video ad break popup */}
      {adBreak && (
        <div className="absolute inset-0 z-20 flex items-center justify-center bg-black/85 p-4 backdrop-blur-sm">
          <div className="w-full max-w-md rounded-2xl bg-white p-5 text-center shadow-2xl dark:bg-gray-900">
            <p className="mb-1 text-xs font-bold uppercase tracking-wide text-rose-500">
              Ad Break
            </p>
            <h3 className="mb-4 text-lg font-bold">Watch this ad to continue</h3>
            <AdSlot placement="in_player" className="mb-4 bg-gray-50 dark:bg-gray-800" />
            <button
              onClick={resume}
              className="w-full rounded-xl bg-[var(--brand)] py-2.5 font-semibold text-white transition hover:opacity-90"
            >
              ▶ Resume video
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
