"use client"; import { Button } from "@/components/ui/button"; import { Link as I18nLink, LOCALE_NAMES, routing } from "@/i18n/routing"; import { cn } from "@/lib/utils"; import { useLocaleStore } from "@/stores/localeStore"; import { ArrowRight, Globe, X } from "lucide-react"; import { useLocale } from "next-intl"; import { useCallback, useEffect, useState } from "react"; export function LanguageDetectionAlert() { const [countdown, setCountdown] = useState(10); // countdown 10s and dismiss const [isVisible, setIsVisible] = useState(false); const locale = useLocale(); const [detectedLocale, setDetectedLocale] = useState(null); const { showLanguageAlert, setShowLanguageAlert, dismissLanguageAlert, getLangAlertDismissed, } = useLocaleStore(); const handleDismiss = useCallback(() => { setIsVisible(false); setTimeout(() => { dismissLanguageAlert(); }, 300); }, [dismissLanguageAlert]); const handleSwitchLanguage = useCallback(() => { dismissLanguageAlert(); }, [dismissLanguageAlert]); useEffect(() => { const detectedLang = navigator.language; // Get full language code, e.g., zh_HK const storedDismiss = getLangAlertDismissed(); if (!storedDismiss) { let supportedLang = routing.locales.find((l) => l === detectedLang); if (!supportedLang) { const mainLang = detectedLang.split("-")[0]; supportedLang = routing.locales.find((l) => l.startsWith(mainLang)); } if (supportedLang && supportedLang !== locale) { setDetectedLocale(supportedLang); setShowLanguageAlert(true); setTimeout(() => setIsVisible(true), 100); } } }, [locale, getLangAlertDismissed, setShowLanguageAlert]); useEffect(() => { let timer: NodeJS.Timeout; if (showLanguageAlert && countdown > 0) { timer = setInterval(() => { setCountdown((prev) => prev - 1); }, 1000); } return () => { if (timer) clearInterval(timer); }; }, [showLanguageAlert, countdown]); useEffect(() => { if (countdown === 0 && showLanguageAlert) { handleDismiss(); } }, [countdown, showLanguageAlert, handleDismiss]); if (!showLanguageAlert || !detectedLocale) return null; const messages = require(`@/i18n/messages/${detectedLocale}.json`); const alertMessages = messages.LanguageDetection; return (

{alertMessages.title}

{alertMessages.description}

{countdown}s
); }