"use client";

import { useEffect, useRef, useState } from "react";
import { motion } from "framer-motion";
import { Play, Volume2, VolumeX } from "lucide-react";
import type { Locale } from "@/lib/i18n";

interface VideoShowcaseProps {
  locale: Locale;
}

/**
 * Cinematic product film band. The video autoplays (muted, looped) only when
 * scrolled into view to keep the landing fast; poster falls back to the hero
 * still so nothing flashes while loading.
 */
export function VideoShowcase({ locale }: VideoShowcaseProps) {
  const isRTL = locale === "ar";
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const [muted, setMuted] = useState(true);
  const [playing, setPlaying] = useState(false);

  const t =
    locale === "ar"
      ? {
          badge: "شاهد كيف يعمل",
          title: "موظفوك يعملون —",
          titleHighlight: "وأنت تشاهد.",
          subtitle: "من لوحة Odoo إلى رسالة على هاتفك: هكذا ينجز موظفك الذكي مهمته ويبلّغك بالنتيجة.",
          play: "تشغيل",
        }
      : {
          badge: "SEE HOW IT WORKS",
          title: "Your employees at work —",
          titleHighlight: "while you watch.",
          subtitle: "From the Odoo dashboard to a message on your phone: this is how your AI employee finishes a task and reports back.",
          play: "Play",
        };

  // Autoplay/pause based on visibility.
  useEffect(() => {
    const el = videoRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          el.play().then(() => setPlaying(true)).catch(() => setPlaying(false));
        } else {
          el.pause();
          setPlaying(false);
        }
      },
      { threshold: 0.35 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <section id="watch" className="relative py-24 overflow-hidden" dir={isRTL ? "rtl" : "ltr"}>
      <div className="absolute inset-0 bg-void-black" />
      <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[900px] h-[500px] bg-electric-cyan/[0.05] rounded-full blur-3xl" />

      <div className="container-custom relative z-10">
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ duration: 0.7 }}
          className="text-center max-w-2xl mx-auto mb-10"
        >
          <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full border border-electric-cyan/20 bg-electric-cyan/[0.03] mb-6">
            <Play size={12} className="text-electric-cyan" />
            <span className="font-jetbrains-mono text-xs text-electric-cyan tracking-widest">{t.badge}</span>
          </div>
          <h2 className="font-space-grotesk font-bold text-3xl md:text-5xl leading-tight mb-4">
            <span className="text-warm-white">{t.title} </span>
            <span className="text-gradient-cyan">{t.titleHighlight}</span>
          </h2>
          <p className="text-muted-white text-base md:text-lg">{t.subtitle}</p>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 40, scale: 0.97 }}
          whileInView={{ opacity: 1, y: 0, scale: 1 }}
          viewport={{ once: true }}
          transition={{ duration: 0.9 }}
          className="relative mx-auto max-w-5xl"
        >
          {/* Glow frame */}
          <div className="absolute -inset-1 rounded-[28px] bg-gradient-to-r from-electric-cyan/30 via-soft-emerald/20 to-electric-cyan/30 blur-lg opacity-60" />
          <div className="relative overflow-hidden rounded-3xl border border-white/10 bg-obsidian shadow-glass">
            <video
              ref={videoRef}
              className="block w-full"
              poster="/landing/hero-office.webp"
              src="/landing/how-it-works.mp4?v=30s"
              muted={muted}
              loop
              playsInline
              preload="metadata"
            />
            {/* Controls */}
            <div className="absolute bottom-4 left-4 right-4 flex items-center justify-between">
              {!playing && (
                <button
                  onClick={() => videoRef.current?.play().then(() => setPlaying(true)).catch(() => {})}
                  className="inline-flex items-center gap-2 rounded-full bg-electric-cyan px-5 py-2.5 font-space-grotesk text-sm font-semibold text-void-black shadow-glow-cyan"
                >
                  <Play size={15} /> {t.play}
                </button>
              )}
              <span />
              <button
                onClick={() => {
                  setMuted((m) => !m);
                  if (videoRef.current) videoRef.current.muted = !muted;
                }}
                className="rounded-full border border-white/15 bg-void-black/60 p-2.5 text-warm-white backdrop-blur-sm transition hover:bg-void-black/80"
                aria-label={muted ? "Unmute" : "Mute"}
              >
                {muted ? <VolumeX size={16} /> : <Volume2 size={16} />}
              </button>
            </div>
          </div>
        </motion.div>
      </div>
    </section>
  );
}
