"use client";

import React, { useEffect, useRef, useState } from "react";
import CustomAlert from "@/components/common/CustomAlert";

export default function CustomAlertProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  const originalAlertRef = useRef<typeof window.alert | null>(null);
  const [isOpen, setIsOpen] = useState(false);
  const [message, setMessage] = useState("");

  useEffect(() => {
    if (typeof window === "undefined") return;

    originalAlertRef.current = window.alert;

    window.alert = (msg?: any) => {
      const nextMessage =
        typeof msg === "string"
          ? msg
          : msg == null
          ? ""
          : JSON.stringify(msg);
      setMessage(nextMessage);
      setIsOpen(true);
    };

    return () => {
      if (originalAlertRef.current) {
        window.alert = originalAlertRef.current;
      }
    };
  }, []);

  return (
    <>
      {children}
      <CustomAlert
        isOpen={isOpen}
        message={message}
        onClose={() => setIsOpen(false)}
      />
    </>
  );
}

