'use client'

import { useState, useEffect, useRef, useCallback } from 'react'
import styles from './Intro.module.css'

interface IntroProps {
  onEnter: () => void
}

export default function Intro({ onEnter }: IntroProps) {
  const [videoReady, setVideoReady] = useState(false)
  const [isMobile, setIsMobile] = useState(false)
  const [videoFailed, setVideoFailed] = useState(false)
  const videoRef = useRef<HTMLVideoElement>(null)

  // Detect mobile/touch device
  useEffect(() => {
    const checkMobile = () => {
      const mobile = window.matchMedia('(max-width: 768px)').matches ||
        'ontouchstart' in window ||
        navigator.maxTouchPoints > 0
      setIsMobile(mobile)
    }
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  // On mobile, skip video and show static intro
  useEffect(() => {
    if (isMobile) {
      setVideoReady(true)
    }
  }, [isMobile])

  // Pause video 500ms before end to keep PRIME title visible
  useEffect(() => {
    if (isMobile) return

    const video = videoRef.current
    if (!video) return

    const checkTime = () => {
      if (video.duration && video.currentTime >= video.duration - 0.5) {
        video.pause()
        setVideoReady(true)
      }
    }

    const handleError = () => {
      setVideoFailed(true)
      setVideoReady(true)
    }

    const handleCanPlay = () => {
      // Video loaded successfully
      video.play().catch(() => {
        // Autoplay blocked, show static
        setVideoFailed(true)
        setVideoReady(true)
      })
    }

    video.addEventListener('timeupdate', checkTime)
    video.addEventListener('error', handleError)
    video.addEventListener('canplay', handleCanPlay)

    return () => {
      video.removeEventListener('timeupdate', checkTime)
      video.removeEventListener('error', handleError)
      video.removeEventListener('canplay', handleCanPlay)
    }
  }, [isMobile])

  const handleEnter = useCallback(() => {
    onEnter()
  }, [onEnter])

  // Handle any interaction - can skip at any time
  useEffect(() => {
    const handleInteraction = () => handleEnter()

    window.addEventListener('click', handleInteraction)
    window.addEventListener('keydown', handleInteraction)
    window.addEventListener('touchstart', handleInteraction)

    return () => {
      window.removeEventListener('click', handleInteraction)
      window.removeEventListener('keydown', handleInteraction)
      window.removeEventListener('touchstart', handleInteraction)
    }
  }, [handleEnter])

  const showStaticIntro = isMobile || videoFailed

  return (
    <div className={styles.intro}>
      {showStaticIntro ? (
        // Static intro for mobile or video fallback
        <div className={styles.staticIntro}>
          <div className={styles.staticLogo}>
            <span className={styles.primeText}>PRIME</span>
          </div>
          <div className={styles.staticTagline}>
            Not stronger. Different.
          </div>
        </div>
      ) : (
        // Video intro for desktop
        <video
          ref={videoRef}
          className={styles.video}
          autoPlay
          muted
          playsInline
          preload="auto"
        >
          <source src="/intro.mp4" type="video/mp4" />
        </video>
      )}

      {/* Prompt - always visible */}
      <div className={`${styles.prompt} ${styles.visible} ${videoReady ? styles.ready : ''}`}>
        <span>{videoReady ? (isMobile ? 'Tap to enter' : 'Click anywhere to enter') : 'Skip'}</span>
      </div>
    </div>
  )
}
