jQuery(document).ready(function ($) {

    // --- Tab Switching ---
    $('.afi-nav-item').on('click', function (e) {
        e.preventDefault();

        // Update Nav
        $('.afi-nav-item').removeClass('active');
        $(this).addClass('active');

        // Update View
        var targetView = $(this).data('view');
        $('.afi-view').removeClass('active');
        $('#view-' + targetView).addClass('active');

        // Toggle Save Bar: Hide on Overview, Show on Settings/Templates
        var $saveBar = $('.afi-save-bar');
        if (targetView === 'overview') {
            $saveBar.addClass('hidden');
            $saveBar.hide();
        } else {
            $saveBar.removeClass('hidden');
            $saveBar.show();
        }

        // Save Active Tab to LocalStorage
        localStorage.setItem('cafi_active_tab', targetView);
    });

    // Restore Active Tab
    var savedTab = localStorage.getItem('cafi_active_tab');
    var serverTab = (typeof cafiData !== 'undefined') ? cafiData.currentTab : '';

    // Priority: Server-side (URL/Menu click) > LocalStorage > Default
    // If serverTab is set and is NOT 'overview' (meaning specific page clicked), we use it. 
    // Actually, even if 'overview', if user clicked Overview menu, we should show Overview. 
    // But 'auto-featured-image' slug defaults to overview, so we treat it as authoritative.

    if (serverTab) {
        $('.afi-nav-item[data-view="' + serverTab + '"]').click();
    } else if (savedTab && savedTab !== 'overview') {
        $('.afi-nav-item[data-view="' + savedTab + '"]').click();
    }


    // Initial Check
    if ($('.afi-nav-item.active').data('view') === 'overview') {
        $('.afi-save-bar').hide().addClass('hidden');
    }

    // --- Font Weight Validation ---
    var fontData = (typeof cafiData !== 'undefined' && cafiData.fontData) ? cafiData.fontData : {};

    $('#afi_font_family').on('change', function () {
        var family = $(this).val();
        var weights = [];

        // Find weights
        if (fontData[family]) {
            // If it's the object format { license: '...', weights: [...] }
            if (fontData[family].weights) {
                weights = fontData[family].weights;
            } else {
                // Legacy or unknown format, assume all standard supported if not specified
                weights = ['Regular', 'Bold'];
            }
        } else {
            // System fonts or unknown
            weights = ['Regular', 'Bold']; // Basic fallback
        }

        var $weightSelect = $('#afi_font_weight');
        var currentWeight = $weightSelect.val();
        var validSelection = false;

        $weightSelect.find('option').each(function () {
            var val = $(this).val();
            if (weights.includes(val)) {
                $(this).prop('disabled', false).show();
                if (val === currentWeight) validSelection = true;
            } else {
                $(this).prop('disabled', true).hide();
            }
        });

        // If current selection is invalid, switch to first valid (usually Regular)
        if (!validSelection) {
            // Try to find 'Regular' or 'Bold' first, else first available
            if (weights.includes('Regular')) {
                $weightSelect.val('Regular');
            } else if (weights.includes('Bold')) {
                $weightSelect.val('Bold');
            } else if (weights.length > 0) {
                $weightSelect.val(weights[0]);
            }
        }

        updatePreview();
    });

    // Trigger on init
    $('#afi_font_family').trigger('change');


    // --- Margin Linking Logic ---
    var isMarginsLinked = true;

    // Check initial state (if values differ, unlink)
    var pTop = $('#afi_padding_top').val();
    var pRight = $('#afi_padding_right').val();
    var pBottom = $('#afi_padding_bottom').val();
    var pLeft = $('#afi_padding_left').val();

    if (pTop !== pRight || pTop !== pBottom || pTop !== pLeft) {
        isMarginsLinked = false;
        $('#afi-link-margins').removeClass('active text-primary border-primary bg-primary/10').addClass('text-gray-400');
    } else {
        $('#afi-link-margins').addClass('active text-primary border-primary bg-primary/10').removeClass('text-gray-400');
    }

    $('#afi-link-margins').on('click', function () {
        isMarginsLinked = !isMarginsLinked;
        if (isMarginsLinked) {
            $(this).addClass('active text-primary border-primary bg-primary/10').removeClass('text-gray-400');
            // Sync to Top value
            var val = $('#afi_padding_top').val();
            $('.afi-margin-input').val(val).trigger('input'); // Trigger input for preview update
        } else {
            $(this).removeClass('active text-primary border-primary bg-primary/10').addClass('text-gray-400');
        }
    });

    $('.afi-margin-input').on('input', function () {
        if (isMarginsLinked) {
            var val = $(this).val();
            // Update others without triggering their input event loops endlessly
            $('.afi-margin-input').not(this).val(val);
        }
        updatePreview();
    });


    // --- Live Preview Updates ---

    function updatePreview() {
        // Gather Values
        var fontSize = parseInt($('#afi_font_size').val()) || 100;
        var fontColor = $('#afi_font_color').val();
        var fontFamily = $('#afi_font_family').val();
        var textPos = $('#afi_text_position').val();
        var textAlign = $('#afi_text_alignment').val();
        var fontWeight = $('#afi_font_weight').val();

        // Margins
        var pTop = parseInt($('#afi_padding_top').val()) || 0;
        var pRight = parseInt($('#afi_padding_right').val()) || 0;
        var pBottom = parseInt($('#afi_padding_bottom').val()) || 0;
        var pLeft = parseInt($('#afi_padding_left').val()) || 0;

        // Logo settings
        var logoUrl = $('#afi_logo_url').val();
        var logoSize = parseInt($('#afi_logo_size').val()) || 20; // percentage
        var logoPos = $('input[name="cafi_settings[logo_position]"]:checked').val() || 'bottom-right';

        // Split Offsets
        var logoOffsetX = parseInt($('#afi_logo_offset_x').val()) || 20;
        var logoOffsetY = parseInt($('#afi_logo_offset_y').val()) || 20;

        var $previewContainer = $('#afi-preview-element');
        var previewWidth = $previewContainer.width() || 348;
        var canvasWidth = 1200;

        var scaleFactor = previewWidth / canvasWidth;
        var scaledFontSize = fontSize * scaleFactor;

        // Scale Margins
        var smTop = pTop * scaleFactor;
        var smRight = pRight * scaleFactor;
        var smBottom = pBottom * scaleFactor;
        var smLeft = pLeft * scaleFactor;

        // Scale Logo Offset
        var smLogoOffsetX = logoOffsetX * scaleFactor;
        var smLogoOffsetY = logoOffsetY * scaleFactor;

        var $previewText = $('.afi-preview-overlay-text');

        // --- Logo Overlay ---
        var $logo = $('#afi-preview-logo-overlay');
        if (logoUrl) {
            if ($logo.length === 0) {
                // Create logo element if missing
                $previewContainer.append('<img id="afi-preview-logo-overlay" src="' + logoUrl + '" style="position:absolute; object-fit:contain; z-index:20;">');
                $logo = $('#afi-preview-logo-overlay');
            } else {
                $logo.attr('src', logoUrl);
                $logo.show();
            }

            // Size: Percentage of preview width
            var logoPixelWidth = (logoSize / 100) * previewWidth;
            $logo.css('width', logoPixelWidth + 'px');
            $logo.css('height', 'auto'); // Maintain aspect ratio

            // Reset Positions
            $logo.css({ top: '', bottom: '', left: '', right: '', transform: '' });

            // Positioning Logic
            var parts = logoPos.split('-'); // e.g., ['top', 'left']
            var vPos = parts[0]; // top, middle, bottom
            var hPos = parts[1]; // left, center, right

            // Vertical
            if (vPos === 'top') {
                $logo.css('top', smLogoOffsetY + 'px');
            } else if (vPos === 'bottom') {
                $logo.css('bottom', smLogoOffsetY + 'px');
            } else { // middle
                $logo.css('top', '50%');
                $logo.css('transform', 'translateY(-50%)'); // Partial transform, needs X too
            }

            // Horizontal
            if (hPos === 'left') {
                $logo.css('left', smLogoOffsetX + 'px');
            } else if (hPos === 'right') {
                $logo.css('right', smLogoOffsetX + 'px');
            } else { // center
                $logo.css('left', '50%');
                if (vPos === 'middle') {
                    $logo.css('transform', 'translate(-50%, -50%)');
                } else {
                    $logo.css('transform', 'translateX(-50%)');
                }
            }

        } else {
            $logo.hide();
        }

        var $previewText = $('.afi-preview-overlay-text');

        // Dynamically Load Google Font (Logic handled previously, just load)
        var systemFonts = ['Arial', 'Verdana', 'Georgia', 'Times New Roman', 'Courier New'];
        if (fontFamily && !systemFonts.includes(fontFamily)) {
            var fontId = 'afi-font-' + fontFamily.replace(/\s+/g, '-').toLowerCase();
            if (!$('#' + fontId).length) {
                var link = document.createElement('link');
                link.id = fontId;
                link.rel = 'stylesheet';
                // Request range of weights
                link.href = 'https://fonts.googleapis.com/css2?family=' + encodeURIComponent(fontFamily) + ':wght@400;500;700;900&display=swap';
                document.head.appendChild(link);
            }
        }

        $previewText.css({
            'font-size': scaledFontSize + 'px',
            'color': fontColor,
            'font-family': "'" + fontFamily + "', sans-serif",
            'font-weight': fontWeight,
            'text-align': textAlign,
            'width': '100%',
            'left': '0',
            'right': '0', // Reset
            'top': '',
            'bottom': '',
            'transform': '',
            'box-sizing': 'border-box',
            'padding-top': '0',
            'padding-left': smLeft + 'px',
            'padding-right': smRight + 'px'
            // Top/Bottom handled via positioning
        });

        // Vertical Positioning Logic with Margins
        if (textPos === 'top') {
            $previewText.css({ 'top': smTop + 'px', 'transform': 'none' });
        } else if (textPos === 'bottom') {
            $previewText.css({ 'bottom': smBottom + 'px', 'top': 'auto', 'transform': 'none' });
        } else {
            // Middle - usually ignores top/bottom margins, but let's see. 
            // If linked, it's irrelevant. If unlinked, usually centered means dead center.
            // But if user sets Top Margin: 200, maybe they want it offset?
            // Standard CSS centering:
            $previewText.css({ 'top': '50%', 'transform': 'translateY(-50%)' });
        }
    }

    // Bind Inputs for Preview (Remove old bindings first if needed, but .on handles it)
    $('#afi_font_size, #afi_font_color, #afi_font_family, #afi_text_position, #afi_text_alignment, #afi_font_weight').on('input change', updatePreview);
    // Bind Logo Inputs
    $('#afi_logo_size, #afi_logo_offset_x, #afi_logo_offset_y').on('input change', updatePreview);
    $('input[name="cafi_settings[logo_position]"]').on('change', updatePreview);

    // Update Logo Size Display
    $('#afi_logo_size').on('input', function () {
        $('#afi_logo_size_display').text($(this).val() + '%');
    });

    // --- Link to Switch Tabs ---
    $(document).on('click', '.afi-change-template-link', function (e) {
        e.preventDefault();
        $('.afi-nav-item[data-view="templates"]').click();
    });

    // --- Template Filter Logic ---
    $('.afi-filter-btn').on('click', function () {
        // Active State
        $('.afi-filter-btn').removeClass('active');
        $(this).addClass('active');

        // Filter Logic
        var filter = $(this).data('filter');
        var $cards = $('.afi-template-card-new');

        if (filter === 'all') {
            $cards.show();
        } else {
            $cards.hide();
            // Show only matching category
            $('.afi-template-card-new[data-category="' + filter + '"]').show();
        }
    });

    // --- Template Selection ---
    $(document).on('click', '.afi-template-card-new', function () {
        $('.afi-template-card-new').removeClass('active');
        $('.afi-card-status-dot').removeClass('active');
        $('.afi-active-badge').remove();

        $(this).addClass('active');
        $(this).find('.afi-card-status-dot').addClass('active');

        if ($(this).find('.afi-card-hero .afi-active-badge').length === 0) {
            $(this).find('.afi-card-hero').append('<div class="afi-active-badge"><span class="material-symbols-outlined" style="font-size:14px;">check</span>Active</div>');
        }

        var tmplType = $(this).data('type');
        var tmplValue = $(this).data('value');
        var tmplId = $(this).data('id');
        var templateName = $(this).data('name');
        var settingsRaw = $(this).data('settings');

        // Reset defaults to prevent state leakage from previous templates
        $('.afi-margin-input').val(60);
        $('#afi_text_position').val('middle');
        $('#afi_text_alignment').val('center');

        // Reset Visual Buttons (to match defaults)
        $('.afi-pos-btn').removeClass('bg-white dark:bg-primary text-primary dark:text-white').addClass('text-gray-600 dark:text-gray-400 hover:text-gray-900');
        $('.afi-pos-btn[data-value="middle"]').removeClass('text-gray-600 dark:text-gray-400 hover:text-gray-900').addClass('bg-white dark:bg-primary text-primary dark:text-white');

        $('.afi-align-btn').removeClass('bg-white dark:bg-primary text-primary dark:text-white shadow-sm').addClass('text-gray-600 dark:text-gray-400 hover:bg-white');
        $('.afi-align-btn[data-value="center"]').removeClass('text-gray-600 dark:text-gray-400 hover:bg-white').addClass('bg-white dark:bg-primary text-primary dark:text-white shadow-sm');

        // Reset Logo Defaults
        $('#afi_logo_size').val(25);
        $('#afi_logo_offset_x').val(20);
        $('#afi_logo_offset_y').val(20);

        if (settingsRaw) {
            try {
                var s = settingsRaw;
                if (typeof s === 'string') {
                    s = JSON.parse(s);
                }

                // Font
                if (s.font_family) $('#afi_font_family').val(s.font_family).trigger('change');

                // Set Weight with delay to allow Family options to update
                if (s.font_weight) {
                    setTimeout(function () {
                        $('#afi_font_weight').val(s.font_weight).trigger('change');
                    }, 50);
                }

                if (s.font_size) $('#afi_font_size').val(s.font_size).trigger('input');

                // Color
                if (s.font_color) {
                    $('#afi_font_color').val(s.font_color).trigger('change');
                    if (pickr) pickr.setColor(s.font_color);
                }

                // Position/Align
                if (s.text_position) {
                    $('#afi_text_position').val(s.text_position).trigger('change');
                    // Update visual buttons
                    $('.afi-pos-btn').removeClass('bg-white dark:bg-primary text-primary dark:text-white').addClass('text-gray-600 dark:text-gray-400 hover:text-gray-900');
                    $('.afi-pos-btn[data-value="' + s.text_position + '"]').removeClass('text-gray-600 dark:text-gray-400 hover:text-gray-900').addClass('bg-white dark:bg-primary text-primary dark:text-white');
                }
                if (s.text_alignment) {
                    $('#afi_text_alignment').val(s.text_alignment).trigger('change');
                    $('.afi-align-btn').removeClass('bg-white dark:bg-primary text-primary dark:text-white shadow-sm').addClass('text-gray-600 dark:text-gray-400 hover:bg-white');
                    $('.afi-align-btn[data-value="' + s.text_alignment + '"]').removeClass('text-gray-600 dark:text-gray-400 hover:bg-white').addClass('bg-white dark:bg-primary text-primary dark:text-white shadow-sm');
                }

                // Margins (Unlink first to allow individual)
                // Actually if specific padding set, we unlink.
                // Margins (Unlink first to allow individual)
                // Actually if specific padding set, we unlink.
                if (s.padding_top !== undefined || s.padding_left !== undefined) {
                    // Temporarily disable margin linking to apply individual values
                    isMarginsLinked = false;
                    isMarginsLinked = false;
                    $('#afi-link-margins').removeClass('active');


                    // Assume complex padding means unlink
                    // Or just set values. The linker logic checks if values differ.
                    if (s.padding_top !== undefined) $('#afi_padding_top').val(s.padding_top).trigger('input');
                    if (s.padding_right !== undefined) $('#afi_padding_right').val(s.padding_right).trigger('input');
                    if (s.padding_bottom !== undefined) $('#afi_padding_bottom').val(s.padding_bottom).trigger('input');
                    if (s.padding_left !== undefined) $('#afi_padding_left').val(s.padding_left).trigger('input');
                } else {
                    // If no specific padding, ensure we reset to linked default state?
                    // We already reset inputs to 60 above. 
                    // We should arguably re-link if it was unlinked?
                    // For now, let's keep user state or reset. Line 341 set values to 60 but didn't touch link state.
                    // Let's force link if strict defaults.
                    isMarginsLinked = true;
                    isMarginsLinked = true;
                    $('#afi-link-margins').addClass('active');
                }

                // Logo
                // Logo - Only apply if logo_position is explicitly set in the template
                if (s.logo_position) {
                    $('input[name="cafi_settings[logo_position]"][value="' + s.logo_position + '"]').prop('checked', true).trigger('change');

                    // Auto-Restore Default Logo if None is Set
                    var currentLogoUrl = $('#afi_logo_url').val();
                    if (!currentLogoUrl) {
                        var defaultLogo = $('#afi-reset-logo-btn').data('default');
                        if (defaultLogo) {
                            $('#afi_logo_url').val(defaultLogo).trigger('change');
                            $('#afi-logo-preview').html('<img src="' + defaultLogo + '" class="max-w-full max-h-full object-contain">');
                            $('#afi-remove-logo-btn').removeClass('hidden');
                        }
                    }
                } else {
                    // If NO logo position is defined in the template config (e.g. tech_06),
                    // We assume this template should NOT show a logo.
                    // We can simulate this by clearing the logo URL input (visually) or just hiding the overlay.
                    // To be safe and "preview" correctly, let's Temporarily clear the logo URL from the input
                    // so the updatePreview function hides it.
                    // However, we don't want to destroy the user's uploaded logo data permanently if they switch back.
                    // Better approach: updatePreview checks a flag? OR we just clear the input and user re-selects?
                    // User said: "J template gulan a logo r kno information thakbe na osob a logo dekhabe na live priview eu and generate o korba na"

                    // So we force the input empty to verify "no logo".
                    $('#afi_logo_url').val('').trigger('change');
                    $('#afi-logo-preview').html('<span class="material-symbols-outlined text-gray-400">no_photography</span>');
                }

                if (s.logo_offset_x !== undefined) $('#afi_logo_offset_x').val(s.logo_offset_x).trigger('input');
                if (s.logo_offset_y !== undefined) $('#afi_logo_offset_y').val(s.logo_offset_y).trigger('input');

            } catch (e) {
                console.error("Error parsing template settings", e);
            }
        }

        // Update Preview Background
        if (tmplType === 'color') {
            $('#afi-preview-element').css('background-image', 'none').css('background-color', tmplValue);
            $('#afi-preview-mini-thumb').css('background-image', 'none').css('background-color', tmplValue);
        } else if (tmplType === 'gradient') {
            var parts = tmplValue.split(',');
            if (parts.length >= 3) {
                var dir = parts[parts.length - 1].trim();
                var cssDir = (dir === 'vertical') ? 'to bottom' : 'to right';
                var colors = parts.slice(0, parts.length - 1).join(', ');
                var gradientCss = 'linear-gradient(' + cssDir + ', ' + colors + ')';

                $('#afi-preview-element').css('background-color', '').css('background-image', gradientCss);
                $('#afi-preview-mini-thumb').css('background-color', '').css('background-image', gradientCss);
            }
        } else {
            $('#afi-preview-element').css('background-color', '').css('background-image', 'url("' + tmplValue + '")');
            $('#afi-preview-mini-thumb').css('background-color', '').css('background-image', 'url("' + tmplValue + '")');
        }

        $('#afi-preview-template-name').text(templateName);
        $('#afi-preview-template-name-2').text(templateName);

        // Update Hidden Input for Form Submission
        $('#afi_selected_template').val(tmplId);

        // Feedback
        console.log("Selected Template: " + templateName + " (" + tmplType + ")");

        updatePreview();
    });

    // --- Save Settings ---
    $('#afi-save-settings').on('click', function (e) {
        e.preventDefault();
        var $btn = $(this);
        $btn.text('Saving...');

        // Trigger native form submission
        $('form#afi-main-form').submit();
    });

    // --- Color Picker (Pickr) ---
    var pickr = null;
    if (typeof Pickr !== 'undefined') {
        pickr = Pickr.create({
            el: '.afi-color-picker',
            theme: 'classic',
            default: $('#afi_font_color').val(),
            comparison: false,
            components: {
                preview: true,
                opacity: true,
                hue: true,
                interaction: {
                    hex: true,
                    input: true,
                    save: true
                }
            }
        });

        // Event: Picker Change -> Update Inputs & UI
        pickr.on('change', (color, source, instance) => {
            const hexColor = color.toHEXA().toString(); // Use HEX as default

            // Update Hidden Input (Form) - Always
            $('#afi_font_color').val(hexColor).trigger('change');

            // Update Visual Text Input - ONLY IF USER IS NOT TYPING IN IT
            // This prevents the "fighting" / deleting characters issue
            if (!$("#afi_font_color_text").is(":focus")) {
                $('#afi_font_color_text').val(hexColor);
            }

            // Update Swatch Bg
            $('#afi-color-swatch-preview').css('background-color', hexColor);

            // Update Live Preview
            updatePreview();
        });

        // Trigger: Click Swatch -> Show Picker
        $('#afi-color-swatch-container').on('click', function () {
            pickr.show();
        });

        // Trigger: Type in Text Input -> Update Picker
        $('#afi_font_color_text').on('input', function () {
            var val = $(this).val();
            if (val.startsWith('#') && (val.length === 4 || val.length === 7)) {
                pickr.setColor(val);
                $('#afi-color-swatch-preview').css('background-color', val);
                $('#afi_font_color').val(val).trigger('change');
            }
        });

        // Ensure initial sync
        pickr.setColor($('#afi_font_color').val());
    }

    // --- New Typography UI Logic ---

    // Position Buttons
    $('.afi-pos-btn').not('.afi-align-btn').on('click', function () {
        var val = $(this).data('value');
        $('#afi_text_position').val(val).trigger('change');

        $('.afi-pos-btn').not('.afi-align-btn').removeClass('active');
        $(this).addClass('active');
    });

    // Alignment Buttons
    $('.afi-align-btn').on('click', function () {
        var val = $(this).data('value');
        $('#afi_text_alignment').val(val).trigger('change');

        $('.afi-align-btn').removeClass('active');
        $(this).addClass('active');
    });

    // Reset Defaults (Global Reset)
    $('#afi-reset-defaults').on('click', function () {
        if (!confirm('Are you sure you want to reset ALL settings to defaults (Typography, Margins, Colors, and Logo)?')) return;

        // --- Typography ---
        $('#afi_font_size').val(60);
        $('#afi_font_family').val('Inter');
        $('#afi_font_weight').val('Bold');

        // Reset Padding Intputs to 60
        // Update classes manually
        $('.afi-margin-input').val(60);
        isMarginsLinked = true;
        $('#afi-link-margins').addClass('active');

        // Position & Alignment
        $('#afi_text_position').val('middle');
        $('#afi_text_alignment').val('center');

        // Update classes manually
        $('.afi-pos-btn').not('.afi-align-btn').removeClass('active');
        $('.afi-pos-btn[data-value="middle"]').not('.afi-align-btn').addClass('active');

        $('.afi-align-btn').removeClass('active');
        $('.afi-align-btn[data-value="center"]').addClass('active');



        // Reset Color
        $('#afi_font_color').val('#000000').trigger('change');
        if (typeof Pickr !== 'undefined') {
            // Assuming pickr is global or accessible, but logic suggests it was in init() scope?
            // Wait, step 506 view shows pickr is defined inside init() but this handler is inside init(). So 'pickr' var should be available if scope allows. 
            // Line 367 shows 'var pickr = ...'. If this handler is inside that scope, good.
            // Line 438 is inside `jQuery(document).ready...`. `pickr` is defined line 367. So yes.
            // Wait, Step 506 view says `if (typeof Pickr !== 'undefined')` which checks class existence. 
            // But existing code checked `pickr` instance?
            // Existing code (lines 466-468) used `$('#afi_font_color_text').val('#000000').trigger('input');` which updates pickr via listener.
            $('#afi_font_color_text').val('#000000').trigger('input');
        }

        // --- Logo Settings ---
        // Restore Default URL (using the button's data if available, or finding the restore button to get data)
        var defaultUrl = $('#afi-reset-logo-btn').data('default'); // Reuse data from the other button
        if (defaultUrl) {
            $('#afi_logo_id').val('');
            $('#afi_logo_url').val(defaultUrl).trigger('change');
            $('#afi-logo-preview').html('<img src="' + defaultUrl + '" class="max-w-full max-h-full object-contain">');
            $('#afi-remove-logo-btn').removeClass('hidden');
        }

        // Reset Logo Size/Pos
        $('#afi_logo_size').val(25).trigger('input');
        $('#afi_logo_size_display').text('25%');

        $('#afi_logo_offset_x').val(20).trigger('input');
        $('#afi_logo_offset_y').val(20).trigger('input');
        // Reset Radio Button for Logo Position
        $('input[name="cafi_settings[logo_position]"][value="bottom-right"]').prop('checked', true).trigger('change');

        // Trigger font change for validation reset
        $('#afi_font_family').trigger('change');

        updatePreview();
    });

    // --- Media Uploader ---
    var originalSendAttachment = wp.media.editor.send.attachment;

    $('#afi-upload-logo-btn').on('click', function (e) {
        e.preventDefault();

        var uploader = wp.media({
            title: 'Select Logo',
            button: {
                text: 'Use this logo'
            },
            multiple: false
        })
            .on('select', function () {
                var attachment = uploader.state().get('selection').first().toJSON();

                // Update Inputs
                $('#afi_logo_id').val(attachment.id);
                $('#afi_logo_url').val(attachment.url).trigger('change'); // Trigger change for preview

                // Update UI
                $('#afi-logo-preview').html('<img src="' + attachment.url + '" class="max-w-full max-h-full object-contain">');
                $('#afi-remove-logo-btn').removeClass('hidden');

                updatePreview();
            })
            .open();
        updatePreview();
    });

    // --- Save Template Config Logic ---


    $('#afi-remove-logo-btn').on('click', function () {
        $('#afi_logo_id').val('');
        $('#afi_logo_url').val('').trigger('change');

        $('#afi-logo-preview').html('<span class="material-symbols-outlined text-gray-400">image</span>');
        $(this).addClass('hidden');

        updatePreview();
    });

    // Reset Logo Logic (Comprehensive)
    $('#afi-reset-logo-btn').on('click', function (e) {
        e.preventDefault();
        if (!confirm('Reset Logo Size and Position to defaults?')) return;

        var defaultUrl = $(this).data('default');
        $('#afi_logo_id').val('');
        $('#afi_logo_url').val(defaultUrl).trigger('change');
        $('#afi-logo-preview').html('<img src="' + defaultUrl + '" class="max-w-full max-h-full object-contain">');
        $('#afi-remove-logo-btn').removeClass('hidden');

        // Reset Size & Position
        $('#afi_logo_size').val(25).trigger('input'); // Default 25%
        $('#afi_logo_size_display').text('25%');

        $('#afi_logo_offset_x').val(20).trigger('input');
        $('#afi_logo_offset_y').val(20).trigger('input');
        $('input[name="cafi_settings[logo_position]"][value="bottom-right"]').prop('checked', true).trigger('change');

        updatePreview();
    });

    // Reset Typography (Fonts & Margins)
    $('#afi-reset-typography-btn').on('click', function (e) {
        e.preventDefault();
        if (!confirm('Reset Fonts and Margins to defaults?')) return;

        // Font Defaults
        $('#afi_font_size').val(40).trigger('input');
        $('#afi_font_family').val('Inter').trigger('change');
        $('#afi_font_weight').val('Bold').trigger('change');
        $('#afi_font_color').val('#000000').trigger('change');
        if (typeof pickr !== 'undefined') pickr.setColor('#000000');
        $('#afi_font_color_text').val('#000000');

        // Margin Defaults
        $('.afi-margin-input').val(60).trigger('input');

        // Reset Alignment/Position
        $('#afi_text_alignment').val('center');
        $('.afi-align-btn').removeClass('bg-white dark:bg-primary text-primary dark:text-white shadow-sm').addClass('text-gray-600 dark:text-gray-400 hover:bg-white');
        $('.afi-align-btn[data-value="center"]').removeClass('text-gray-600 dark:text-gray-400 hover:bg-white').addClass('bg-white dark:bg-primary text-primary dark:text-white shadow-sm');

        updatePreview();
    });

    // Initialize
    updatePreview();

});
