import { useEffect, useRef } from "react"
import { useTranslation } from "react-i18next"
import styles from "./drone.module.css"

export default function Drone() {
  const { t } = useTranslation("services")
  const videoRef = useRef<HTMLVideoElement | null>(null)
  const sourceRef = useRef<HTMLSourceElement | null>(null)

  useEffect(() => {
    function setVideoDroneQuality() {
      if (!sourceRef.current || !videoRef.current) return

      const videoSources = {
        fullHD: "static/home/video/drone-background-video-1080p.mp4", // For desktops (1920x1080)
        hd: "static/home/video/drone-background-video-720p.mp4",      // For tablets/smaller screens (1280x720)
        lowRes: "static/home/video/drone-background-video-480p.mp4"   // For mobile devices or low performance (854x480)
      }

      const screenWidth = window.innerWidth

      // Pick appropriate source
      if (screenWidth >= 1920) {
        sourceRef.current.src =
          "https://vontor-cz.s3.eu-central-1.amazonaws.com/" + videoSources.fullHD
      } else if (screenWidth >= 1280) {
        sourceRef.current.src =
          "https://vontor-cz.s3.eu-central-1.amazonaws.com/" + videoSources.hd
      } else {
        sourceRef.current.src =
          "https://vontor-cz.s3.eu-central-1.amazonaws.com/" + videoSources.lowRes
      }

      // Reload video
      videoRef.current.load()
      console.log("Drone video set!")
    }

    // Run once on mount
    setVideoDroneQuality()

    // Optional: rerun on resize
    window.addEventListener("resize", setVideoDroneQuality)
    return () => {
      window.removeEventListener("resize", setVideoDroneQuality)
    }
  }, [])

  return (
    <div className={`${styles.drone}`}>
      <video
        ref={videoRef}
        id="drone-video"
        className={styles.videoBackground}
        autoPlay
        muted
        loop
        playsInline
      >
        <source ref={sourceRef} id="video-source" type="video/mp4" />
        Your browser does not support video.
      </video>

      <article>
        <header>
          <h1>{t("droneAd.title")}</h1>
        </header>

        <main>
          <section>
            <h2>{t("droneAd.permissionTitle")}</h2>
            <p>{t("droneAd.permissionText")}</p>
          </section>

          <section>
            <h2>{t("droneAd.priceTitle")}</h2>
            <p>{t("droneAd.priceText")}</p>
          </section>

          <section>
            <h2>{t("droneAd.outputTitle")}</h2>
            <p>{t("droneAd.outputText")}</p>
          </section>
        </main>

        <div>
          <a href="#contacts">{t("droneAd.interested")}</a>
        </div>
      </article>
    </div>
  )
}
