<script>
(function () {
    var preference = <?= json_encode((string) \App\Core\site_setting('default_theme', 'system')) ?> || 'system';
    try {
        preference = window.localStorage.getItem('zalorox_theme_preference') || preference;
        if (!preference) {
            preference = window.localStorage.getItem('zalorox_dark_mode') === '0' ? 'light' : 'dark';
        }
    } catch (error) {
        preference = <?= json_encode((string) \App\Core\site_setting('default_theme', 'system')) ?> || 'system';
    }

    if (!/^(dark|light|system)$/.test(preference)) {
        preference = 'system';
    }

    var resolved = preference === 'system'
        ? (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
        : preference;

    document.documentElement.dataset.theme = resolved;
    document.documentElement.dataset.themePreference = preference;
    document.documentElement.style.colorScheme = resolved;
})();
</script>
