"use client";

import { useState } from "react";
import dynamic from "next/dynamic";
import { createPortal } from "react-dom";

const ReactPlayer = dynamic(() => import("react-player"), { ssr: false });

interface VideoPopupPlayerProps {
  videoUrl: string;
  triggerSymbol: string;
  triggerClassName?: string;
}

export default function VideoPopupPlayer({
  videoUrl,
  triggerSymbol,
  triggerClassName = "video-trigger",
}: VideoPopupPlayerProps) {
  const [isVideoOpen, setIsVideoOpen] = useState(false);
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);
  const canUseDOM = typeof window !== "undefined";

  const normalizedVideoUrl = videoUrl.includes("/embed/")
    ? videoUrl.replace("/embed/", "/watch?v=")
    : videoUrl;

  const openVideo = () => {
    setIsVideoOpen(true);
    requestAnimationFrame(() => setIsVideoPlaying(true));
  };

  const closeVideo = () => {
    setIsVideoPlaying(false);
    setTimeout(() => setIsVideoOpen(false), 120);
  };

  return (
    <>
      <a
        href="#"
        className={triggerClassName}
        data-video={videoUrl}
        onClick={(event) => {
          event.preventDefault();
          openVideo();
        }}
      >
        {triggerSymbol}
      </a>

      {canUseDOM &&
        isVideoOpen &&
        createPortal(
          <div
            onClick={closeVideo}
            style={{
              position: "fixed",
              inset: 0,
              backgroundColor: "rgba(0, 0, 0, 0.75)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              zIndex: 9999,
              padding: "20px",
            }}
          >
            <div
              onClick={(event) => event.stopPropagation()}
              style={{
                position: "relative",
                width: "min(900px, 100%)",
                aspectRatio: "16 / 9",
                backgroundColor: "#000",
              }}
            >
              <button
                type="button"
                onClick={closeVideo}
                style={{
                  position: "absolute",
                  top: "-40px",
                  right: "0",
                  border: "none",
                  background: "transparent",
                  color: "#fff",
                  fontSize: "28px",
                  lineHeight: 1,
                  cursor: "pointer",
                }}
                aria-label="Close video player"
              >
                ×
              </button>
              <ReactPlayer
                src={normalizedVideoUrl}
                width="100%"
                height="100%"
                playing={isVideoPlaying}
                controls
              />
            </div>
          </div>
          ,
          document.body,
        )}
    </>
  );
}
