(function () {
    try {
        // Priority order:
        //   1. ?theme_mode= URL param (used by the admin Appearance preview
        //      iframe so light/dark/system can be toggled independently).
        //   2. localStorage — the user's manual ThemeToggle choice persists.
        //   3. window.__themeModePref — the active theme's mode_pref knob,
        //      set server-side in app.blade.php. Lets the deployment admin
        //      bias the default.
        //   4. OS prefers-color-scheme media query.
        var params = new URLSearchParams(window.location.search);
        var override = params.get('theme_mode');
        var stored = localStorage.getItem('appshot:theme');
        var pref = window.__themeModePref;
        var media = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
        var theme;
        if (override === 'light' || override === 'dark') {
            theme = override;
        } else if (override === 'system') {
            theme = media;
        } else if (stored === 'light' || stored === 'dark') {
            theme = stored;
        } else if (pref === 'light' || pref === 'dark') {
            theme = pref;
        } else {
            theme = media;
        }
        document.documentElement.setAttribute('data-theme', theme);
    } catch (e) { /* storage blocked; fall through to light default */ }
})();
