import React, { useEffect, useState } from "react";

const SignOut = () => {
	const [isVisible, setIsVisible] = useState(false);

	useEffect(() => {
		const isAuthenticated = sessionStorage.getItem("isAuthenticated") === "true";
		setIsVisible(isAuthenticated);

		const handleAuthChange = () => {
			setIsVisible(sessionStorage.getItem("isAuthenticated") === "true");
		};

		document.addEventListener("auth-success", handleAuthChange);
		return () => document.removeEventListener("auth-success", handleAuthChange);
	}, []);

	const handleSignOut = () => {
		sessionStorage.removeItem("isAuthenticated");
		sessionStorage.removeItem("role");
		window.location.reload();
	};

	if (!isVisible) return null;

	return (
		<button onClick={handleSignOut} className="btn btn-secondary">
			Sign Out
		</button>
	);
};

export default SignOut;
