const listeners = new Map();
let mediaQuery;

function ensureMediaQuery() {
    if (!mediaQuery) {
        mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    }
    return mediaQuery;
}

function applyColorScheme(isDark) {
    // Always use light color scheme for backgrounds
    document.documentElement.style.colorScheme = 'light';
}

export function getPreference(storageKey) {
    const stored = localStorage.getItem(storageKey);
    if (stored === 'light' || stored === 'dark') {
        return stored;
    }

    return ensureMediaQuery().matches ? 'dark' : 'light';
}

export function getStoredPreference(storageKey) {
    const stored = localStorage.getItem(storageKey);
    return stored ?? '';
}

export function persistPreference(storageKey, value) {
    localStorage.setItem(storageKey, value);
}

export function applyTheme(isDark) {
    document.documentElement.classList.toggle('dark', isDark);
    applyColorScheme(isDark);
}

export function subscribe(dotNetRef, storageKey) {
    const mq = ensureMediaQuery();

    const handler = event => {
        if (!dotNetRef) {
            return;
        }

        const stored = localStorage.getItem(storageKey);
        if (stored === 'light' || stored === 'dark') {
            return;
        }

        dotNetRef.invokeMethodAsync('OnSystemPreferenceChanged', event.matches);
    };

    mq.addEventListener('change', handler);
    listeners.set(dotNetRef, handler);
    applyColorScheme(mq.matches);
}

export function unsubscribe(dotNetRef) {
    if (!dotNetRef) {
        return;
    }

    const handler = listeners.get(dotNetRef);
    if (handler && mediaQuery) {
        mediaQuery.removeEventListener('change', handler);
    }
    listeners.delete(dotNetRef);
}



