"use client";

import { useEffect } from "react";

export default function WebpackErrorHandler() {
  useEffect(() => {
    // Listen for unhandled errors
    const handleError = (event: ErrorEvent) => {
      const error = event.error || event.message || "";
      const errorString = String(error);

      // Check if it's a webpack module loading error
      if (
        errorString.includes("Cannot read properties of undefined") &&
        (errorString.includes("reading 'call'") ||
          errorString.includes("webpack") ||
          errorString.includes("react-server-dom-webpack"))
      ) {
        console.warn(
          "Webpack module loading error detected, forcing page reload..."
        );

        // Clear all caches and reload
        if (typeof window !== "undefined") {
          // Clear service worker cache if exists
          if ("serviceWorker" in navigator) {
            navigator.serviceWorker.getRegistrations().then((registrations) => {
              registrations.forEach((registration) => {
                registration.unregister();
              });
            });
          }

          // Clear all caches
          if ("caches" in window) {
            caches.keys().then((names) => {
              names.forEach((name) => {
                caches.delete(name);
              });
            });
          }

          // Force hard reload after a short delay
          setTimeout(() => {
            window.location.reload();
          }, 100);
        }
      }
    };

    // Listen for unhandled promise rejections
    const handleRejection = (event: PromiseRejectionEvent) => {
      const error = event.reason || "";
      const errorString = String(error);

      if (
        errorString.includes("Cannot read properties of undefined") &&
        (errorString.includes("reading 'call'") ||
          errorString.includes("webpack") ||
          errorString.includes("react-server-dom-webpack"))
      ) {
        console.warn(
          "Webpack module loading error detected in promise, forcing page reload..."
        );

        if (typeof window !== "undefined") {
          setTimeout(() => {
            window.location.reload();
          }, 100);
        }
      }
    };

    window.addEventListener("error", handleError);
    window.addEventListener("unhandledrejection", handleRejection);

    return () => {
      window.removeEventListener("error", handleError);
      window.removeEventListener("unhandledrejection", handleRejection);
    };
  }, []);

  return null;
}
