"use client";

import { ReactNode, useEffect } from "react";
import { useRouter } from "next/navigation";

const SESSION_REASON = "sesion-expirada";

export default function PanelLayout({ children }: { children: ReactNode }) {
  const router = useRouter();

  useEffect(() => {
    const nativeFetch = window.fetch.bind(window);
    let redirecting = false;

    window.fetch = async (...args) => {
      const response = await nativeFetch(...args);
      let expired = response.status === 401;

      if (!expired && response.status === 403) {
        try {
          const body = await response.clone().json();
          const detail = String(body?.detail || "").toLowerCase();
          expired = detail.includes("csrf") || detail.includes("sesión inválida") ||
            detail.includes("sesion invalida") || detail.includes("sesión expirada");
        } catch {
          expired = false;
        }
      }

      if (expired && !redirecting) {
        redirecting = true;
        sessionStorage.removeItem("documenta:csrf");
        router.replace(`/acceso?motivo=${SESSION_REASON}`);
      }
      return response;
    };

    return () => {
      window.fetch = nativeFetch;
    };
  }, [router]);

  return children;
}
