import { writable, derived } from 'svelte/store';

// Detect browser language
function detectLanguage(): 'en' | 'pt' {
	if (typeof navigator === 'undefined') return 'en';

	if (navigator.languages && navigator.languages.length > 0) {
		const twoLetterLang = navigator.languages.find((lang) => lang.length === 2);
		if (twoLetterLang) {
			return twoLetterLang === 'pt' ? 'pt' : 'en';
		}
	}

	const lang =
		(navigator.language || (navigator as any).userLanguage || (navigator as any).browserLanguage || 'en')
			.substring(0, 2);
	return lang === 'pt' ? 'pt' : 'en';
}

// Global state (matching compiled frontend)
export const dropletsDialogOpen = writable(false);
export const muted = writable(false);
export const language = writable<'en' | 'pt'>(detectLanguage());
export const captcha = writable<string | undefined>(undefined);
export const now = writable(Date.now());
export const turnstileLoaded = writable(false);

// Update time every 500ms (for charge regeneration)
if (typeof window !== 'undefined') {
	setInterval(() => {
		now.set(Date.now());
	}, 500);
}

// Derived online status
export const online = writable(true);
