jQuery(document).ready(function ($) {
    // $('.color-field').wpColorPicker();
    document.querySelectorAll(".color-field").forEach(z => z.type = "color");

    /**
     * Retrieve the value from an input element by its name attribute.
     *
     * @param {string} name - The input element’s name.
     * @param {string} defaultValue - The default value to return if not found.
     * @returns {string} The input’s value or the default.
     */
    function getElementValueByName(name, defaultValue) {
        var elements = document.getElementsByName(name);
        return (elements && elements.length > 0) ? elements[0].value : defaultValue;
    }

    /**
     * Build a styles object for a given style group.
     * Only properties with non-empty values are added.
     *
     * @param {string} elementType - The style group (e.g., 'header_text', 'button_text').
     * @returns {Object} An object of CSS properties and values.
     */
    function getStyleObject(elementType) {
        var styles = {};
        var value;

        switch (elementType) {
            case 'powered_by':
                value = getElementValueByName('postology_header_font_color', '');
                if (value !== '') styles['color'] = value;
                break;
            case 'header_text':
                value = getElementValueByName('postology_header_font_size', '');
                if (value !== '') styles['font-size'] = value;
                value = getElementValueByName('postology_header_font_family', '');
                if (value !== '') styles['font-family'] = value;
                value = getElementValueByName('postology_header_font_weight', '');
                if (value !== '') styles['font-weight'] = value;
                value = getElementValueByName('postology_header_font_color', '');
                if (value !== '') styles['color'] = value;
                value = getElementValueByName('postology_header_line_height', '');
                if (value !== '') styles['line-height'] = value;
                break;
            case 'summary_heading_text':
                value = getElementValueByName('postology_summary_heading_font_size', '');
                if (value !== '') styles['font-size'] = value;
                value = getElementValueByName('postology_summary_heading_font_family', '');
                if (value !== '') styles['font-family'] = value;
                value = getElementValueByName('postology_summary_heading_font_weight', '');
                if (value !== '') styles['font-weight'] = value;
                value = getElementValueByName('postology_summary_heading_font_color', '');
                if (value !== '') styles['color'] = value;
                value = getElementValueByName('postology_summary_heading_line_height', '');
                if (value !== '') styles['line-height'] = value;
                break;
            case 'summary_background':
                value = getElementValueByName('postology_summary_background_color', '');
                if (value !== '') styles['background-color'] = value;
                break;
            case 'button_text':
                value = getElementValueByName('postology_button_font_size', '');
                if (value !== '') styles['font-size'] = value;
                value = getElementValueByName('postology_button_font_family', '');
                if (value !== '') styles['font-family'] = value;
                value = getElementValueByName('postology_button_font_weight', '');
                if (value !== '') styles['font-weight'] = value;
                value = getElementValueByName('postology_button_font_color', '');
                if (value !== '') styles['color'] = value;
                value = getElementValueByName('postology_button_line_height', '');
                if (value !== '') styles['line-height'] = value;
                value = getElementValueByName('postology_button_background_color', '');
                if (value !== '') styles['background-color'] = value;
                value = getElementValueByName('postology_button_border_color', '');
                if (value !== '') styles['border'] = '1px solid ' + value;
                value = getElementValueByName('postology_button_border_radius', '');
                if (value !== '') styles['border-radius'] = value;
                break;
            case 'bullet_points_text':
                value = getElementValueByName('postology_bullet_points_font_size', '');
                if (value !== '') styles['font-size'] = value;
                value = getElementValueByName('postology_bullet_points_font_family', '');
                if (value !== '') styles['font-family'] = value;
                value = getElementValueByName('postology_bullet_points_font_weight', '');
                if (value !== '') styles['font-weight'] = value;
                value = getElementValueByName('postology_bullet_points_font_color', '');
                if (value !== '') styles['color'] = value;
                value = getElementValueByName('postology_bullet_points_line_height', '');
                if (value !== '') styles['line-height'] = value;
                break;
            case 'main_container':
                value = getElementValueByName('postology_main_container_background_color', '');
                if (value !== '') styles['background-color'] = value;
                value = getElementValueByName('postology_main_container_border_radius', '');
                if (value !== '') styles['border-radius'] = value;
                value = getElementValueByName('postology_main_container_border_color', '');
                if (value !== '') styles['border'] = '0px solid ' + value;
                value = getElementValueByName('postology_main_container_border_shadow', '');
                if (value !== '') styles['box-shadow'] = value;
                break;
            case 'inner_container':
                value = getElementValueByName('postology_inner_container_background_color', '');
                if (value !== '') styles['background-color'] = value;
                value = getElementValueByName('postology_inner_container_border_radius', '');
                if (value !== '') styles['border-radius'] = value;
                value = getElementValueByName('postology_inner_container_border_color', '');
                if (value !== '') styles['border'] = '0px solid ' + value;
                value = getElementValueByName('postology_inner_container_border_shadow', '');
                if (value !== '') styles['box-shadow'] = value;
                break;
            case 'icon_container':
                value = getElementValueByName('postology_box_icon_color', '');
                if (value !== '') styles['fill'] = value;
                break;
            default:
                break;
        }
        return styles;
    }

    /**
     * Apply a styles object to an element without removing existing styles.
     *
     * @param {HTMLElement} element - The DOM element to style.
     * @param {Object} styles - An object mapping CSS property names to values.
     */
    function applyStyles(element, styles) {
        Object.keys(styles).forEach(function (property) {
            if (styles[property] !== "") {
                element.style.setProperty(property, styles[property], "important");
            }
        });
    }

    /**
     * Update the Postology box styles by updating only the changed properties.
     */
    function updateBoxStyles() {
        var mainContainer = document.getElementById('postology-box');
        if (mainContainer) {
            applyStyles(mainContainer, getStyleObject('main_container'));
        }

        var header = document.querySelector('.postology-header');
        if (header) {
            applyStyles(header, getStyleObject('header_text'));
        }

        var summaryTitle = document.getElementById('summary-title');
        if (summaryTitle) {
            applyStyles(summaryTitle, getStyleObject('summary_heading_text'));
        }

        var summaryContentPlaceholder = document.getElementById('summary-content-placeholder');
        if (summaryContentPlaceholder) {
            applyStyles(summaryContentPlaceholder, getStyleObject('summary_background'));
        }

        var button = document.getElementById('generate-summary');
        if (button) {
            applyStyles(button, getStyleObject('button_text'));
        }

        var bulletPoints = document.querySelector('#summary-content ul');
        if (bulletPoints) {
            applyStyles(bulletPoints, getStyleObject('bullet_points_text'));
        }

        var innerContainer = document.getElementById('summary-content');
        if (innerContainer) {
            applyStyles(innerContainer, getStyleObject('inner_container'));
        }

        var poweredBy = document.querySelector('.postology-powered-by');
        if (poweredBy) {
            applyStyles(poweredBy, getStyleObject('powered_by'));
        }

        var icons = document.querySelectorAll('.postology-box-icon');
        if (icons.length) {
            icons.forEach(icon => {
                applyStyles(icon.querySelector(".fill-path"), getStyleObject('icon_container'));
            })
        }
    }

    // On DOM ready, perform an initial style update and set up input listeners.
    updateBoxStyles();
    // Listen for changes on all inputs whose name starts with "postology_"
    var inputs = document.querySelectorAll("input[name^='postology_']");
    inputs.forEach(function (input) {
        input.addEventListener('input', updateBoxStyles);
        input.addEventListener('change', updateBoxStyles);
    });


    const widgetVisibility = document.querySelector("#widget-visibility-checkbox");
    if (widgetVisibility) {
        widgetVisibility.addEventListener('change', function (e) {
            // Convert checked state to a numeric value (1 for true, 0 for false)
            var visibility = e.target.checked ? 1 : 0;

            if (visibility) {
                document.querySelector("#widget-visibility-status-span").innerText = "Visible";
                document.querySelector("#widget-visibility-status-span").style.color = "#16db16";

            }else {
                document.querySelector("#widget-visibility-status-span").innerText = "Not Visible";
                document.querySelector("#widget-visibility-status-span").style.color = "#ed7858";
            }

            // Prepare the POST data. Include 'action' parameter so WordPress knows which function to call.
            var postData = 'action=update_widget_visibility&visibility=' + encodeURIComponent(visibility);

            // Optionally include nonce if you have set one:
            postData += '&security=' + encodeURIComponent(myAjax.nonce);

            // Use fetch() to send the AJAX POST request
            fetch(myAjax.ajaxurl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: postData
            })
                .then(function (response) {
                    return response.text();
                })
                .then(function (data) {
                    console.log('Server response:', data);
                })
                .catch(function (error) {
                    console.error('Error updating widget visibility:', error);
                });
        });
    }
    console.log(widgetVisibility)
    console.log('settings loaded');
});

