"use client";
import { Spinner } from "@heroui/react";
import { useEffect, useRef, useState } from "react";

interface FacebookEmbedProps {
  postUrl: string;
  width?: number;
  showText?: boolean;
}

declare global {
  interface Window {
    FB: any;
  }
}

const FacebookEmbed: React.FC<FacebookEmbedProps> = ({ postUrl }) => {
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!window.FB) {
      const script = document.createElement("script");
      script.src =
        "https://connect.facebook.net/id_ID/sdk.js#xfbml=1&version=v22.0&appId=1290603775136204";
      script.async = true;
      script.defer = true;
      document.body.appendChild(script);

      script.onload = () => {
        window.FB?.XFBML.parse();
        setLoading(false);
      };
    } else {
      window.FB.XFBML.parse();
      setLoading(false);
    }
  }, []);

  return (
    <>
      {loading && <Spinner />}
      <div
        className={`fb-post ${loading ? "hidden" : ""}`}
        data-href={postUrl}
        data-width="500"
        data-show-text="true"
      ></div>
    </>
  );
};

export default FacebookEmbed;
