"use client";

import React, { createContext, useContext, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import TokenExpiredModal from "./TokenExpiredModal";

type TokenExpiredContextType = {
	showModal: () => void;
};

const TokenExpiredContext = createContext<TokenExpiredContextType | undefined>(undefined);

export function useTokenExpired() {
	const context = useContext(TokenExpiredContext);
	if (!context) {
		throw new Error("useTokenExpired must be used within TokenExpiredProvider");
	}
	return context;
}

export function TokenExpiredProvider({ children }: { children: React.ReactNode }) {
	const [isModalOpen, setIsModalOpen] = useState(false);
	const router = useRouter();

	const showModal = () => {
		setIsModalOpen(true);
	};

	const handleClose = () => {
		setIsModalOpen(false);
		// 모달 닫은 후 로그인 페이지로 이동
		router.push("/login");
	};

	// 전역 이벤트 리스너 등록
	useEffect(() => {
		const handleTokenExpired = () => {
			showModal();
		};

		window.addEventListener("tokenExpired", handleTokenExpired);

		return () => {
			window.removeEventListener("tokenExpired", handleTokenExpired);
		};
	}, []);

	return (
		<TokenExpiredContext.Provider value={{ showModal }}>
			{children}
			<TokenExpiredModal open={isModalOpen} onClose={handleClose} />
		</TokenExpiredContext.Provider>
	);
}

