"use client";

import { useState } from "react";
import Image from "next/image";
import { useLocale } from "next-intl";
import { Play } from "lucide-react";
import { trackGAEvent } from "@/lib/google-analytics";

const basePath = process.env.NEXT_PUBLIC_BASE_PATH || "";

interface VideoPlayerProps {
  /** Base name under /public/videos, without extension. */
  fileName: string;
  /** Accessible description of the video for screen readers. */
  videoLabel: string;
  /** Spoken label on the play button, e.g. "Play video". */
  playLabel: string;
  /** True when `<fileName>.en.vtt` and `<fileName>.es.vtt` sit next to the video. */
  hasCaptions?: boolean;
  /** Run length shown on the poster, e.g. "0:50". */
  durationLabel?: string;
  /** Loads the poster eagerly. Use only for a player above the fold. */
  priority?: boolean;
  className?: string;
}

/**
 * Poster-first video player: the file is a still image until the visitor
 * presses play, so a multi-megabyte video never downloads on page load. Shared
 * by the landing page walkthrough and the signup page panel.
 */
export default function VideoPlayer({
  fileName,
  videoLabel,
  playLabel,
  hasCaptions = false,
  durationLabel,
  priority = false,
  className = "",
}: VideoPlayerProps) {
  const [isPlaying, setIsPlaying] = useState(false);
  const locale = useLocale();

  const videoSrc = `${basePath}/videos/${fileName}.mp4`;
  const posterSrc = `${basePath}/videos/${fileName}.jpg`;

  // Audio is English for both recordings, so a Spanish visitor needs Spanish
  // subtitles turned on by default rather than offered as an option they have
  // to find. Both tracks ship; the active locale is the one marked default.
  const captionTracks = [
    { srcLang: "en", label: "English" },
    { srcLang: "es", label: "Español" },
  ];

  const handlePlay = () => {
    setIsPlaying(true);
    // Consent-gated: no-ops unless analytics are allowed on this page.
    trackGAEvent("video_play", { video_id: fileName, locale });
  };

  return (
    <div
      className={`relative aspect-video overflow-hidden rounded-2xl bg-gray-900 shadow-xl ring-1 ring-black/5 ${className}`}
    >
      {isPlaying ? (
        <video
          key={fileName}
          className="absolute inset-0 h-full w-full"
          src={videoSrc}
          poster={posterSrc}
          controls
          autoPlay
          playsInline
          preload="auto"
          aria-label={videoLabel}
        >
          {hasCaptions &&
            captionTracks.map((track) => (
              <track
                key={track.srcLang}
                kind="captions"
                srcLang={track.srcLang}
                label={track.label}
                src={`${basePath}/videos/${fileName}.${track.srcLang}.vtt`}
                default={track.srcLang === locale}
              />
            ))}
        </video>
      ) : (
        <button
          type="button"
          onClick={handlePlay}
          aria-label={`${playLabel}: ${videoLabel}`}
          className="group absolute inset-0 h-full w-full cursor-pointer focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#2E8EBE]"
        >
          <Image
            key={fileName}
            src={posterSrc}
            alt=""
            fill
            priority={priority}
            sizes="(min-width: 1024px) 50vw, 100vw"
            className="object-cover"
          />
          {/* Only the lower third is darkened, so the speaker's face stays
              bright while the duration badge keeps its contrast. */}
          <span className="absolute inset-x-0 bottom-0 h-1/3 bg-gradient-to-t from-black/55 to-transparent" />
          <span className="absolute inset-0 flex items-center justify-center">
            <span className="flex h-[70px] w-[70px] items-center justify-center rounded-full bg-white shadow-xl transition duration-200 group-hover:scale-105">
              <Play
                className="h-7 w-7 translate-x-[2px] text-[#2E8EBE]"
                fill="currentColor"
                aria-hidden="true"
              />
            </span>
          </span>
          {durationLabel && (
            <span className="absolute bottom-3 right-3 rounded-md bg-black/75 px-2 py-1 text-xs font-semibold text-white tabular-nums">
              {durationLabel}
            </span>
          )}
        </button>
      )}
    </div>
  );
}
