{% load lb_tags %}
{% load static %}

<c-vars
    :no_global_css="False"
    setThemeEndpoint=""
/>

{% if not no_global_css %}
    {% lb_css_path as css_path %}
    <link rel="stylesheet" href="{% static css_path %}">
{% endif %}

{% if setThemeEndpoint %}
{% csrf_token %}
<script>

function labbGetCSRFToken() {
    // First try to get from hidden input field
    const csrfInput = document.querySelector('input[name="csrfmiddlewaretoken"]');
    if (csrfInput && csrfInput.value) {
        return csrfInput.value;
    }

    // Fallback to cookie
    const name = 'csrftoken';
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue || '';
}
document.addEventListener('DOMContentLoaded', function() {
    // Get CSRF token from cookie or hidden input


    // Get current theme from data-theme attribute
    const currentTheme = document.documentElement.getAttribute('data-theme') || '__system__';

    // Find all theme controllers (checkboxes and radios)
    const themeControllers = document.querySelectorAll('input[type="checkbox"].theme-controller, input[type="radio"].theme-controller');

    function setTheme(theme) {
        if (theme && theme !== '__system__') {
            document.documentElement.setAttribute('data-theme', theme);
        } else {
            document.documentElement.removeAttribute('data-theme');
        }
    }

    themeControllers.forEach(function(controller) {
        // Set initial state based on current theme
        if (controller.type === 'checkbox') {
            // For checkboxes, check if the current theme matches the checkbox's value
            controller.checked = (controller.value === currentTheme);
        } else if (controller.type === 'radio') {
            // For radios, check the one that matches current theme exactly
            if (controller.value === currentTheme) {
                controller.checked = true;
            }
        }

        // Add change event listener
        controller.addEventListener('change', function() {
            let newTheme;

            if (this.type === 'checkbox') {
                // For checkboxes, use the checkbox's value if checked, otherwise use default
                newTheme = this.checked ? this.value : '__system__';
            } else if (this.type === 'radio') {
                // For radios, use the value directly
                newTheme = this.value;
            }


            // Update the HTML data-theme attribute immediately for instant feedback
            setTheme(newTheme);

            // Send AJAX request to save theme preference
            fetch('{{ setThemeEndpoint }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRFToken': labbGetCSRFToken()
                },
                body: 'theme=' + encodeURIComponent(newTheme)
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    console.error('Failed to save theme preference:', data.error);
                    // Revert the theme if save failed
                    setTheme(currentTheme);
                    if (this.type === 'checkbox') {
                        this.checked = !this.checked;
                    } else if (this.type === 'radio') {
                        // Find and check the radio that matches the original theme
                        const originalRadio = document.querySelector(`input[type="radio"].theme-controller[value="${currentTheme}"]`);
                        if (originalRadio) {
                            originalRadio.checked = true;
                        }
                    }
                }
            })
            .catch(error => {
                console.error('Error saving theme preference:', error);
                // Revert the theme if request failed
                setTheme(currentTheme);
                if (this.type === 'checkbox') {
                    this.checked = !this.checked;
                } else if (this.type === 'radio') {
                    // Find and check the radio that matches the original theme
                    const originalRadio = document.querySelector(`input[type="radio"].theme-controller[value="${currentTheme}"]`);
                    if (originalRadio) {
                        originalRadio.checked = true;
                    }
                }
            });
        });
    });
});
</script>
{% endif %}

{{ slot }}
