import React, { useMemo } from "react";
import { VideoEmbedProps } from "./types";

import { cx } from "@shared/utils";

// import styles from "./styles.module.scss";

export type Props = {
  containerClassName?: string;
  autoplay?: boolean; // Add the autoplay prop
} & VideoEmbedProps;

export const YoutubeEmbed: React.FC<Props> = props => {
  const { link, containerClassName, autoplay = false } = props;

  const embedId = useMemo(() => {
    if (!link) return "";

    const href = link.toString();
    const regExp =
      /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
    const match = href.match(regExp);

    return match && match[7].length === 11 ? match[7] : "";
  }, [link]);

  // Add autoplay parameter to the URL if autoplay is true
  const autoplayParam = autoplay ? "?autoplay=1" : "";

  return (
    <div
      className={cx(
        "relative h-full w-full overflow-hidden pb-[56.25%]",
        containerClassName
      )}
    >
      <iframe
        className="absolute left-0 top-0 h-full w-full"
        src={`https://www.youtube.com/embed/${embedId}${autoplayParam}`}
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        allowFullScreen={true}
        title="Embedded youtube"
      />
    </div>
  );
};
