import { router, usePage } from '@inertiajs/react'; export type Locale = 'id' | 'en'; /** Content written once per language, e.g. `{ id: {...}, en: {...} }`. */ export type Localized = Record; const setCookie = (name: string, value: string, days = 365): void => { const maxAge = days * 24 * 60 * 60; document.cookie = `${name}=${value};path=/;max-age=${maxAge};SameSite=Lax`; }; /** * The visitor's language comes from the `locale` cookie, which the server * reads (HandleLocale) and shares as a page prop. Switching stores the new * choice and reloads the page props so every component re-renders in it. */ export function useLocale() { const { locale } = usePage().props; const setLocale = (next: Locale): void => { if (next === locale) { return; } setCookie('locale', next); document.documentElement.lang = next; router.reload(); }; return { locale, setLocale } as const; } /** Picks the current language's version of a localized content object. */ export function useContent(content: Localized): T { return content[useLocale().locale]; }