import { ref, watch } from 'vue';

const STORAGE_KEY = 'crmfic-theme';

function getInitialTheme() {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored === 'light' || stored === 'dark') return stored;
    // First-ever visit (nothing saved yet) always starts in light mode,
    // regardless of the OS/browser's own dark-mode preference.
    return 'light';
}

function applyTheme(value) {
    document.documentElement.setAttribute('data-theme', value);
}

// Module-level singleton so every component shares the same theme state.
const theme = ref(getInitialTheme());
applyTheme(theme.value);

watch(theme, (value) => {
    applyTheme(value);
    localStorage.setItem(STORAGE_KEY, value);
});

export function useTheme() {
    function toggleTheme() {
        theme.value = theme.value === 'dark' ? 'light' : 'dark';
    }

    return { theme, toggleTheme };
}
