/**
 * WPSummarize Theme Preview + Customization + AI Style Match
 * v3 — individual padding, theme-specific controls
 *
 * THEME_CONFIG values sourced directly from each wpsummarize_*.css file.
 */
(function($) {
    'use strict';

    /* =====================================================================
       CONFIG
       ===================================================================== */

    var CUSTOM_CSS_TEXTAREA_SELECTOR = 'textarea[name="wpsummarize_custom_css"]';

    /**
     * Theme-specific control definitions.
     *
     * Each control:
     *   label   – what the user sees
     *   type    – 'color' or 'range'
     *   default – the value currently in the theme CSS
     *   rules[] – CSS rule templates. {sel} = theme selector, {val} = user value
     *
     * For range controls also: min, max, step, unit
     */
    var THEME_CONFIG = {

        /* -- Classic ---------------------------------- */
        classic: {
            borderColor:    { label: 'Box border',         type: 'color', default: '#e0e0e0',
                              rules: ['{sel} { border-color: {val}; }'] },
            separatorColor: { label: 'Item separator',     type: 'color', default: '#dddddd',
                              rules: ['{sel} li::after { background: {val}; }'] },
            boxRadius:      { label: 'Box roundness',      type: 'range', default: 8, min: 0, max: 30, unit: 'px',
                              rules: ['{sel} { border-radius: {val}px; }'] }
        },

        /* -- Formal ----------------------------------- */
        formal: {
            accentColor:    { label: 'Left border accent', type: 'color', default: '#007bff',
                              rules: ['{sel} { border-left-color: {val}; }', '{sel} li::before { color: {val}; }'] },
            titleUnderline: { label: 'Title underline',    type: 'color', default: '#dee2e6',
                              rules: ['{sel} .wpsummarize_title { border-bottom-color: {val}; }'] },
            strongColor:    { label: 'Bold text',          type: 'color', default: '#28a745',
                              rules: ['{sel} strong { color: {val}; }'] },
            emColor:        { label: 'Emphasis text',      type: 'color', default: '#6c757d',
                              rules: ['{sel} em { color: {val}; }'] }
        },

        /* -- Elegant ---------------------------------- */
        elegant: {
            accentColor:    { label: 'Left border accent', type: 'color', default: '#4a90e2',
                              rules: ['{sel} li { border-left-color: {val}; }', '{sel} strong { color: {val}; }'] },
            itemBg:         { label: 'Item background',    type: 'color', default: '#f9f9f9',
                              rules: ['{sel} li { background: {val}; }'] },
            titleUnderline: { label: 'Title underline',    type: 'color', default: '#e0e0e0',
                              rules: ['{sel} .wpsummarize_title { border-bottom-color: {val}; }'] }
        },

        /* -- Bubbles ---------------------------------- */
        bubbles: {
            accentColor:    { label: 'Title underline bar',type: 'color', default: '#007bff',
                              rules: ['{sel} .wpsummarize_title::after { background: {val}; }', '{sel} li::before { color: {val}; }'] },
            itemBg:         { label: 'Card background',    type: 'color', default: '#ffffff',
                              rules: ['{sel} li { background: {val}; }'] },
            itemRadius:     { label: 'Card roundness',     type: 'range', default: 10, min: 0, max: 30, unit: 'px',
                              rules: ['{sel} li { border-radius: {val}px; }'] },
            strongColor:    { label: 'Highlight text',     type: 'color', default: '#28a745',
                              rules: ['{sel} strong { color: {val}; }'] }
        },

        /* -- Numbered --------------------------------- */
        numbered: {
            underlineBar:   { label: 'Title underline bar',type: 'color', default: '#3498db',
                              rules: ['{sel} .wpsummarize_title::after { background: {val}; }', '{sel} p::after { background: {val}; }'] },
            circleColor1:   { label: 'Circle #1',          type: 'color', default: '#3498db',
                              rules: ['{sel} li:nth-child(1)::before { background: {val}; }'] },
            circleColor2:   { label: 'Circle #2',          type: 'color', default: '#e74c3c',
                              rules: ['{sel} li:nth-child(2)::before { background: {val}; }'] },
            circleColor3:   { label: 'Circle #3',          type: 'color', default: '#2ecc71',
                              rules: ['{sel} li:nth-child(3)::before { background: {val}; }'] },
            circleColor4:   { label: 'Circle #4',          type: 'color', default: '#f39c12',
                              rules: ['{sel} li:nth-child(4)::before { background: {val}; }'] },
            itemBg:         { label: 'Card background',    type: 'color', default: '#ffffff',
                              rules: ['{sel} li { background: {val}; }'] },
            itemRadius:     { label: 'Card roundness',     type: 'range', default: 15, min: 0, max: 30, unit: 'px',
                              rules: ['{sel} li { border-radius: {val}px; }'] }
        },

        /* -- Sunset ----------------------------------- */
        sunset: {
            accentColor:    { label: 'Title underline',    type: 'color', default: '#fb923c',
                              rules: ['{sel} .wpsummarize_title { border-bottom-color: {val}; }'] },
            borderColor:    { label: 'Box border',         type: 'color', default: '#fdba74',
                              rules: ['{sel} { border-color: {val}; }'] },
            itemBg:         { label: 'Item background',    type: 'color', default: '#ffffff',
                              rules: ['{sel} li { background: rgba({val}, .7); }'] },
            itemRadius:     { label: 'Item roundness',     type: 'range', default: 10, min: 0, max: 25, unit: 'px',
                              rules: ['{sel} li { border-radius: {val}px; }'] },
            strongColor:    { label: 'Bold text',          type: 'color', default: '#c2410c',
                              rules: ['{sel} strong { color: {val}; }'] },
            emColor:        { label: 'Emphasis text',      type: 'color', default: '#ea580c',
                              rules: ['{sel} em { color: {val}; }'] }
        },

        /* -- Dark ------------------------------------- */
        dark: {
            borderAccent:   { label: 'Item left border',   type: 'color', default: '#0f3460',
                              rules: ['{sel} li { border-left-color: {val}; }'] },
            hoverAccent:    { label: 'Hover accent',       type: 'color', default: '#e94560',
                              rules: ['{sel} li:hover { border-left-color: {val}; }'] },
            itemBg:         { label: 'Item background',    type: 'color', default: '#16213e',
                              rules: ['{sel} li { background: {val}; }'] },
            itemRadius:     { label: 'Item roundness',     type: 'range', default: 8, min: 0, max: 20, unit: 'px',
                              rules: ['{sel} li { border-radius: {val}px; }'] },
            titleSeparator: { label: 'Title separator',    type: 'color', default: '#2d2d44',
                              rules: ['{sel} .wpsummarize_title { border-bottom-color: {val}; }'] },
            strongColor:    { label: 'Bold text',          type: 'color', default: '#53a8ff',
                              rules: ['{sel} strong { color: {val}; }'] },
            emColor:        { label: 'Emphasis text',      type: 'color', default: '#e94560',
                              rules: ['{sel} em { color: {val}; }'] }
        },

        /* -- Magazine --------------------------------- */
        magazine: {
            ruleColor:      { label: 'Top/bottom rule',    type: 'color', default: '#222222',
                              rules: ['{sel} { border-top-color: {val}; border-bottom-color: {val}; }'] },
            columnDivider:  { label: 'Column divider',     type: 'color', default: '#e0e0e0',
                              rules: ['{sel} ul { column-rule-color: {val}; }'] },
            ornamentColor:  { label: 'Ornament color',     type: 'color', default: '#999999',
                              rules: ['{sel} .wpsummarize_title::after { color: {val}; }'] },
            strongColor:    { label: 'Bold text',          type: 'color', default: '#8b0000',
                              rules: ['{sel} strong { color: {val}; }'] },
            itemSeparator:  { label: 'Item separator',     type: 'color', default: '#eeeeee',
                              rules: ['{sel} li { border-bottom-color: {val}; }'] }
        },

        /* -- Nature ----------------------------------- */
        nature: {
            borderAccent:   { label: 'Item left border',   type: 'color', default: '#6b8f3c',
                              rules: ['{sel} li { border-left-color: {val}; }'] },
            titleDashes:    { label: 'Title dash line',    type: 'color', default: '#8b7d5e',
                              rules: ['{sel} .wpsummarize_title::after { background: repeating-linear-gradient(90deg, {val} 0, {val} 8px, transparent 8px, transparent 14px); }'] },
            borderColor:    { label: 'Box border',         type: 'color', default: '#d4c9b0',
                              rules: ['{sel} { border-color: {val}; }'] },
            itemRadius:     { label: 'Item roundness',     type: 'range', default: 8, min: 0, max: 20, unit: 'px',
                              rules: ['{sel} li { border-radius: {val}px; }'] },
            strongColor:    { label: 'Bold text',          type: 'color', default: '#4a7c22',
                              rules: ['{sel} strong { color: {val}; }'] },
            emColor:        { label: 'Emphasis text',      type: 'color', default: '#8b7d5e',
                              rules: ['{sel} em { color: {val}; }'] }
        },

        /* -- Timeline --------------------------------- */
        timeline: {
            strongColor:    { label: 'Bold text',          type: 'color', default: '#2563eb',
                              rules: ['{sel} strong { color: {val}; }'] },
            emColor:        { label: 'Emphasis text',      type: 'color', default: '#7c3aed',
                              rules: ['{sel} em { color: {val}; }'] },
            itemBg:         { label: 'Item background',    type: 'color', default: '#f8fafc',
                              rules: ['{sel} li { background: {val}; }'] },
            itemBorder:     { label: 'Item border',        type: 'color', default: '#e2e8f0',
                              rules: ['{sel} li { border-color: {val}; }', '{sel} li::after { background: {val}; }'] },
            titleUnderline: { label: 'Title underline',    type: 'color', default: '#e2e8f0',
                              rules: ['{sel} .wpsummarize_title { border-bottom-color: {val}; }'] },
            itemRadius:     { label: 'Item roundness',     type: 'range', default: 8, min: 0, max: 20, unit: 'px',
                              rules: ['{sel} li { border-radius: {val}px; }'] }
        },

        /* -- Sticky Notes ----------------------------- */
        stickynotes: {
            note1Bg:        { label: 'Note color 1 (yellow)', type: 'color', default: '#fff9b1',
                              rules: ['{sel} li:nth-child(8n+1) { background: {val}; }'] },
            note2Bg:        { label: 'Note color 2 (blue)',   type: 'color', default: '#b1f0ff',
                              rules: ['{sel} li:nth-child(8n+2) { background: {val}; }'] },
            note3Bg:        { label: 'Note color 3 (pink)',   type: 'color', default: '#ffb1d0',
                              rules: ['{sel} li:nth-child(8n+3) { background: {val}; }'] },
            note4Bg:        { label: 'Note color 4 (green)',  type: 'color', default: '#b1ffcc',
                              rules: ['{sel} li:nth-child(8n+4) { background: {val}; }'] },
            note5Bg:        { label: 'Note color 5 (orange)', type: 'color', default: '#ffd6a5',
                              rules: ['{sel} li:nth-child(8n+5) { background: {val}; }'] },
            note6Bg:        { label: 'Note color 6 (purple)', type: 'color', default: '#d0b1ff',
                              rules: ['{sel} li:nth-child(8n+6) { background: {val}; }'] },
            note7Bg:        { label: 'Note color 7 (sky)',    type: 'color', default: '#b1d4ff',
                              rules: ['{sel} li:nth-child(8n+7) { background: {val}; }'] },
            note8Bg:        { label: 'Note color 8 (peach)',  type: 'color', default: '#ffe0b1',
                              rules: ['{sel} li:nth-child(8n+8) { background: {val}; }'] }
        },

        /* -- Spotlight -------------------------------- */
        spotlight: {
            accentColor:    { label: 'Accent / highlight',  type: 'color', default: '#fbbf24',
                              rules: [
                                  '{sel} .wpsummarize_title::after { background: {val}; }',
                                  '{sel} strong { color: {val}; }',
                                  '{sel} ul:hover li:hover::before { background: {val}; border-color: {val}; box-shadow: 0 0 12px rgba(251,191,36,.5); }'
                              ] },
            dotColor:       { label: 'Dot (inactive)',      type: 'color', default: '#333333',
                              rules: ['{sel} li::before { background: {val}; }'] },
            dotBorder:      { label: 'Dot border',          type: 'color', default: '#555555',
                              rules: ['{sel} li::before { border-color: {val}; }'] },
            emColor:        { label: 'Emphasis text',       type: 'color', default: '#60a5fa',
                              rules: ['{sel} em { color: {val}; }'] },
            itemRadius:     { label: 'Item roundness',      type: 'range', default: 10, min: 0, max: 25, unit: 'px',
                              rules: ['{sel} li { border-radius: {val}px; }'] }
        },

        /* -- No CSS ----------------------------------- */
        no_css: {}
    };


    /* =====================================================================
       STATE
       ===================================================================== */
    var currentTheme = null;
    var currentPostId = null;
    var loadedCssUrls = {};
    var previewRequest = null;
    var aiMatchRequest = null;

    var changedProps = {};     // general controls
    var tsChangedProps = {};   // theme-specific controls
    var paddingLinked = true;

    var rangeDefaults = {
        'padding': '20', 'padding-top': '20', 'padding-right': '20',
        'padding-bottom': '20', 'padding-left': '20',
        'border-width': '0', 'border-radius': '0',
        'title-size': '1.3', 'text-size': '1'
    };


    /* =====================================================================
       INIT
       ===================================================================== */
    $(document).ready(function() {
        var $sel = $('#wpsummarize-theme-selector');
        if (!$sel.length) return;

        currentTheme = $sel.find('.wpsummarize-theme-thumb.active').data('theme') || 'classic';
        currentPostId = $('#wpsummarize-preview-post-select').val() || 'placeholder';

        bindThemeClicks($sel);
        bindPostSelect();
        bindBgToggle($sel);
        bindCustomizeToggle();
        bindGeneralControls();
        bindPaddingLink();
        bindCssOutputActions();
        bindAiStyleMatch();

        renderThemeSpecificControls(currentTheme);
        loadPreview(currentTheme, currentPostId);
    });


    /* =====================================================================
       THEME PREVIEW
       ===================================================================== */

    function bindThemeClicks($sel) {
        $sel.on('click', '.wpsummarize-theme-thumb', function() {
            var theme = $(this).data('theme');
            if (theme === currentTheme) return;

            $sel.find('.wpsummarize-theme-thumb').removeClass('active');
            $(this).addClass('active').find('.wpsummarize-theme-radio').prop('checked', true);

            currentTheme = theme;
            loadPreview(theme, currentPostId);
            resetAllCustomizations();
            renderThemeSpecificControls(theme);
        });
    }

    function bindPostSelect() {
        $('#wpsummarize-preview-post-select').on('change', function() {
            currentPostId = $(this).val();
            loadPreview(currentTheme, currentPostId);
            $('#wpsummarize-preview-source-note').text(
                currentPostId === 'placeholder' ? 'Showing placeholder text.' : 'Showing a summary from your site.'
            );
        });
    }

    function bindBgToggle($sel) {
        $sel.on('click', '.wpsummarize-bg-toggle button', function(e) {
            e.preventDefault();
            $sel.find('.wpsummarize-bg-toggle button').removeClass('active');
            $(this).addClass('active');
            $('#wpsummarize-preview-area')
                .removeClass('wpsummarize-bg-light wpsummarize-bg-grey wpsummarize-bg-dark')
                .addClass('wpsummarize-bg-' + $(this).data('bg'));
        });
    }

    function loadPreview(theme, postId) {
        var $c = $('#wpsummarize-preview-content');
        if (previewRequest && previewRequest.readyState !== 4) previewRequest.abort();
        $c.addClass('wpsummarize-preview-fading');

        previewRequest = $.ajax({
            url: wpSummarizeAjax.ajaxurl, type: 'POST',
            data: { action: 'wpsummarize_theme_preview', nonce: wpSummarizeAjax.nonce,
                    theme: theme, post_id: (postId === 'placeholder') ? 0 : postId },
            success: function(r) {
                if (r.success && r.data) {
                    loadThemeCss(r.data.css_url, r.data.theme, function() {
                        setTimeout(function() {
                            $c.html(r.data.html).removeClass('wpsummarize-preview-fading');
                            applyAllToPreview();
                        }, 150);
                    });
                } else {
                    $c.html('<p style="color:#d63638;">Error.</p>').removeClass('wpsummarize-preview-fading');
                }
            },
            error: function(x, s) {
                if (s !== 'abort') $c.html('<p style="color:#d63638;">Error loading preview.</p>').removeClass('wpsummarize-preview-fading');
            }
        });
    }

    function loadThemeCss(url, theme, cb) {
        if (loadedCssUrls[theme]) { cb(); return; }
        var $l = $('<link>', { id: 'wpsummarize-theme-css-' + theme, rel: 'stylesheet', type: 'text/css', href: url });
        $l.on('load error', function() { loadedCssUrls[theme] = true; cb(); });
        $('head').append($l);
    }


    /* =====================================================================
       CUSTOMIZE TOGGLE
       ===================================================================== */

    function bindCustomizeToggle() {
        $('#wpsummarize-customize-toggle').on('click', function() {
            var $p = $('#wpsummarize-customize-panel'), $a = $(this).find('.wpsummarize-customize-arrow');
            $p.slideToggle(200, function() { $a.toggleClass('dashicons-arrow-down-alt2 dashicons-arrow-up-alt2'); });
        });
    }


    /* =====================================================================
       GENERAL CONTROLS (colors + sliders)
       ===================================================================== */

    function bindGeneralControls() {
        var $panel = $('#wpsummarize-customize-panel');

        // Colors
        $panel.on('input change', '.wpsummarize-customize-section input[type="color"]', function() {
            changedProps[$(this).data('prop')] = $(this).val();
            applyAllToPreview(); updateCssOutput();
        });

        // Range sliders (not padding-* sides)
        $panel.on('input', '.wpsummarize-customize-section input[type="range"]:not([data-prop^="padding-"])', function() {
            var prop = $(this).data('prop');
            if (prop === 'padding' && paddingLinked) {
                changedProps['padding'] = $(this).val();
                $('#wps-cust-padding-val').text($(this).val() + 'px');
            } else if (prop !== 'padding') {
                changedProps[prop] = $(this).val();
                var unit = (prop === 'title-size' || prop === 'text-size') ? 'em' : 'px';
                $('#wps-cust-' + prop + '-val').text($(this).val() + unit);
            }
            applyAllToPreview(); updateCssOutput();
        });

        // Unlinked padding sides
        $panel.on('input', 'input[data-prop^="padding-"]', function() {
            var prop = $(this).data('prop');
            if (prop === 'padding-all') return;
            changedProps[prop] = $(this).val();
            $('#wps-cust-' + prop + '-val').text($(this).val() + 'px');
            applyAllToPreview(); updateCssOutput();
        });

        // Reset buttons (general section only)
        $panel.on('click', '.wpsummarize-customize-section .wpsummarize-reset-control', function() {
            var prop = $(this).data('prop');

            if (prop === 'padding-all') {
                ['padding-top','padding-right','padding-bottom','padding-left'].forEach(function(p) {
                    delete changedProps[p];
                    $('[data-prop="' + p + '"]').val(20);
                    $('#wps-cust-' + p + '-val').text('20px');
                });
            } else {
                delete changedProps[prop];
                var $input = $('[data-prop="' + prop + '"]').not('button');
                if ($input.attr('type') === 'range') {
                    var def = rangeDefaults[prop] || '0';
                    $input.val(def);
                    var unit = (prop === 'title-size' || prop === 'text-size') ? 'em' : 'px';
                    $('#wps-cust-' + prop + '-val').text(def + unit);
                } else if ($input.attr('type') === 'color') {
                    $input.val('#cccccc');
                }
            }
            applyAllToPreview(); updateCssOutput();
        });
    }


    /* =====================================================================
       PADDING LINK / UNLINK
       ===================================================================== */

    function bindPaddingLink() {
        $('#wpsummarize-padding-link').on('click', function() {
            paddingLinked = !paddingLinked;
            $(this).toggleClass('active');

            if (paddingLinked) {
                var val = changedProps['padding-top'] || '20';
                delete changedProps['padding-top']; delete changedProps['padding-right'];
                delete changedProps['padding-bottom']; delete changedProps['padding-left'];
                changedProps['padding'] = val;
                $('#wps-cust-padding').val(val);
                $('#wps-cust-padding-val').text(val + 'px');

                $('#wpsummarize-padding-linked').show();
                $('#wpsummarize-padding-unlinked').hide();
                $(this).find('.dashicons').removeClass('dashicons-editor-unlink').addClass('dashicons-admin-links');
            } else {
                var val = changedProps['padding'] || '20';
                delete changedProps['padding'];

                ['padding-top','padding-right','padding-bottom','padding-left'].forEach(function(p) {
                    changedProps[p] = val;
                    $('[data-prop="' + p + '"]').val(val);
                    $('#wps-cust-' + p + '-val').text(val + 'px');
                });

                $('#wpsummarize-padding-linked').hide();
                $('#wpsummarize-padding-unlinked').show();
                $(this).find('.dashicons').removeClass('dashicons-admin-links').addClass('dashicons-editor-unlink');
            }
            applyAllToPreview(); updateCssOutput();
        });
    }


    /* =====================================================================
       THEME-SPECIFIC CONTROLS (dynamic rendering)
       ===================================================================== */

    function renderThemeSpecificControls(theme) {
        var config = THEME_CONFIG[theme] || {};
        var $section = $('#wpsummarize-theme-specific-section');
        var $container = $('#wpsummarize-theme-specific-controls');

        tsChangedProps = {};
        $container.off(); // unbind previous events
        $container.empty();

        var keys = Object.keys(config);
        if (!keys.length) { $section.hide(); return; }

        // Set section title to include theme name
        var themeLabel = $('#wpsummarize-theme-selector .wpsummarize-theme-thumb.active .wpsummarize-theme-thumb-label').text() || theme;
        $('#wpsummarize-theme-specific-title').text(themeLabel + ' accents');

        $section.show();

        keys.forEach(function(key) {
            var ctrl = config[key];
            var html = '<div class="wpsummarize-control-row" data-ts-key="' + key + '">';
            html += '<label>' + ctrl.label + '</label>';
            html += '<div class="wpsummarize-control-input';

            if (ctrl.type === 'range') {
                html += ' wpsummarize-control-slider">';
                html += '<input type="range" data-ts-prop="' + key + '"';
                html += ' min="' + (ctrl.min || 0) + '" max="' + (ctrl.max || 30) + '"';
                html += ' step="' + (ctrl.step || 1) + '" value="' + ctrl.default + '" />';
                html += '<span class="wpsummarize-slider-value" id="wps-ts-' + key + '-val">' + ctrl.default + (ctrl.unit || 'px') + '</span>';
            } else {
                html += '">';
                html += '<input type="color" data-ts-prop="' + key + '" value="' + ctrl.default + '" />';
            }

            html += '<button type="button" class="wpsummarize-reset-control wpsummarize-ts-reset" data-ts-prop="' + key + '" title="Reset">&times;</button>';
            html += '</div></div>';

            $container.append(html);
        });

        // Bind events
        $container.on('input change', 'input[type="color"]', function() {
            tsChangedProps[$(this).data('ts-prop')] = $(this).val();
            applyAllToPreview(); updateCssOutput();
        });

        $container.on('input', 'input[type="range"]', function() {
            var k = $(this).data('ts-prop'), v = $(this).val();
            tsChangedProps[k] = v;
            $('#wps-ts-' + k + '-val').text(v + (config[k].unit || 'px'));
            applyAllToPreview(); updateCssOutput();
        });

        $container.on('click', '.wpsummarize-ts-reset', function() {
            var k = $(this).data('ts-prop');
            delete tsChangedProps[k];
            var cfg = config[k], $i = $('[data-ts-prop="' + k + '"]').not('button');
            if (cfg.type === 'range') {
                $i.val(cfg.default);
                $('#wps-ts-' + k + '-val').text(cfg.default + (cfg.unit || 'px'));
            } else if (cfg.type === 'color') {
                $i.val(cfg.default);
            }
            applyAllToPreview(); updateCssOutput();
        });
    }


    /* =====================================================================
       PREVIEW INJECTION
       ===================================================================== */

    function applyAllToPreview() {
        var id = 'wpsummarize-customize-preview-styles';
        var $ex = $('#' + id);
        var hasG = !$.isEmptyObject(changedProps), hasT = !$.isEmptyObject(tsChangedProps);

        if (!hasG && !hasT) { $ex.remove(); return; }

        var sel = '#wpsummarize-preview-content .wpsummarize_box.design-' + currentTheme;
        var rules = [];

        // -- General box --
        var box = [];
        if (changedProps['bg-color'])      box.push('background: ' + changedProps['bg-color'] + ' !important');
        if (changedProps['border-color'])   box.push('border-color: ' + changedProps['border-color'] + ' !important');
        if (changedProps['border-width'])   box.push('border-width: ' + changedProps['border-width'] + 'px !important; border-style: solid');
        if (changedProps['border-radius'])  box.push('border-radius: ' + changedProps['border-radius'] + 'px !important');

        if (paddingLinked && changedProps['padding']) {
            box.push('padding: ' + changedProps['padding'] + 'px !important');
        } else if (!paddingLinked) {
            var pt = changedProps['padding-top'], pr = changedProps['padding-right'],
                pb = changedProps['padding-bottom'], pl = changedProps['padding-left'];
            if (pt || pr || pb || pl) {
                box.push('padding: ' + (pt||'20') + 'px ' + (pr||'20') + 'px ' + (pb||'20') + 'px ' + (pl||'20') + 'px !important');
            }
        }
        if (box.length) rules.push(sel + ' { ' + box.join('; ') + '; }');

        // Title
        var tit = [];
        if (changedProps['title-color']) tit.push('color: ' + changedProps['title-color'] + ' !important');
        if (changedProps['title-size'])  tit.push('font-size: ' + changedProps['title-size'] + 'em !important');
        if (tit.length) rules.push(sel + ' .wpsummarize_title { ' + tit.join('; ') + '; }');

        // Text
        var txt = [];
        if (changedProps['text-color']) txt.push('color: ' + changedProps['text-color'] + ' !important');
        if (changedProps['text-size'])  txt.push('font-size: ' + changedProps['text-size'] + 'em !important');
        if (txt.length) {
            rules.push(sel + ' li { ' + txt.join('; ') + '; }');
            rules.push(sel + ' p { ' + txt.join('; ') + '; }');
        }

        if (changedProps['strong-color']) rules.push(sel + ' strong { color: ' + changedProps['strong-color'] + ' !important; }');

        // -- Theme-specific --
        var config = THEME_CONFIG[currentTheme] || {};
        $.each(tsChangedProps, function(key, val) {
            var ctrl = config[key];
            if (!ctrl || !ctrl.rules) return;
            ctrl.rules.forEach(function(rule) {
                var r = rule.replace(/\{sel\}/g, sel).replace(/\{val\}/g, val);
                // Inject !important before each semicolon and closing brace
                r = r.replace(/;(?!\s*})/g, ' !important;');
                r = r.replace(/;\s*}/g, ' !important; }');
                // Handle last property if no trailing semicolon
                r = r.replace(/([^;{])\s*}/g, '$1 !important; }');
                rules.push(r);
            });
        });

        var css = rules.join('\n');
        if ($ex.length) { $ex.text(css); } else { $('<style>', { id: id, text: css }).appendTo('head'); }
    }


    /* =====================================================================
       CSS OUTPUT GENERATION
       ===================================================================== */

    function updateCssOutput() {
        var $wrapper = $('#wpsummarize-css-output-wrapper');
        var $textarea = $('#wpsummarize-css-output');
        var hasG = !$.isEmptyObject(changedProps), hasT = !$.isEmptyObject(tsChangedProps);

        if (!hasG && !hasT) {
            // Only hide if there's no AI-generated CSS sitting in the textarea.
            // AI CSS gets set via applyRawCssToPreview which adds #wpsummarize-ai-preview-styles.
            // If that style tag doesn't exist, this is leftover manual CSS — clear it.
            if (!$('#wpsummarize-ai-preview-styles').length) {
                $textarea.val('');
                $wrapper.slideUp(150);
            }
            return;
        }

        $wrapper.slideDown(150);

        var sel = '.wpsummarize_box.design-' + currentTheme;
        var lines = ['/* WPSummarize: Custom overrides for ' + currentTheme + ' theme */'];

        // Box
        var bR = [];
        if (changedProps['bg-color'])      bR.push('    background: ' + changedProps['bg-color'] + ';');
        if (changedProps['border-color'])   bR.push('    border-color: ' + changedProps['border-color'] + ';');
        if (changedProps['border-width'])   { bR.push('    border-width: ' + changedProps['border-width'] + 'px;'); bR.push('    border-style: solid;'); }
        if (changedProps['border-radius'])  bR.push('    border-radius: ' + changedProps['border-radius'] + 'px;');

        if (paddingLinked && changedProps['padding']) {
            bR.push('    padding: ' + changedProps['padding'] + 'px;');
        } else if (!paddingLinked) {
            var pt = changedProps['padding-top'], pr = changedProps['padding-right'],
                pb = changedProps['padding-bottom'], pl = changedProps['padding-left'];
            if (pt || pr || pb || pl) {
                bR.push('    padding: ' + (pt||'20') + 'px ' + (pr||'20') + 'px ' + (pb||'20') + 'px ' + (pl||'20') + 'px;');
            }
        }
        if (bR.length) { lines.push(sel + ' {'); lines = lines.concat(bR); lines.push('}'); }

        // Title
        var tR = [];
        if (changedProps['title-color']) tR.push('    color: ' + changedProps['title-color'] + ';');
        if (changedProps['title-size'])  tR.push('    font-size: ' + changedProps['title-size'] + 'em;');
        if (tR.length) { lines.push(sel + ' .wpsummarize_title {'); lines = lines.concat(tR); lines.push('}'); }

        // Text
        var xR = [];
        if (changedProps['text-color']) xR.push('    color: ' + changedProps['text-color'] + ';');
        if (changedProps['text-size'])  xR.push('    font-size: ' + changedProps['text-size'] + 'em;');
        if (xR.length) { lines.push(sel + ' li,'); lines.push(sel + ' p {'); lines = lines.concat(xR); lines.push('}'); }

        if (changedProps['strong-color']) {
            lines.push(sel + ' strong {'); lines.push('    color: ' + changedProps['strong-color'] + ';'); lines.push('}');
        }

        // Theme-specific
        var config = THEME_CONFIG[currentTheme] || {};
        $.each(tsChangedProps, function(key, val) {
            var ctrl = config[key];
            if (!ctrl || !ctrl.rules) return;
            ctrl.rules.forEach(function(rule) {
                lines.push(rule.replace(/\{sel\}/g, sel).replace(/\{val\}/g, val));
            });
        });

        $textarea.val(lines.join('\n'));
    }


    /* =====================================================================
       CSS OUTPUT ACTIONS
       ===================================================================== */

    function bindCssOutputActions() {
        $('#wpsummarize-add-to-custom-css').on('click', function() {
            var css = $('#wpsummarize-css-output').val();
            if (!css) return;
            var $t = findCustomCssTextarea();
            if ($t.length) {
                var ex = $t.val().trim();
                $t.val(ex + (ex ? '\n\n' : '') + css);
                $t[0].scrollTop = $t[0].scrollHeight;
                $t.addClass('wpsummarize-flash');
                setTimeout(function() { $t.removeClass('wpsummarize-flash'); }, 1500);
                showStatus('Added to Custom CSS! Remember to save settings.', 'success');
            } else {
                copyToClipboard(css);
                showStatus('Custom CSS field not found. Copied to clipboard instead.', 'warning');
            }
        });

        $('#wpsummarize-copy-css').on('click', function() {
            var css = $('#wpsummarize-css-output').val();
            if (css) { copyToClipboard(css); showStatus('Copied!', 'success'); }
        });

        $('#wpsummarize-reset-all-customizations').on('click', resetAllCustomizations);
    }

    function findCustomCssTextarea() {
        var $t = $(CUSTOM_CSS_TEXTAREA_SELECTOR);
        if (!$t.length) $t = $('#wpsummarize_custom_css, textarea[name="wpsummarize_options[custom_css]"]').first();
        return $t;
    }

    function resetAllCustomizations() {
        changedProps = {};
        tsChangedProps = {};

        // Reset general range sliders
        $.each(rangeDefaults, function(prop, val) {
            var $i = $('[data-prop="' + prop + '"]').not('button');
            if ($i.length) {
                $i.val(val);
                var unit = (prop === 'title-size' || prop === 'text-size') ? 'em' : 'px';
                $('#wps-cust-' + prop + '-val').text(val + unit);
            }
        });

        // Reset general color inputs to neutral gray
        $('#wpsummarize-customize-panel .wpsummarize-customize-section input[type="color"]').val('#cccccc');

        // Restore linked padding
        if (!paddingLinked) {
            paddingLinked = true;
            $('#wpsummarize-padding-linked').show();
            $('#wpsummarize-padding-unlinked').hide();
            $('#wpsummarize-padding-link').addClass('active')
                .find('.dashicons').removeClass('dashicons-editor-unlink').addClass('dashicons-admin-links');
        }

        // Reset theme-specific controls to their actual defaults
        var config = THEME_CONFIG[currentTheme] || {};
        $.each(config, function(key, ctrl) {
            var $i = $('[data-ts-prop="' + key + '"]').not('button');
            $i.val(ctrl.default);
            if (ctrl.type === 'range') $('#wps-ts-' + key + '-val').text(ctrl.default + (ctrl.unit || 'px'));
        });

        $('#wpsummarize-customize-preview-styles').remove();
        $('#wpsummarize-ai-preview-styles').remove();
        $('#wpsummarize-css-output-wrapper').slideUp(150);
        $('#wpsummarize-css-output').val('');
        $('#wpsummarize-css-output-status').text('').removeClass('success warning');
    }

    function copyToClipboard(t) {
        if (navigator.clipboard) { navigator.clipboard.writeText(t); }
        else { var $a = $('<textarea>').val(t).appendTo('body').select(); document.execCommand('copy'); $a.remove(); }
    }

    function showStatus(msg, type) {
        var $s = $('#wpsummarize-css-output-status');
        $s.text(msg).removeClass('success warning').addClass(type).stop(true).css('opacity', 1);
        setTimeout(function() {
            $s.fadeOut(300, function() { $(this).text('').removeClass('success warning').css({opacity:1,display:''}); });
        }, 4000);
    }


    /* =====================================================================
       AI STYLE MATCH
       ===================================================================== */

    function bindAiStyleMatch() {
        $('#wpsummarize-ai-match-btn').on('click', function() {
            var $btn = $(this), $status = $('#wpsummarize-ai-match-status'),
                $text = $status.find('.wpsummarize-ai-match-status-text'),
                $spin = $status.find('.spinner');

            if ($btn.prop('disabled')) return;
            resetAllCustomizations();

            $btn.prop('disabled', true).addClass('wpsummarize-ai-loading');
            $status.show(); $spin.addClass('is-active');
            $text.text('Analyzing your site\u2019s design\u2026').removeClass('wpsummarize-ai-error wpsummarize-ai-success');

            if (aiMatchRequest && aiMatchRequest.readyState !== 4) aiMatchRequest.abort();

            aiMatchRequest = $.ajax({
                url: wpSummarizeAjax.ajaxurl, type: 'POST', timeout: 45000,
                data: { action: 'wpsummarize_ai_style_match', nonce: wpSummarizeAjax.nonce, theme: currentTheme },
                success: function(r) {
                    $spin.removeClass('is-active');
                    $btn.prop('disabled', false).removeClass('wpsummarize-ai-loading');
                    if (r.success && r.data && r.data.css) {
                        $('#wpsummarize-css-output').val(r.data.css);
                        $('#wpsummarize-css-output-wrapper').slideDown(200);
                        applyRawCssToPreview(r.data.css);
                        $text.text('CSS generated! Review in preview, then click \u201CAdd to Custom CSS\u201D to apply.').addClass('wpsummarize-ai-success');
                        setTimeout(function() { $status.slideUp(200); }, 6000);
                    } else {
                        $text.text(r.data || 'Something went wrong.').addClass('wpsummarize-ai-error');
                    }
                },
                error: function(x, s) {
                    $spin.removeClass('is-active');
                    $btn.prop('disabled', false).removeClass('wpsummarize-ai-loading');
                    if (s !== 'abort') $text.text(s === 'timeout' ? 'Timed out \u2014 try again.' : 'Network error.').addClass('wpsummarize-ai-error');
                }
            });
        });
    }

    function applyRawCssToPreview(raw) {
        var id = 'wpsummarize-ai-preview-styles';
        var scoped = raw.replace(/\.wpsummarize_box/g, '#wpsummarize-preview-content .wpsummarize_box');
        scoped = scoped.replace(/;(\s*\n?\s*})/g, ' !important;$1');
        scoped = scoped.replace(/;\s*$/gm, ' !important;');
        var $ex = $('#' + id);
        if ($ex.length) { $ex.text(scoped); } else { $('<style>', { id: id, text: scoped }).appendTo('head'); }
    }

})(jQuery);