"use client";

import { useEffect, useState } from "react";
import dynamic from "next/dynamic";
import Image from "next/image";
import { createPortal } from "react-dom";

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

type VideoPopupButtonProps = {
  videoUrl: string;
  text: string;
  icon: string;
  iconAlt: string;
};

export default function VideoPopupButton({ videoUrl, text, icon, iconAlt }: VideoPopupButtonProps) {
  const [isOpen, setIsOpen] = useState(false);

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

  const isPlaceholderUrl = normalizedVideoUrl.includes("VIDEO_ID");

  useEffect(() => {
    if (!isOpen) {
      document.body.style.removeProperty("overflow");
      return;
    }

    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.removeProperty("overflow");
    };
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) {
      return;
    }

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setIsOpen(false);
      }
    };

    window.addEventListener("keydown", handleEscape);
    return () => window.removeEventListener("keydown", handleEscape);
  }, [isOpen]);

  return (
    <>
      <button type="button" className="video-btn video-trigger" onClick={() => setIsOpen(true)}>
        <span>{text}</span>
        <small>
          <Image src={icon} alt={iconAlt} width={20} height={20} />
        </small>
      </button>

      {isOpen &&
        createPortal(
        <div
          className="video-popup-overlay"
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 99999,
            background: "rgba(0, 0, 0, 0.85)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            padding: "24px",
          }}
          onClick={() => setIsOpen(false)}
        >
          <div
            style={{
              width: "min(100%, 960px)",
              aspectRatio: "16 / 9",
              position: "relative",
            }}
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              aria-label="Close video"
              onClick={() => setIsOpen(false)}
              style={{
                position: "absolute",
                top: "-40px",
                right: "0",
                background: "transparent",
                color: "#fff",
                border: "none",
                fontSize: "28px",
                cursor: "pointer",
              }}
            >
              ×
            </button>
            {isPlaceholderUrl ? (
              <div
                style={{
                  width: "100%",
                  height: "100%",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  color: "#fff",
                  background: "#111",
                  textAlign: "center",
                  padding: "20px",
                }}
              >
                Set a real video URL in `footerData.ts` to play video.
              </div>
            ) : (
              <ReactPlayer src={normalizedVideoUrl} playing controls width="100%" height="100%" />
            )}
          </div>
        </div>,
        document.body
      )}
    </>
  );
}
