document.addEventListener('DOMContentLoaded', () => {
    // Style hook for page-level targeting
    document.body.classList.add('mdxcsp-admin');

    const form = document.getElementById('mdxcsp-settings-form');
    const grid = document.getElementById('mdxcsp-templates-grid');
    const cards = grid ? Array.from(grid.querySelectorAll('.mdxcsp-template-card')) : [];
    const loadMoreBtn = document.getElementById('mdxcsp-load-more');
    const optionWrap = document.getElementById('mdxcsp-template-options-wrap');
    const optionSections = optionWrap ? Array.from(optionWrap.querySelectorAll('.mdxcsp-template-options')) : [];
    const templateRadios = grid ? Array.from(grid.querySelectorAll('input[name="mdxcsp_selected_template"]')) : [];

    // Sticky bar live region for better a11y announcements
    const stickyText = document.querySelector('.mdxcsp-sticky-text');
    if (stickyText && !stickyText.getAttribute('aria-live')) {
        stickyText.setAttribute('aria-live', 'polite');
    }

    // Flags
    const AUTO_SCROLL_TO_OPTIONS = false;  // keep user where they are

    // Dirty state helper (drives blue line + dot)
    const markDirty = () => document.body.classList.add('mdxcsp-dirty');

    // REQUIRED FIELD VALIDATION FUNCTIONS
    const validateRequiredFields = () => {
        // Clear previous error states
        clearValidationErrors();

        const selectedTemplate = document.querySelector('input[name="mdxcsp_selected_template"]:checked')?.value || 'template-1';
        const activeSection = document.querySelector(`.mdxcsp-template-options[data-template="${selectedTemplate}"]`);

        if (!activeSection) return true;

        const requiredLabels = activeSection.querySelectorAll('.mdxcsp-required-label');
        let isValid = true;
        let firstInvalidField = null;

        requiredLabels.forEach(requiredLabel => {
            const fieldContainer = requiredLabel.closest('tr') || requiredLabel.closest('.mdxcsp-field-wrapper') || requiredLabel.closest('.mdxcsp-menu-item') || requiredLabel.closest('.mdxcsp-image-field') || requiredLabel.parentElement;

            if (!fieldContainer) return;

            // Check if this field is empty based on its type
            const isEmpty = isFieldEmpty(fieldContainer, activeSection);

            if (isEmpty) {
                isValid = false;
                fieldContainer.classList.add('mdxcsp-field-error');

                // Add error message if not exists
                if (!fieldContainer.querySelector('.mdxcsp-error-message')) {
                    const errorMsg = document.createElement('div');
                    errorMsg.className = 'mdxcsp-error-message';
                    errorMsg.textContent = 'This field is required';
                    errorMsg.style.color = '#d63638';
                    errorMsg.style.fontSize = '12px';
                    errorMsg.style.marginTop = '4px';
                    fieldContainer.appendChild(errorMsg);
                }

                // Store first invalid field for focus (only if it's a focusable element and we haven't found one yet)
                if (!firstInvalidField) {
                    const focusableField = getFocusableField(fieldContainer);
                    if (focusableField) {
                        firstInvalidField = focusableField;
                    }
                }
            }
        });

        if (!isValid && firstInvalidField) {
            // Scroll to and focus the first invalid field
            setTimeout(() => {
                firstInvalidField.scrollIntoView({behavior: 'smooth', block: 'center'});
                setTimeout(() => {
                    firstInvalidField.focus();
                }, 300);
            }, 100);

            return false;
        }

        return true;
    };

    const isFieldEmpty = (fieldContainer, activeSection) => {
        // Menu items - check only the name field (not URL)
        if (fieldContainer.closest('.mdxcsp-menu-item')) {
            const nameInput = fieldContainer.querySelector('input[type="text"]:not(.mdxcsp-color-picker)');
            // For menu items, only validate the name field, URL can be empty
            return nameInput ? !nameInput.value.trim() : true;
        }

        // Image fields (logo, background, social icons, menu toggle)
        if (fieldContainer.closest('.mdxcsp-image-field')) {
            const hiddenInput = fieldContainer.querySelector('input[type="hidden"]');
            // Check if image is selected (value should be > 0)
            return hiddenInput ? parseInt(hiddenInput.value) === 0 : true;
        }

        // Background mode section
        if (fieldContainer.querySelector('input[data-role="bg-mode"]')) {
            const bgMode = activeSection.querySelector('input[name*="[bg_mode]"]:checked')?.value || 'image';
            if (bgMode === 'image') {
                const bgInput = activeSection.querySelector('input[name*="[bg_id]"]');
                return bgInput ? parseInt(bgInput.value) === 0 : true;
            } else if (bgMode === 'color') {
                const colorInput = activeSection.querySelector('input[name*="[bg_color]"]');
                return colorInput ? !colorInput.value.trim() : true;
            }
            return true;
        }

        // Social URL fields
        if (fieldContainer.querySelector('input[name*="[social_"]') && fieldContainer.querySelector('input[type="text"]')) {
            const urlInput = fieldContainer.querySelector('input[type="text"]');
            return urlInput ? !urlInput.value.trim() : true;
        }

        // Regular text fields (title, subtitle, copyright, menu toggle label, etc.)
        const textInput = fieldContainer.querySelector('input[type="text"], input[type="datetime-local"], textarea');
        if (textInput) {
            return !textInput.value.trim();
        }

        // Default to not empty if we can't determine
        return false;
    };

    const getFocusableField = (fieldContainer) => {
        // Try to find a focusable input field
        const inputs = fieldContainer.querySelectorAll('input[type="text"], input[type="datetime-local"], textarea, input.mdxcsp-color-picker');
        for (let input of inputs) {
            if (input.offsetParent !== null && !input.disabled) {
                return input;
            }
        }

        // For image fields, find the upload button
        const uploadBtn = fieldContainer.querySelector('.mdxcsp-upload');
        if (uploadBtn && uploadBtn.offsetParent !== null && !uploadBtn.disabled) {
            return uploadBtn;
        }

        // For background mode, find the first radio button
        const radioBtn = fieldContainer.querySelector('input[type="radio"]');
        if (radioBtn && radioBtn.offsetParent !== null && !radioBtn.disabled) {
            return radioBtn;
        }

        return null;
    };

    const clearValidationErrors = () => {
        const errorFields = document.querySelectorAll('.mdxcsp-field-error');
        errorFields.forEach(field => {
            field.classList.remove('mdxcsp-field-error');
            const errorMsg = field.querySelector('.mdxcsp-error-message');
            if (errorMsg) {
                errorMsg.remove();
            }
        });
    };

    const clearFieldError = (field) => {
        const fieldContainer = field.closest('tr') || field.closest('.mdxcsp-field-wrapper') || field.closest('.mdxcsp-menu-item') || field.closest('.mdxcsp-image-field') || field.parentElement;
        if (fieldContainer) {
            fieldContainer.classList.remove('mdxcsp-field-error');
            const errorMsg = fieldContainer.querySelector('.mdxcsp-error-message');
            if (errorMsg) {
                errorMsg.remove();
            }
        }
    };

    // Real-time validation as user types/fills fields
    const setupRealTimeValidation = (section) => {
        if (!section) return;

        // Text inputs
        const textInputs = section.querySelectorAll('input[type="text"], textarea, input[type="datetime-local"]');
        textInputs.forEach(input => {
            input.addEventListener('input', function () {
                clearFieldError(this);
                markDirty();
            });

            input.addEventListener('change', function () {
                clearFieldError(this);
                markDirty();
            });
        });

        // Color pickers
        const colorPickers = section.querySelectorAll('.mdxcsp-color-picker');
        colorPickers.forEach(picker => {
            // Color picker validation is handled in initColorPickers
        });

        // Background mode changes
        const bgModeRadios = section.querySelectorAll('input[data-role="bg-mode"]');
        bgModeRadios.forEach(radio => {
            radio.addEventListener('change', function () {
                const section = this.closest('.mdxcsp-template-options');
                const bgImageField = section.querySelector('.mdxcsp-bg-image-controls');
                const bgColorField = section.querySelector('.mdxcsp-bg-color-controls');
                if (bgImageField) clearFieldError(bgImageField);
                if (bgColorField) clearFieldError(bgColorField);
                markDirty();
            });
        });
    };

    // Robust WP color picker init (for any .mdxcsp-color-picker)
    const initColorPickers = (scope = document) => {
        if (!(window.jQuery && jQuery.fn.wpColorPicker)) return;
        jQuery(scope).find('input.mdxcsp-color-picker').each(function () {
            const $input = jQuery(this);

            // already initialized?
            if ($input.closest('.wp-picker-container').length) return;

            // init
            $input.wpColorPicker({
                change: function () {
                    markDirty();
                    clearFieldError(this);
                },
                clear: function () {
                    markDirty();
                    clearFieldError(this);
                }
            });
        });

        // Fallback safety re-init shortly after DOM load (in case of late renders)
        setTimeout(() => {
            jQuery(scope).find('input.mdxcsp-color-picker').each(function () {
                const $input = jQuery(this);
                if ($input.closest('.wp-picker-container').length) return;
                $input.wpColorPicker({
                    change: function () {
                        markDirty();
                        clearFieldError(this);
                    },
                    clear: function () {
                        markDirty();
                        clearFieldError(this);
                    }
                });
            });
        }, 200);
    };

    // Update selected card visuals + ARIA
    const updateSelectedCard = () => {
        cards.forEach((card) => {
            const radio = card.querySelector('input[type="radio"]');
            const checked = !!(radio && radio.checked);
            card.classList.toggle('is-selected', checked);

            // a11y roles and states
            card.setAttribute('role', 'radio');
            card.setAttribute('aria-checked', String(checked));
            if (!card.hasAttribute('tabindex')) {
                card.setAttribute('tabindex', '0');
            }
            const titleEl = card.querySelector('.mdxcsp-template-title');
            if (titleEl && !card.getAttribute('aria-label')) {
                card.setAttribute('aria-label', titleEl.textContent.trim());
            }
        });
    };

    // Make the grid a radio group for better a11y
    if (grid) {
        grid.setAttribute('role', 'radiogroup');
        if (!grid.getAttribute('aria-label')) {
            grid.setAttribute('aria-label', 'Select a Template');
        }
    }

    // Keyboard support for cards (Enter/Space to select)
    cards.forEach((card) => {
        card.addEventListener('keydown', (e) => {
            const key = e.key || e.code;
            if (key === 'Enter' || key === ' ' || key === 'Spacebar') {
                const radio = card.querySelector('input[type="radio"]');
                if (radio && !radio.checked) {
                    e.preventDefault();
                    radio.checked = true;
                    radio.dispatchEvent(new Event('change', {bubbles: true}));
                    card.focus();
                }
            }
        });
    });

    // Load more for template cards (with Show Less) — robust FLIP
    if (!cards.length) {
        if (loadMoreBtn) loadMoreBtn.style.display = 'none';
    } else {
        const step = 3;
        let visibleCount = Math.min(step, cards.length);

        // initial: show first 3 explicitly as flex (prevents layout glitches)
        cards.forEach((card, idx) => {
            card.style.display = idx < visibleCount ? 'flex' : 'none';
        });

        if (loadMoreBtn) {
            loadMoreBtn.setAttribute('aria-controls', 'mdxcsp-templates-grid');
            loadMoreBtn.setAttribute('aria-expanded', String(visibleCount >= cards.length ? true : false));

            if (visibleCount >= cards.length) loadMoreBtn.style.display = 'none';

            let showLessBtn = document.getElementById('mdxcsp-show-less');
            if (!showLessBtn) {
                showLessBtn = document.createElement('button');
                showLessBtn.type = 'button';
                showLessBtn.id = 'mdxcsp-show-less';
                showLessBtn.className = 'button button-secondary';
                showLessBtn.textContent = 'Show Less';
                showLessBtn.setAttribute('aria-controls', 'mdxcsp-templates-grid');
                showLessBtn.style.display = 'none';
                (loadMoreBtn || grid).insertAdjacentElement('afterend', showLessBtn);
            }

            const reveal = (els) => {
                els.forEach((el, i) => {
                    el.classList.remove('is-revealed');
                    void el.offsetWidth;
                    el.style.animationDelay = (i * 60) + 'ms';
                    el.classList.add('is-revealed');
                });
                setTimeout(() => {
                    els.forEach((el) => {
                        el.style.animationDelay = '';
                    });
                }, 800);
            };

            loadMoreBtn.addEventListener('click', () => {
                loadMoreBtn.classList.add('is-busy');

                const prevVisible = visibleCount;
                const nextCount = cards.length;
                for (let i = visibleCount; i < nextCount; i++) {
                    cards[i].style.display = 'flex';
                }
                visibleCount = nextCount;

                loadMoreBtn.setAttribute('aria-expanded', 'true');
                if (visibleCount >= cards.length) {
                    loadMoreBtn.style.display = 'none';
                    showLessBtn.style.display = '';
                    setTimeout(() => showLessBtn.focus(), 0);
                }

                const newlyShown = cards.slice(prevVisible, visibleCount);
                if (newlyShown.length) {
                    reveal(newlyShown);
                    if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
                        newlyShown[0].scrollIntoView({behavior: 'smooth', block: 'nearest'});
                    }
                }

                setTimeout(() => loadMoreBtn.classList.remove('is-busy'), 300);
            });

            // Show Less: robust FLIP + fallback
            showLessBtn.addEventListener('click', () => {
                const newCount = Math.min(step, cards.length);
                showLessBtn.classList.add('is-busy');
                const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

                const startHeight = grid.getBoundingClientRect().height;
                grid.style.height = startHeight + 'px';
                grid.classList.add('is-animating');
                void grid.offsetHeight;

                for (let i = newCount; i < cards.length; i++) {
                    cards[i].style.display = 'none';
                    cards[i].classList.remove('is-revealed');
                }
                visibleCount = newCount;

                loadMoreBtn.style.display = (visibleCount < cards.length) ? '' : 'none';
                showLessBtn.style.display = 'none';
                loadMoreBtn.setAttribute('aria-expanded', 'false');

                if (!prefersReduced) {
                    requestAnimationFrame(() => {
                        const endHeight = grid.getBoundingClientRect().height;
                        grid.style.height = endHeight + 'px';

                        const cleanUp = () => {
                            grid.style.height = '';
                            grid.classList.remove('is-animating');
                            showLessBtn.classList.remove('is-busy');
                        };

                        let finished = false;
                        const onEnd = (e) => {
                            if (e && e.propertyName && e.propertyName !== 'height') return;
                            finished = true;
                            cleanUp();
                            grid.removeEventListener('transitionend', onEnd);
                            grid.removeEventListener('transitioncancel', onEnd);
                        };
                        grid.addEventListener('transitionend', onEnd, {once: true});
                        grid.addEventListener('transitioncancel', onEnd, {once: true});

                        setTimeout(() => {
                            if (!finished) cleanUp();
                        }, 400);
                    });
                } else {
                    grid.style.height = '';
                    grid.classList.remove('is-animating');
                    showLessBtn.classList.remove('is-busy');
                }

                if (!window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
                    grid.scrollIntoView({behavior: 'smooth', block: 'start'});
                }
                if (loadMoreBtn.style.display !== 'none') {
                    loadMoreBtn.focus();
                }
            });
        }
    }

    // Toggle background mode (image vs color) per section
    const updateBgModeForSection = (sec) => {
        const radios = Array.from(sec.querySelectorAll('input[type="radio"][data-role="bg-mode"]'));
        if (!radios.length) return;

        const current = radios.find(r => r.checked);
        const mode = current ? current.value : 'image';

        const imgWrap = sec.querySelector('.mdxcsp-bg-image-controls');
        const colorWrap = sec.querySelector('.mdxcsp-bg-color-controls');

        if (imgWrap) {
            imgWrap.style.display = mode === 'image' ? '' : 'none';
            imgWrap.setAttribute('aria-hidden', mode === 'image' ? 'false' : 'true');
            Array.from(imgWrap.querySelectorAll('input,button,select,textarea')).forEach(el => {
                if (!el.matches('input[type="radio"][data-role="bg-mode"]')) {
                    el.disabled = mode !== 'image';
                }
            });
        }

        if (colorWrap) {
            colorWrap.style.display = mode === 'color' ? '' : 'none';
            colorWrap.setAttribute('aria-hidden', mode === 'color' ? 'false' : 'true');
            Array.from(colorWrap.querySelectorAll('input,button,select,textarea')).forEach(el => {
                el.disabled = mode !== 'color';
            });
        }
    };

    // Keep all accordions open
    const lockAccordionsOpen = () => {
        const details = document.querySelectorAll('.mdxcsp-acc');
        details.forEach(d => {
            d.setAttribute('open', '');
            d.classList.add('mdxcsp-acc-locked');
        });
    };

    // Utils
    const cssEscape = (s) => (window.CSS && CSS.escape) ? CSS.escape(s) : String(s).replace(/([^\w-])/g, '\\$1');
    const isVisible = (el) => !!el && el.offsetParent !== null && window.getComputedStyle(el).display !== 'none';

    // FIXED MENU ITEMS FUNCTIONALITY
    const setupMenuItems = (sec) => {
        if (!sec || sec.dataset.menuEnhanced === '1') return;

        const menuContainer = sec.querySelector('.mdxcsp-menu-items-container');
        if (!menuContainer) return;

        // Get all menu items
        const menuItems = Array.from(menuContainer.querySelectorAll('.mdxcsp-menu-item'));
        const addButton = sec.querySelector('.mdxcsp-add-menu-btn');

        if (!addButton) return;

        // Initialize: show only first item, hide others
        menuItems.forEach((item, index) => {
            if (index === 0) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
                item.classList.add('mdxcsp-menu-item-hidden');
            }
        });

        // Update add button state
        const updateAddButton = () => {
            const visibleItems = menuItems.filter(item => item.style.display !== 'none');
            if (visibleItems.length >= 10) {
                addButton.style.display = 'none';
            } else {
                addButton.style.display = '';
            }
        };

        // Add remove button functionality to all items except first
        menuItems.forEach((item, index) => {
            if (index > 0) {
                const removeBtn = item.querySelector('.mdxcsp-remove-menu-item');
                if (removeBtn) {
                    removeBtn.addEventListener('click', () => {
                        // Clear the values
                        const inputs = item.querySelectorAll('input');
                        inputs.forEach(input => {
                            if (input.type !== 'button' && input.type !== 'submit') {
                                input.value = '';
                            }
                        });

                        // Hide the item
                        item.style.display = 'none';
                        item.classList.add('mdxcsp-menu-item-hidden');

                        // Update add button
                        updateAddButton();
                        markDirty();
                    });
                }
            }
        });

        // Add button functionality
        addButton.addEventListener('click', () => {
            const hiddenItems = menuItems.filter(item =>
                item.style.display === 'none' && item.classList.contains('mdxcsp-menu-item-hidden')
            );

            if (hiddenItems.length > 0) {
                // Show the next hidden item
                const nextItem = hiddenItems[0];
                nextItem.style.display = 'block';
                nextItem.classList.remove('mdxcsp-menu-item-hidden');

                // Focus on the first input
                const firstInput = nextItem.querySelector('input[type="text"]');
                if (firstInput) {
                    setTimeout(() => firstInput.focus(), 100);
                }

                updateAddButton();
                markDirty();
            }
        });

        // Initialize button state
        updateAddButton();

        sec.dataset.menuEnhanced = '1';
    };

    // DATETIME-LOCAL: default time to 00:00 (12 AM) when date changes or partial input occurs
    const attachDatetimeDefaults = (sec) => {
        const inputs = Array.from(sec.querySelectorAll('input[type="datetime-local"]'));
        inputs.forEach((dt) => {
            const setDefaultTime = () => {
                const v = String(dt.value || '').trim();
                if (!v) return;
                const parts = v.split('T');
                if (parts.length === 1) {
                    dt.value = parts[0] + 'T00:00';
                    return;
                }
                const [date, time] = parts;
                if (!time || !/^\d{2}:\d{2}$/.test(time)) {
                    dt.value = date + 'T00:00';
                }
            };
            dt.addEventListener('focus', () => {
                dt.dataset.prevValue = dt.value || '';
            }, {passive: true});
            dt.addEventListener('change', () => {
                const prev = dt.dataset.prevValue || '';
                const pv = prev.split('T');
                const nv = String(dt.value || '').split('T');
                const prevDate = pv[0] || '';
                const prevTime = pv[1] || '';
                const newDate = nv[0] || '';
                const newTime = nv[1] || '';
                if (newDate && newDate !== prevDate && (!newTime || newTime === prevTime)) {
                    dt.value = newDate + 'T00:00';
                } else {
                    setDefaultTime();
                }
                markDirty();
                clearFieldError(dt);
            });
            dt.addEventListener('input', () => {
                const v = String(dt.value || '').trim();
                if (/^\d{4}-\d{2}-\d{2}$/.test(v)) {
                    dt.value = v + 'T00:00';
                }
                clearFieldError(dt);
            }, {passive: true});
            dt.addEventListener('blur', setDefaultTime);
        });
    };

    // Progressive fields (Menu items + Social links) with Add/Remove
    const setupProgressiveFields = (sec) => {
        if (!sec || sec.dataset.progressiveReady === '1') return;

        // Setup menu items with new fixed functionality
        setupMenuItems(sec);

        // SOCIAL LINKS: show both 1 and 2 by default, allow removing/adding second
        const tkey = sec.dataset.template || '';
        const esc = cssEscape(tkey);

        const social1Id = sec.querySelector(`input[name="mdxcsp_template_settings[${esc}][social_1_id]"]`);
        if (social1Id) {
            const fieldset = social1Id.closest('fieldset');
            if (fieldset && !fieldset.dataset.socialEnhanced) {
                fieldset.dataset.socialEnhanced = '1';

                const iconPs = Array.from(fieldset.querySelectorAll('p')).filter(p =>
                    p.querySelector('input[name*="[social_1_id]"], input[name*="[social_1_url]"], input[name*="[social_2_id]"], input[name*="[social_2_url]"]')
                );

                const [p1, p2] = iconPs;
                if (p1) p1.style.display = '';
                if (p2) p2.style.display = ''; // visible by default

                // Add social button
                let addSocialBtn = fieldset.querySelector('.mdxcsp-add-social-btn');
                if (!addSocialBtn) {
                    addSocialBtn = document.createElement('button');
                    addSocialBtn.type = 'button';
                    addSocialBtn.className = 'button mdxcsp-add-btn mdxcsp-add-social-btn';
                    addSocialBtn.innerHTML = '<span class="mdxcsp-add-btn-icon">+</span> Add social link';
                    fieldset.appendChild(addSocialBtn);
                }

                const updateAddSocialBtn = () => {
                    if (!p2) {
                        addSocialBtn.style.display = 'none';
                        return;
                    }
                    addSocialBtn.style.display = p2.style.display === 'none' ? '' : 'none';
                };

                // Remove button for Social 2
                if (p2) {
                    const ensureRemoveButton = (p, onRemove) => {
                        if (!p) return;
                        let btn = p.querySelector('.mdxcsp-remove-row');
                        if (!btn) {
                            btn = document.createElement('button');
                            btn.type = 'button';
                            btn.className = 'button-link mdxcsp-remove-row';
                            btn.style.marginLeft = '8px';
                            btn.textContent = 'Remove';
                            p.appendChild(btn);
                            btn.addEventListener('click', (e) => {
                                e.preventDefault();
                                if (typeof onRemove === 'function') onRemove();
                                markDirty();
                            });
                        }
                    };

                    ensureRemoveButton(p2, () => {
                        const hid = p2.querySelector('input[name*="[social_2_id]"]');
                        const hul = p2.querySelector('input[name*="[social_2_url]"]');
                        if (hid) hid.value = '';
                        if (hul) hul.value = '';
                        p2.style.display = 'none';
                        updateAddSocialBtn();
                    });
                }

                updateAddSocialBtn();

                addSocialBtn.addEventListener('click', () => {
                    if (p2 && p2.style.display === 'none') {
                        p2.style.display = '';
                        const input = p2.querySelector('input[type="text"], input[type="url"]') || p2.querySelector('input');
                        if (input) input.focus();
                        markDirty();
                    }
                    updateAddSocialBtn();
                });
            }
        }

        // DATETIME default time behavior
        attachDatetimeDefaults(sec);

        // Init WP color pickers inside this section
        initColorPickers(sec);

        sec.dataset.progressiveReady = '1';
    };

    // Initialize all sections
    optionSections.forEach((sec) => {
        updateBgModeForSection(sec);
        const radios = Array.from(sec.querySelectorAll('input[type="radio"][data-role="bg-mode"]'));
        radios.forEach(radio => {
            radio.addEventListener('change', () => {
                updateBgModeForSection(sec);
                markDirty();
            });
        });

        setupProgressiveFields(sec);
        attachDatetimeDefaults(sec);
        initColorPickers(sec);
        setupRealTimeValidation(sec);
    });

    // Template selection -> show active options (stay in place; no jump)
    const setActiveTemplate = (tpl) => {
        optionSections.forEach((sec) => {
            const match = sec.dataset.template === tpl;
            sec.style.display = match ? '' : 'none';
            const inputs = Array.from(sec.querySelectorAll('input, textarea, select, button'));
            inputs.forEach((el) => {
                if (el.classList.contains('mdxcsp-upload') || el.classList.contains('mdxcsp-remove')) {
                    el.disabled = !match;
                } else {
                    el.disabled = !match;
                }
            });
            if (match) {
                updateBgModeForSection(sec);
                setupProgressiveFields(sec);
                attachDatetimeDefaults(sec);
                initColorPickers(sec);
                setupRealTimeValidation(sec);
            }
        });
    };

    // Initial selections
    const initialRadio = templateRadios.find((r) => r.checked) || null;
    const initialTpl = (initialRadio ? initialRadio.value : (window.mdxcspAdmin && mdxcspAdmin.selectedTemplate)) || 'template-1';
    if (optionSections.length) setActiveTemplate(initialTpl);
    updateSelectedCard();
    initColorPickers(document);

    // Template change handlers
    templateRadios.forEach((radio) => {
        radio.addEventListener('change', (e) => {
            setActiveTemplate(e.target.value);
            updateSelectedCard();
            if (AUTO_SCROLL_TO_OPTIONS && !window.matchMedia('(prefers-reduced-motion: reduce)').matches && optionWrap) {
                optionWrap.scrollIntoView({behavior: 'smooth', block: 'start'});
            }
            markDirty();
        });
    });

    // Media uploader handlers
    if (optionWrap && window.wp && wp.media) {
        optionWrap.addEventListener('click', (e) => {
            const uploadBtn = e.target.closest('.mdxcsp-upload');
            const removeBtn = e.target.closest('.mdxcsp-remove');

            if (uploadBtn) {
                e.preventDefault();
                const section = uploadBtn.closest('.mdxcsp-template-options');
                const target = uploadBtn.getAttribute('data-target');
                if (!section || !target) return;

                const input = section.querySelector(`input[name*="[${target}]"]`);
                const preview = section.querySelector(`.mdxcsp-image-preview[data-target="${target}"]`);

                const frame = wp.media({
                    title: (window.mdxcspAdmin && mdxcspAdmin.i18n && mdxcspAdmin.i18n.selectImage) || 'Select image',
                    button: {text: (window.mdxcspAdmin && mdxcspAdmin.i18n && mdxcspAdmin.i18n.useImage) || 'Use this image'},
                    library: {type: ['image']},
                    multiple: false
                });

                frame.on('select', () => {
                    const attachment = frame.state().get('selection').first().toJSON();
                    if (input) input.value = attachment.id;
                    if (preview) {
                        preview.src = attachment.url;
                        preview.style.display = '';
                    }
                    const remove = section.querySelector(`.mdxcsp-remove[data-target="${target}"]`);
                    if (remove) remove.disabled = false;
                    markDirty();

                    // Clear validation error for this image field
                    const imageField = uploadBtn.closest('.mdxcsp-image-field');
                    if (imageField) {
                        clearFieldError(imageField);
                    }
                });

                frame.open();
            }

            if (removeBtn) {
                e.preventDefault();
                const section = removeBtn.closest('.mdxcsp-template-options');
                const target = removeBtn.getAttribute('data-target');
                if (!section || !target) return;

                const input = section.querySelector(`input[name*="[${target}]"]`);
                const preview = section.querySelector(`.mdxcsp-image-preview[data-target="${target}"]`);
                if (input) input.value = '';
                if (preview) {
                    preview.src = '';
                    preview.style.display = 'none';
                }
                removeBtn.disabled = true;
                markDirty();
            }
        });
    }

    // Enhance the status toggle as an ARIA switch
    (() => {
        const toggleWrapper = document.querySelector('.mdxcsp-toggle-switch');
        const toggleInput = document.getElementById('mdxcsp_enable_coming_soon');
        if (toggleWrapper && toggleInput) {
            toggleWrapper.setAttribute('role', 'switch');
            toggleWrapper.setAttribute('aria-checked', String(!!toggleInput.checked));
            toggleWrapper.setAttribute('tabindex', '0');

            const reflect = () => toggleWrapper.setAttribute('aria-checked', String(!!toggleInput.checked));
            toggleInput.addEventListener('change', () => {
                reflect();
                markDirty();
            });

            toggleWrapper.addEventListener('keydown', (e) => {
                const key = e.key || e.code;
                if (key === 'Enter' || key === ' ' || key === 'Spacebar') {
                    e.preventDefault();
                    toggleInput.checked = !toggleInput.checked;
                    toggleInput.dispatchEvent(new Event('change', {bubbles: true}));
                }
            });
        }
    })();

    // Submit: with required field validation
    if (form) {
        form.addEventListener('input', markDirty, {passive: true});
        form.addEventListener('change', markDirty, {passive: true});

        form.addEventListener('submit', (e) => {
            // Validate required fields before submission
            if (!validateRequiredFields()) {
                e.preventDefault();
                return false;
            }

            document.body.classList.remove('mdxcsp-dirty');
        });
    }

    lockAccordionsOpen();
    updateSelectedCard();
});