"use client";
import { useEffect, useState } from "react";
export const useSpotifyIframe = () => {
  const [controller, setController] = useState(null);
  const elementId = "splayer";
  useEffect(() => {
    const script = document.createElement("script");
    const spotifyScriptUrl = "https://open.spotify.com/embed/iframe-api/v1";
    const spotifyScriptElementId = "spotify-iframe-api";
    script.id = spotifyScriptElementId;
    script.setAttribute("id", spotifyScriptElementId);
    script.src = spotifyScriptUrl;
    document.body.appendChild(script);

    script.onload = () => {
      (window as any).onSpotifyIframeApiReady = (IFrameAPI) => {
        const element = document.getElementById(elementId);
        const options = {
          width: 400,
          height: 400,
        };
        const callback = (EmbedController) => {
          setController(EmbedController);
        };
        IFrameAPI.createController(element, options, callback);
      };
    };

    return () => {
      document.body.removeChild(script);
    };
  }, []);

  return controller;
};
