import { useEffect } from "react";
import { useUIStore } from "../stores/uiStore";

export function ExternalLinkDialog() {
	const externalLinkUrl = useUIStore((s) => s.externalLinkUrl);
	const closeExternalLink = useUIStore((s) => s.closeExternalLink);

	useEffect(() => {
		function handleKeyDown(e: KeyboardEvent) {
			if (e.key === "Escape") closeExternalLink();
		}
		if (externalLinkUrl) {
			document.addEventListener("keydown", handleKeyDown);
			return () => document.removeEventListener("keydown", handleKeyDown);
		}
	}, [externalLinkUrl, closeExternalLink]);

	if (!externalLinkUrl) return null;

	function handleContinue() {
		if (externalLinkUrl) {
			window.open(externalLinkUrl, "_blank", "noopener,noreferrer");
		}
		closeExternalLink();
	}

	return (
		<div className="fixed inset-0 z-50 flex items-center justify-center">
			<div
				className="absolute inset-0 bg-black/30"
				onClick={closeExternalLink}
				onKeyDown={(e) => {
					if (e.key === "Escape") closeExternalLink();
				}}
			/>
			<div className="relative bg-white rounded-xl shadow-lg p-6 max-w-sm mx-4 w-full">
				<h3 className="text-lg font-semibold text-gray-900 mb-2">
					You are about to leave GearBox
				</h3>
				<p className="text-sm text-gray-600 mb-1">You will be redirected to:</p>
				<p className="text-sm text-gray-600 break-all mb-6">
					{externalLinkUrl}
				</p>
				<div className="flex justify-end gap-3">
					<button
						type="button"
						onClick={closeExternalLink}
						className="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors"
					>
						Cancel
					</button>
					<button
						type="button"
						onClick={handleContinue}
						className="px-4 py-2 text-sm font-medium text-white bg-gray-700 hover:bg-gray-800 rounded-lg transition-colors"
					>
						Continue
					</button>
				</div>
			</div>
		</div>
	);
}
