import { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ROUTE_PATHS } from '../app/route-paths'
import { playSound, SFX_BUTTON_DEFAULT } from '../lib/sounds'
import { supportsFullscreen } from '../lib/platform'
import styles from './IntroPage.module.css'

const SPONSORS = [
  { name: 'Bently Nevada', src: '/sponsors/bently.png', dark: false, url: 'https://www.bakerhughes.com/bently-nevada' },
  { name: 'Microsoft', src: '/sponsors/microsoft.png', dark: false, url: 'https://www.microsoft.com' },
  { name: 'Ridgeline', src: '/sponsors/ridgeline.png', dark: false, url: 'https://www.ridgelineapps.com' },
  { name: 'AVA Logistics', src: '/sponsors/ava.svg', dark: false, url: 'https://avalogistics.com/' },
  { name: 'Coffee n Comics', src: '/sponsors/cnc.png', dark: false, url: 'https://www.coffeencomics.com' },
  { name: 'Type III', src: '/sponsors/typethree.png', dark: true, url: 'https://typeiii.com' },
]

const UNR_URL = 'https://www.unr.edu'

export function IntroPage() {
  const navigate = useNavigate()
  const videoRef = useRef<HTMLVideoElement>(null)
  const [cameraReady, setCameraReady] = useState(false)
  const [cameraDenied, setCameraDenied] = useState(false)
  const [noHwAccel, setNoHwAccel] = useState(false)

  useEffect(() => {
    const canvas = document.createElement('canvas')
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl')
    if (gl) {
      const dbg = (gl as WebGLRenderingContext).getExtension('WEBGL_debug_renderer_info')
      if (dbg) {
        const renderer = (gl as WebGLRenderingContext).getParameter(dbg.UNMASKED_RENDERER_WEBGL)
        if (/swiftshader|software/i.test(renderer)) {
          setNoHwAccel(true)
        }
      }
    }
  }, [])

  const enableCamera = useCallback(() => {
    playSound(SFX_BUTTON_DEFAULT)
    navigator.mediaDevices.getUserMedia({ video: true })
      .then((stream) => {
        if (videoRef.current) {
          videoRef.current.srcObject = stream
        }
        setCameraReady(true)
      })
      .catch(() => {
        setCameraDenied(true)
      })
  }, [])

  const goFullscreen = () => {
    document.documentElement.requestFullscreen().catch(() => {})
    navigate(ROUTE_PATHS.home)
  }

  const goWindowed = () => {
    navigate(ROUTE_PATHS.home)
  }

  return (
    <div className={styles.root}>
{/* hidden video element to hold the stream */}
      <video ref={videoRef} autoPlay playsInline muted hidden />
      <div className={styles.inner}>
        <div className={styles.header}>
          <p className={`${styles.event} font-caption`}>
            BIGGEST LITTLE HACKATHON 2026
          </p>
          <h1 className={`${styles.title} font-display`}>HACK HACK REVOLUTION</h1>
          <p className={`${styles.description} font-body`}>
            A dance-powered arcade experience. Step on the arrows, hit the beat, claim the leaderboard.
          </p>
        </div>

        {noHwAccel && (
          <div className={styles.actions}>
            <p className={`${styles.hwWarning} font-body`}>
              Hardware acceleration appears to be OFF — the game might be janky.
              For best performance, enable it in browser settings and restart.
            </p>
            <button
              type="button"
              className={`${styles.btn} ${styles.btnSecondary} font-title`}
              onClick={() => setNoHwAccel(false)}
            >
              CONTINUE ANYWAY
            </button>
          </div>
        )}

        {!cameraReady && !cameraDenied && (
          <div className={styles.actions}>
            <button
              type="button"
              className={`${styles.btn} ${styles.btnPrimary} font-title`}
              onClick={enableCamera}
            >
              ENABLE CAMERA
            </button>
            <p className={`${styles.cameraHint} font-caption`}>
              This game uses your webcam to detect dance moves
            </p>
          </div>
        )}

        {cameraDenied && (
          <div className={styles.actions}>
            <p className={`${styles.cameraDenied} font-body`}>
              Camera access is required to play. Please allow camera access and try again.
            </p>
            <button
              type="button"
              className={`${styles.btn} ${styles.btnSecondary} font-title`}
              onClick={enableCamera}
            >
              TRY AGAIN
            </button>
          </div>
        )}

        {cameraReady && (
          <div className={styles.actionsRow}>
            {supportsFullscreen() ? (
              <>
                <button
                  type="button"
                  className={`${styles.btn} ${styles.btnPrimary} font-title`}
                  onClick={() => {
                    playSound(SFX_BUTTON_DEFAULT)
                    goFullscreen()
                  }}
                >
                  FULLSCREEN
                </button>
                <button
                  type="button"
                  className={`${styles.btn} ${styles.btnSecondary} font-title`}
                  onClick={() => {
                    playSound(SFX_BUTTON_DEFAULT)
                    goWindowed()
                  }}
                >
                  WINDOWED
                </button>
              </>
            ) : (
              <button
                type="button"
                className={`${styles.btn} ${styles.btnPrimary} font-title`}
                onClick={() => {
                  playSound(SFX_BUTTON_DEFAULT)
                  goWindowed()
                }}
              >
                START
              </button>
            )}
          </div>
        )}

        <section className={styles.sponsors}>
          <p className={`${styles.sponsorLabel} font-caption`}>PRESENTED AT UNR &middot; SPONSORED BY</p>
          <div className={styles.sponsorLogos}>
            <a href={UNR_URL} target="_blank" rel="noopener noreferrer">
              <img className={styles.logo} src="/sponsors/unr.svg" alt="University of Nevada, Reno" />
            </a>
            {SPONSORS.map((s) => (
              <a key={s.name} href={s.url} target="_blank" rel="noopener noreferrer">
                <img className={`${styles.logo}${s.dark ? ` ${styles.logoDark}` : ''}`} src={s.src} alt={s.name} />
              </a>
            ))}
          </div>
        </section>
      </div>
    </div>
  )
}
