(function () {
    const storageKey = 'akkurtcast-theme';
    const root = document.documentElement;

    function getStoredTheme() {
        try {
            return localStorage.getItem(storageKey);
        } catch (error) {
            return null;
        }
    }

    function storeTheme(theme) {
        try {
            localStorage.setItem(storageKey, theme);
        } catch (error) {}
    }

    function systemTheme() {
        return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }

    function currentTheme() {
        return root.dataset.theme || getStoredTheme() || systemTheme();
    }

    function applyTheme(theme) {
        root.dataset.theme = theme;
        document.querySelectorAll('[data-theme-toggle]').forEach((button) => {
            const isDark = theme === 'dark';
            const icon = button.querySelector('[data-theme-icon]');
            const text = button.querySelector('[data-theme-text]');
            button.setAttribute('aria-pressed', String(isDark));
            button.setAttribute('title', isDark ? 'Açık temaya geç' : 'Koyu temaya geç');
            if (icon) icon.className = isDark ? 'bi bi-sun-fill' : 'bi bi-moon-stars-fill';
            if (text) text.textContent = isDark ? 'Açık tema' : 'Koyu tema';
        });
    }

    applyTheme(currentTheme());

    document.addEventListener('click', (event) => {
        const toggle = event.target.closest('[data-theme-toggle]');
        if (!toggle) return;
        const nextTheme = currentTheme() === 'dark' ? 'light' : 'dark';
        storeTheme(nextTheme);
        applyTheme(nextTheme);
    });
})();
