jQuery(document).ready(function ($) {
    /**
     * Initializes card meaning visibility based on the checkbox state.
     */
    function initializeCardMeaningVisibility() {
        if (!$('#enable_card_meaning').prop('checked')) {
            $('[id^=cardMeaningPreview]').css('display', 'none');
        }
    }

    /**
     * Updates the live preview for the three-card tarot game.
     */
    function updateThreeCardPreview() {
        // Update all three card name previews
        $('[id^=cardNamePreview]').css({
            'font-family': $('#card_name_font_family').val(),
            'font-size': $('#card_name_font_size').val(),
            'color': $('#card_name_text_color').val()
        });

        // Update all three card meaning previews
        $('[id^=cardMeaningPreview]').css({
            'font-family': $('#card_meaning_font_family').val(),
            'font-size': $('#card_meaning_font_size').val(),
            'color': $('#card_meaning_text_color').val()
        });

        // Update the "Draw Again" button preview
        $('#drawAgainButtonPreview').css({
            'background-color': $('#button_bg_color').val(),
            'color': $('#button_text_color').val(),
            'font-size': $('#button_font_size').val(),
            'border-radius': $('#round_edges').val() + 'px'
        });
    }

    /**
     * Initializes the color pickers and binds the change event to update the preview.
     */
    function initializeColorPickers() {
        $('.color-field').wpColorPicker({
            change: function (event, ui) {
                updateThreeCardPreview();
            }
        });
    }

    /**
     * Binds event listeners to update the preview when settings are changed.
     */
    function bindPreviewUpdateEvents() {
        $('#card_name_font_family, #card_name_font_size, ' +
            '#card_meaning_font_family, #card_meaning_font_size, ' +
            '#button_font_size, #round_edges').on('change', updateThreeCardPreview);
    }

    /**
     * Handles form submission when the game selection dropdown changes.
     */
    function handleGameSelectionChange() {
        var selectedGameDropdown = document.getElementById('selected_game');
        if (selectedGameDropdown) {
            var form = selectedGameDropdown.closest('form');
            if (form) {
                selectedGameDropdown.addEventListener('change', function () {
                    form.submit();
                });
            } else {
                console.warn('Form element not found for the selected game dropdown.');
            }
        }
    }

    // Initialize functionality
    initializeCardMeaningVisibility();
    initializeColorPickers();
    bindPreviewUpdateEvents();
    handleGameSelectionChange();

    // Event listener for the "Enable Card Meaning" checkbox
    $('#enable_card_meaning').on('change', function () {
        $('[id^=cardMeaningPreview]').css('display', this.checked ? 'block' : 'none');
    });
});