"use client";

import styles from "./Video.module.css";
import { useEffect, useRef } from "react";

type VideoProps = {
  src?: string;
  play: boolean;
  poster?: string;
  fetchPriority?: "auto" | "high" | "low";
  preload?: "none" | "metadata" | "auto";
};

const Video = (props: VideoProps) => {
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    const { current } = videoRef;

    if (!current) return;

    if (props.play) {
      if (current.readyState === 0) {
        current.load();
      }
      current.play().catch(() => {});
    } else {
      current.pause();
    }
  }, [props.play, props.src]);

  const handleCanPlay = () => {
    const { current } = videoRef;
    if (current && props.play) {
      current.play().catch(() => {});
    }
  };

  if (!props.src) return <></>;

  const fetchPriorityProps = props.fetchPriority
    ? ({ fetchPriority: props.fetchPriority } as {
        fetchPriority: "auto" | "high" | "low";
      })
    : {};

  return (
    <div className={styles.video_wrapper}>
      <video
        ref={videoRef}
        className={styles.video}
        controls={false}
        poster={props.poster}
        preload={props.preload ?? (props.play ? "auto" : "none")}
        autoPlay={props.play}
        playsInline
        loop
        muted
        width="100%"
        height="100%"
        onCanPlay={handleCanPlay}
        {...fetchPriorityProps}
      >
        <source src={props.src} type="video/mp4" />
      </video>
    </div>
  );
};

export default Video;
