import { createPortal } from "react-dom";
import ReactPlayer from "react-player";

type FaqVideoModalProps = {
  isOpen: boolean;
  onClose: () => void;
  videoUrl: string;
  title?: string;
};

export default function FaqVideoModal({
  isOpen,
  onClose,
  videoUrl,
  title = "FAQ intro video",
}: FaqVideoModalProps) {
  // Guard for server-side rendering
  if (typeof window === "undefined" || !isOpen) {
    return null;
  }

  return createPortal(
    <div
      role="dialog"
      aria-modal="true"
      aria-label={title}
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        zIndex: 9999,
        backgroundColor: "rgba(0, 0, 0, 0.8)",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: "24px",
      }}
    >
      <div
        onClick={(event) => event.stopPropagation()}
        style={{
          width: "100%",
          maxWidth: "900px",
          position: "relative",
        }}
      >
        <button
          type="button"
          onClick={onClose}
          aria-label="Close video popup"
          style={{
            position: "absolute",
            top: "-44px",
            right: "0",
            border: 0,
            background: "transparent",
            color: "#fff",
            fontSize: "32px",
            lineHeight: 1,
            cursor: "pointer",
          }}
        >
          ×
        </button>
        <div
          style={{
            position: "relative",
            paddingTop: "56.25%",
            borderRadius: "8px",
            overflow: "hidden",
          }}
        >
          <ReactPlayer
            src={videoUrl}
            controls={true}
            playing={isOpen}
            muted={true}
            width="100%"
            height="100%"
            style={{ position: "absolute", top: 0, left: 0 }}
          />
        </div>
      </div>
    </div>,
    document.body,
  );
}
