"use client";

import { useRef, useEffect, useState } from "react";
import type { ReactNode } from "react";
import Image from "next/image";

interface Props {
  img: string;
  alt: string;
  name: string;
  subtitle: string;
  iconNode: ReactNode;
  video?: string;
}

export default function TechVideoPlayer({ img, alt, name, subtitle, iconNode, video }: Props) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const hasStarted = useRef(false);
  const [showPoster, setShowPoster] = useState(true);

  useEffect(() => {
    if (!video || !videoRef.current || !containerRef.current) return;

    let timer: ReturnType<typeof setTimeout> | null = null;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            // Every time it comes into view: show poster for 2s, then hide and play
            setShowPoster(true);
            timer = setTimeout(() => {
              hasStarted.current = true;
              setShowPoster(false);
              videoRef.current?.play().catch(() => {});
            }, 2000);
          } else {
            if (timer) clearTimeout(timer);
            // Pause and bring poster back
            videoRef.current?.pause();
            if (hasStarted.current) setShowPoster(true);
          }
        });
      },
      { threshold: 0.35 }
    );

    observer.observe(containerRef.current);
    return () => {
      observer.disconnect();
      if (timer) clearTimeout(timer);
    };
  }, [video]);

  return (
    <div ref={containerRef} className="relative overflow-hidden rounded-sm">
      {/* Video always rendered underneath */}
      {video && (
        <video
          ref={videoRef}
          src={video}
          loop
          playsInline
          controls
          className="w-full h-80 lg:h-[420px] object-cover"
        />
      )}

      {/* Poster image fades out after 2s */}
      {video ? (
        <div
          className={`absolute inset-0 transition-opacity duration-700 ${showPoster ? "opacity-100" : "opacity-0 pointer-events-none"}`}
        >
          <Image src={img} alt={alt} fill className="object-cover" />
          <div className="absolute inset-0 bg-gradient-to-t from-primary/60 to-transparent" />
          <div className="absolute bottom-0 left-0 p-6">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-sm bg-accent flex items-center justify-center">
                {iconNode}
              </div>
              <div>
                <h3 className="text-primary-foreground font-bold text-lg">{name}</h3>
                <p className="text-primary-foreground/60 text-sm">{subtitle}</p>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <>
          <Image src={img} alt={alt} width={800} height={420} className="w-full h-80 lg:h-[420px] object-cover" />
          <div className="absolute inset-0 bg-gradient-to-t from-primary/60 to-transparent pointer-events-none" />
          <div className="absolute bottom-0 left-0 p-6">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-sm bg-accent flex items-center justify-center">
                {iconNode}
              </div>
              <div>
                <h3 className="text-primary-foreground font-bold text-lg">{name}</h3>
                <p className="text-primary-foreground/60 text-sm">{subtitle}</p>
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

