import { readonly, ref } from 'vue';

export type Appearance = 'light' | 'dark' | 'system';

const STORAGE_KEY = 'appearance';
const media = typeof window !== 'undefined' ? window.matchMedia('(prefers-color-scheme: dark)') : null;

function stored(): Appearance {
    try {
        const value = localStorage.getItem(STORAGE_KEY);

        return value === 'dark' || value === 'system' ? value : 'light';
    } catch {
        return 'light';
    }
}

const appearance = ref<Appearance>(stored());

function apply(): void {
    const dark = appearance.value === 'dark' || (appearance.value === 'system' && (media?.matches ?? false));
    document.documentElement.classList.toggle('dark', dark);
}

// "System" follows the device setting live, for example when it switches at sunset.
media?.addEventListener('change', () => {
    if (appearance.value === 'system') {
        apply();
    }
});

/**
 * The viewer's light/dark preference, remembered in this browser. Light is the default until the
 * viewer chooses otherwise. The inline script in app.blade.php applies the same rule before the
 * first paint.
 */
export function useAppearance() {
    function setAppearance(value: Appearance): void {
        appearance.value = value;
        try {
            if (value === 'light') {
                localStorage.removeItem(STORAGE_KEY);
            } else {
                localStorage.setItem(STORAGE_KEY, value);
            }
        } catch {
            // Storage can be unavailable (private mode); the choice then lasts for this page only.
        }
        apply();
    }

    return { appearance: readonly(appearance), setAppearance };
}
