/**
 * Options Page Builder - Admin JavaScript
 * Handles field management, drag & drop, and AJAX operations
 *
 * @package Switchboard
 * @since 1.0.0
 */

(function($) {
    'use strict';

    let fieldCounter = 0;
    let fieldsData = [];
    let currentPageId = null;
    let saveTimeout = null;
    let sortableInitialized = false;

    /**
     * Field type icons
     */
    const fieldIcons = {
        text: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M3 12h12M3 19h12"/>',
        textarea: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"/>',
        select: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l4-4 4 4m0 6l-4 4-4-4"/>',
        checkbox: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>',
        radio: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>',
        number: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"/>',
        email: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>',
        url: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/>',
        color: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01"/>',
        image: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>',
        wysiwyg: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>',
        date: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"/>',
        group: '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/>'
    };

    /**
     * Field type labels
     */
    const fieldLabels = {
        text: 'Text',
        textarea: 'Textarea',
        select: 'Select',
        checkbox: 'Checkbox',
        radio: 'Radio',
        number: 'Number',
        email: 'Email',
        url: 'URL',
        color: 'Color',
        image: 'Image',
        wysiwyg: 'WYSIWYG',
        date: 'Date',
        group: 'Group'
    };

    /**
     * Width labels
     */
    const widthLabels = {
        'full': 'Full',
        '2-3': '2/3',
        '1-2': '1/2',
        '1-3': '1/3'
    };

    /**
     * Get width label
     */
    function getWidthLabel(width) {
        return widthLabels[width] || width;
    }

    /**
     * Common dashicons for icon picker
     */
    const commonDashicons = [
        'dashicons-admin-generic',
        'dashicons-admin-settings',
        'dashicons-admin-tools',
        'dashicons-admin-site',
        'dashicons-admin-appearance',
        'dashicons-admin-plugins',
        'dashicons-admin-users',
        'dashicons-admin-post',
        'dashicons-admin-page',
        'dashicons-admin-media',
        'dashicons-admin-comments',
        'dashicons-admin-network',
        'dashicons-admin-home',
        'dashicons-admin-links',
        'dashicons-welcome-write-blog',
        'dashicons-format-aside',
        'dashicons-format-image',
        'dashicons-format-gallery',
        'dashicons-format-video',
        'dashicons-format-audio',
        'dashicons-format-chat',
        'dashicons-format-status',
        'dashicons-format-quote',
        'dashicons-calendar',
        'dashicons-calendar-alt',
        'dashicons-cart',
        'dashicons-products',
        'dashicons-store',
        'dashicons-money',
        'dashicons-money-alt',
        'dashicons-analytics',
        'dashicons-chart-bar',
        'dashicons-chart-pie',
        'dashicons-chart-line',
        'dashicons-chart-area',
        'dashicons-groups',
        'dashicons-businessman',
        'dashicons-building',
        'dashicons-location',
        'dashicons-location-alt',
        'dashicons-phone',
        'dashicons-email',
        'dashicons-email-alt',
        'dashicons-email-alt2',
        'dashicons-share',
        'dashicons-share-alt',
        'dashicons-share-alt2',
        'dashicons-twitter',
        'dashicons-facebook',
        'dashicons-facebook-alt',
        'dashicons-instagram',
        'dashicons-linkedin',
        'dashicons-pinterest',
        'dashicons-youtube',
        'dashicons-video-alt',
        'dashicons-video-alt2',
        'dashicons-video-alt3',
        'dashicons-camera',
        'dashicons-camera-alt',
        'dashicons-images-alt',
        'dashicons-images-alt2',
        'dashicons-portfolio',
        'dashicons-book',
        'dashicons-book-alt',
        'dashicons-download',
        'dashicons-upload',
        'dashicons-backup',
        'dashicons-cloud',
        'dashicons-cloud-saved',
        'dashicons-cloud-upload',
        'dashicons-lock',
        'dashicons-unlock',
        'dashicons-shield',
        'dashicons-shield-alt',
        'dashicons-awards',
        'dashicons-star-empty',
        'dashicons-star-filled',
        'dashicons-star-half',
        'dashicons-heart',
        'dashicons-thumbs-up',
        'dashicons-thumbs-down',
        'dashicons-smiley',
        'dashicons-flag',
        'dashicons-megaphone',
        'dashicons-bell',
        'dashicons-lightbulb',
        'dashicons-hammer',
        'dashicons-art',
        'dashicons-migrate',
        'dashicons-performance',
        'dashicons-universal-access',
        'dashicons-universal-access-alt',
        'dashicons-tickets',
        'dashicons-nametag',
        'dashicons-clipboard',
        'dashicons-pressthis',
        'dashicons-update',
        'dashicons-update-alt',
        'dashicons-screenoptions',
        'dashicons-info',
        'dashicons-info-outline',
        'dashicons-warning',
        'dashicons-yes',
        'dashicons-yes-alt',
        'dashicons-no',
        'dashicons-no-alt',
        'dashicons-plus',
        'dashicons-plus-alt',
        'dashicons-plus-alt2',
        'dashicons-minus',
        'dashicons-dismiss',
        'dashicons-marker',
        'dashicons-arrow-up',
        'dashicons-arrow-up-alt',
        'dashicons-arrow-up-alt2',
        'dashicons-arrow-down',
        'dashicons-arrow-down-alt',
        'dashicons-arrow-down-alt2',
        'dashicons-arrow-left',
        'dashicons-arrow-left-alt',
        'dashicons-arrow-left-alt2',
        'dashicons-arrow-right',
        'dashicons-arrow-right-alt',
        'dashicons-arrow-right-alt2',
        'dashicons-sort',
        'dashicons-list-view',
        'dashicons-exerpt-view',
        'dashicons-grid-view',
        'dashicons-move',
        'dashicons-editor-ul',
        'dashicons-editor-ol',
        'dashicons-editor-ol-rtl',
        'dashicons-editor-quote',
        'dashicons-editor-code',
        'dashicons-editor-table',
        'dashicons-align-left',
        'dashicons-align-right',
        'dashicons-align-center',
        'dashicons-align-none',
        'dashicons-editor-bold',
        'dashicons-editor-italic',
        'dashicons-editor-underline',
        'dashicons-editor-strikethrough',
        'dashicons-editor-justify',
        'dashicons-text-page',
        'dashicons-editor-textcolor',
        'dashicons-editor-paste-word',
        'dashicons-editor-paste-text',
        'dashicons-editor-removeformatting',
        'dashicons-editor-video',
        'dashicons-editor-customchar',
        'dashicons-editor-outdent',
        'dashicons-editor-indent',
        'dashicons-editor-help',
        'dashicons-editor-rtl',
        'dashicons-editor-break',
        'dashicons-editor-unlink',
        'dashicons-editor-insertmore',
        'dashicons-editor-spellcheck',
        'dashicons-editor-expand',
        'dashicons-editor-contract',
        'dashicons-editor-kitchensink',
        'dashicons-editor-ltr'
    ];

    /**
     * Show toast notification
     */
    function showToast(message, type = 'success') {
        // Remove any existing toast
        $('.opb-toast').remove();

        const iconSvg = type === 'success'
            ? '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg>'
            : '<svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>';

        const $toast = $(`
            <div class="opb-toast opb-toast-${type}">
                <span class="opb-toast-icon">${iconSvg}</span>
                <span class="opb-toast-message">${escapeHtml(message)}</span>
            </div>
        `);

        $('body').append($toast);

        // Trigger animation
        setTimeout(() => $toast.addClass('show'), 10);

        // Auto dismiss
        setTimeout(() => {
            $toast.removeClass('show');
            setTimeout(() => $toast.remove(), 300);
        }, 3000);
    }

    /**
     * Initialize on document ready
     */
    $(document).ready(function() {
        initEditPage();
        initQuickAdd();
        initFormHandlers();
        initParentMenuLogic();
        initAutoFill();
        initIconPicker();
    });

    /**
     * Initialize edit page
     */
    function initEditPage() {
        const $fieldsList = $('#opb-fields-list');
        if (!$fieldsList.length) return;

        // Get page ID from URL
        const urlParams = new URLSearchParams(window.location.search);
        currentPageId = urlParams.get('page_id');

        // Initialize sortable FIRST
        $fieldsList.sortable({
            handle: '.opb-field-drag',
            placeholder: 'opb-field-placeholder',
            axis: 'y',
            cursor: 'grabbing',
            tolerance: 'pointer',
            update: function() {
                updateFieldsOrder();
                autoSave();
            }
        });
        sortableInitialized = true;

        // Load existing fields AFTER sortable is initialized
        if (currentPageId && typeof switchboard_opb !== 'undefined') {
            loadExistingFields();
        }

        // Field collapse/expand - clicking header
        $(document).on('click', '.opb-field-header', function(e) {
            if ($(e.target).closest('.opb-field-action-btn').length) return;
            $(this).closest('.opb-field-item').toggleClass('collapsed');
        });

        // Field collapse/expand - clicking collapse button (arrow)
        $(document).on('click', '.opb-field-collapse', function(e) {
            e.stopPropagation();
            $(this).closest('.opb-field-item').toggleClass('collapsed');
        });

        // Delete field
        $(document).on('click', '.opb-field-delete', function(e) {
            e.stopPropagation();
            const $field = $(this).closest('.opb-field-item');
            const fieldLabel = $field.find('.opb-field-title').text();

            if (confirm('Are you sure you want to delete the "' + fieldLabel + '" field?')) {
                $field.fadeOut(300, function() {
                    $(this).remove();
                    // Refresh sortable after removing field
                    if (sortableInitialized) {
                        $('#opb-fields-list').sortable('refresh');
                    }
                    updateFieldsOrder();
                    autoSave();
                    checkEmptyState();
                });
            }
        });

        // Field input changes
        $(document).on('change keyup', '.opb-field-body input, .opb-field-body select, .opb-field-body textarea', function() {
            updateFieldData($(this).closest('.opb-field-item'));
            autoSave();
        });
    }

    /**
     * Initialize quick add buttons
     */
    function initQuickAdd() {
        $('.opb-quick-add-field').on('click', function() {
            const fieldType = $(this).data('type');
            addField(fieldType);
        });
    }

    /**
     * Initialize form handlers
     */
    function initFormHandlers() {
        const $form = $('#opb-form');
        if (!$form.length) return;

        // Save button
        $('#opb-save-page').on('click', function(e) {
            e.preventDefault();
            savePage();
        });

        // Delete button
        $('#opb-delete-page').on('click', function(e) {
            e.preventDefault();
            if (confirm('Are you sure you want to delete this options page? This action cannot be undone.')) {
                deletePage();
            }
        });

        // Auto-save on page settings change
        $form.find('input, select').not('.opb-field-body input, .opb-field-body select').on('change', function() {
            autoSave();
        });
    }

    /**
     * Initialize parent menu logic
     */
    function initParentMenuLogic() {
        const $parentMenu = $('#opb-parent-menu');
        const $iconPositionWrapper = $('#opb-icon-position-wrapper');

        if (!$parentMenu.length) return;

        $parentMenu.on('change', function() {
            const isTopLevel = $(this).val() === '';
            $iconPositionWrapper.toggle(isTopLevel);
        }).trigger('change');
    }

    /**
     * Initialize auto-fill for menu title and slug
     */
    function initAutoFill() {
        const $pageTitle = $('#opb-page-title');
        const $menuTitle = $('#opb-menu-title');
        const $menuSlug = $('#opb-menu-slug');

        if (!$pageTitle.length) return;

        // Track if user has manually edited these fields
        let menuTitleEdited = $menuTitle.val() !== '';
        let menuSlugEdited = $menuSlug.val() !== '' && !$menuSlug.prop('readonly');

        $menuTitle.on('input', function() {
            menuTitleEdited = true;
        });

        $menuSlug.on('input', function() {
            menuSlugEdited = true;
        });

        $pageTitle.on('input', function() {
            const value = $(this).val();

            // Auto-fill menu title if not manually edited
            if (!menuTitleEdited) {
                $menuTitle.val(value);
            }

            // Auto-fill menu slug if not manually edited and not readonly
            if (!menuSlugEdited && !$menuSlug.prop('readonly')) {
                const slug = value
                    .toLowerCase()
                    .replace(/[^a-z0-9\s-]/g, '')
                    .replace(/\s+/g, '-')
                    .replace(/-+/g, '-')
                    .replace(/^-|-$/g, '');
                $menuSlug.val(slug);
            }
        });
    }

    /**
     * Initialize icon picker
     */
    function initIconPicker() {
        const $iconInput = $('#opb-icon');

        if (!$iconInput.length) return;

        // Create icon picker elements
        const $pickerContainer = $('<div class="opb-icon-picker-container"></div>');
        const $pickerToggle = $('<button type="button" class="opb-icon-picker-toggle"><span class="dashicons ' + ($iconInput.val() || 'dashicons-admin-generic') + '"></span></button>');
        const $pickerDropdown = $('<div class="opb-icon-picker-dropdown"></div>');

        // Build icon grid
        let iconsHtml = '<div class="opb-icon-picker-grid">';
        commonDashicons.forEach(function(icon) {
            iconsHtml += '<button type="button" class="opb-icon-picker-item" data-icon="' + icon + '"><span class="dashicons ' + icon + '"></span></button>';
        });
        iconsHtml += '</div>';
        $pickerDropdown.html(iconsHtml);

        // Wrap input with picker
        $iconInput.wrap($pickerContainer);
        $iconInput.before($pickerToggle);
        $iconInput.after($pickerDropdown);

        // Toggle dropdown
        $pickerToggle.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            $(this).siblings('.opb-icon-picker-dropdown').toggleClass('show');
        });

        // Select icon
        $(document).on('click', '.opb-icon-picker-item', function(e) {
            e.preventDefault();
            const icon = $(this).data('icon');
            const $container = $(this).closest('.opb-icon-picker-container');
            $container.find('#opb-icon').val(icon);
            $container.find('.opb-icon-picker-toggle .dashicons').attr('class', 'dashicons ' + icon);
            $container.find('.opb-icon-picker-dropdown').removeClass('show');
            autoSave();
        });

        // Close on click outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.opb-icon-picker-container').length) {
                $('.opb-icon-picker-dropdown').removeClass('show');
            }
        });

        // Update preview on manual input
        $iconInput.on('input', function() {
            const icon = $(this).val() || 'dashicons-admin-generic';
            $(this).siblings('.opb-icon-picker-toggle').find('.dashicons').attr('class', 'dashicons ' + icon);
        });
    }

    /**
     * Add new field
     */
    function addField(fieldType, fieldData = null) {
        const fieldId = fieldData ? fieldData.id : 'field_' + Date.now() + '_' + fieldCounter++;
        const label = fieldData ? fieldData.label : (fieldType === 'group' ? 'New Section' : fieldLabels[fieldType] + ' Field');
        const id = fieldData ? fieldData.field_id : fieldId;
        const description = fieldData ? fieldData.description : '';
        const defaultValue = fieldData ? fieldData.default : '';
        const required = fieldData ? fieldData.required : false;
        const options = fieldData ? fieldData.options : '';
        const width = fieldData ? (fieldData.width || 'full') : 'full';

        const $fieldsList = $('#opb-fields-list');
        const $emptyState = $fieldsList.find('.sb-module-empty');

        if ($emptyState.length) {
            $emptyState.remove();
        }

        // Check if this is a group field type
        const isGroup = fieldType === 'group';

        const fieldHtml = isGroup ? getGroupFieldHtml(fieldId, fieldType, label, id, description) : getRegularFieldHtml(fieldId, fieldType, label, id, description, defaultValue, required, options, width);

        $fieldsList.append(fieldHtml);

        // Refresh sortable only if initialized
        if (sortableInitialized) {
            $fieldsList.sortable('refresh');
        }

        // Scroll to new field (keep it collapsed) - only for user-added fields
        if (!fieldData) {
            const $newField = $fieldsList.find('.opb-field-item').last();
            $newField[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }

        updateFieldsOrder();

        // Only auto-save for user-added fields, not when loading existing
        if (!fieldData) {
            autoSave();
        }
    }

    /**
     * Get regular field HTML
     */
    function getRegularFieldHtml(fieldId, fieldType, label, id, description, defaultValue, required, options, width) {
        return `
            <div class="opb-field-item collapsed" data-field-id="${fieldId}" data-field-type="${fieldType}">
                <div class="opb-field-header">
                    <div class="opb-field-drag">
                        <svg fill="currentColor" viewBox="0 0 24 24">
                            <circle cx="9" cy="6" r="1.5"/><circle cx="15" cy="6" r="1.5"/>
                            <circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/>
                            <circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="18" r="1.5"/>
                        </svg>
                    </div>
                    <div class="opb-field-info">
                        <h4 class="opb-field-title">${escapeHtml(label)}${required ? '<span class="opb-field-required-badge">*</span>' : ''}</h4>
                        <div class="opb-field-meta">
                            <span class="opb-field-type">${fieldLabels[fieldType]}</span>
                            <span class="opb-field-id">${escapeHtml(id)}</span>
                            ${width !== 'full' ? `<span class="opb-field-width-badge">${getWidthLabel(width)}</span>` : ''}
                        </div>
                    </div>
                    <div class="opb-field-actions">
                        <button type="button" class="opb-field-action-btn opb-field-collapse">
                            <svg class="opb-field-collapse-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                            </svg>
                        </button>
                        <button type="button" class="opb-field-action-btn opb-field-delete delete">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                            </svg>
                        </button>
                    </div>
                </div>
                <div class="opb-field-body">
                    <div class="opb-field-config">
                        <div class="opb-field-config-row">
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Field Label <span class="sb-module-required">*</span></label>
                                <input type="text" class="sb-module-input opb-field-label-input" value="${escapeHtml(label)}" required>
                            </div>
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Field ID <span class="sb-module-required">*</span></label>
                                <input type="text" class="sb-module-input opb-field-id-input" value="${escapeHtml(id)}" required>
                                <small class="sb-module-help-text">Use lowercase letters, numbers, and underscores only</small>
                            </div>
                        </div>
                        <div class="sb-module-form-group">
                            <label class="sb-module-form-label">Description</label>
                            <textarea class="sb-module-input opb-field-description-input" rows="2">${escapeHtml(description)}</textarea>
                        </div>
                        ${getFieldTypeSpecificHTML(fieldType, defaultValue, options)}
                        <div class="opb-field-config-row opb-field-config-row-3">
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Default Value</label>
                                <input type="text" class="sb-module-input opb-field-default-value-input" value="${escapeHtml(defaultValue)}">
                            </div>
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Width</label>
                                <select class="sb-module-select opb-field-width-input">
                                    <option value="full" ${width === 'full' ? 'selected' : ''}>Full Width</option>
                                    <option value="2-3" ${width === '2-3' ? 'selected' : ''}>2/3 Width</option>
                                    <option value="1-2" ${width === '1-2' ? 'selected' : ''}>1/2 Width</option>
                                    <option value="1-3" ${width === '1-3' ? 'selected' : ''}>1/3 Width</option>
                                </select>
                            </div>
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Options</label>
                                <label class="sb-module-checkbox-item">
                                    <input type="checkbox" class="opb-field-required-input" ${required ? 'checked' : ''}>
                                    <span>Required field</span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * Get group field HTML
     */
    function getGroupFieldHtml(fieldId, fieldType, label, id, description) {
        return `
            <div class="opb-field-item opb-field-group collapsed" data-field-id="${fieldId}" data-field-type="${fieldType}">
                <div class="opb-field-header opb-field-group-header">
                    <div class="opb-field-drag">
                        <svg fill="currentColor" viewBox="0 0 24 24">
                            <circle cx="9" cy="6" r="1.5"/><circle cx="15" cy="6" r="1.5"/>
                            <circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/>
                            <circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="18" r="1.5"/>
                        </svg>
                    </div>
                    <div class="opb-field-group-icon">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/>
                        </svg>
                    </div>
                    <div class="opb-field-info">
                        <h4 class="opb-field-title">${escapeHtml(label)}</h4>
                        <div class="opb-field-meta">
                            <span class="opb-field-type opb-field-type-group">Section</span>
                            <span class="opb-field-id">${escapeHtml(id)}</span>
                        </div>
                    </div>
                    <div class="opb-field-actions">
                        <button type="button" class="opb-field-action-btn opb-field-collapse">
                            <svg class="opb-field-collapse-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                            </svg>
                        </button>
                        <button type="button" class="opb-field-action-btn opb-field-delete delete">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                            </svg>
                        </button>
                    </div>
                </div>
                <div class="opb-field-body">
                    <div class="opb-field-config">
                        <!-- Group Info Notice -->
                        <div class="opb-group-info-notice">
                            <span class="dashicons dashicons-info-outline"></span>
                            <div>
                                <strong>What is a Section/Group?</strong>
                                <p>Sections organize your fields into logical groups with sidebar navigation on the options page. Fields placed after this section (until the next section) will be grouped together. Great for separating settings like "General", "Social Links", "SEO", etc.</p>
                            </div>
                        </div>
                        <div class="opb-field-config-row">
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Section Title <span class="sb-module-required">*</span></label>
                                <input type="text" class="sb-module-input opb-field-label-input" value="${escapeHtml(label)}" required placeholder="e.g., Personal Info, Social Links">
                            </div>
                            <div class="sb-module-form-group">
                                <label class="sb-module-form-label">Section ID <span class="sb-module-required">*</span></label>
                                <input type="text" class="sb-module-input opb-field-id-input" value="${escapeHtml(id)}" required>
                                <small class="sb-module-help-text">Used for navigation anchor</small>
                            </div>
                        </div>
                        <div class="sb-module-form-group">
                            <label class="sb-module-form-label">Description</label>
                            <textarea class="sb-module-input opb-field-description-input" rows="2" placeholder="Brief description of this section">${escapeHtml(description)}</textarea>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * Get field type specific HTML
     */
    function getFieldTypeSpecificHTML(fieldType, defaultValue = '', options = '') {
        let html = '';

        // Options for select, checkbox, radio
        if (['select', 'checkbox', 'radio'].includes(fieldType)) {
            html += `
                <div class="sb-module-form-group">
                    <label class="sb-module-form-label">Options <span class="sb-module-required">*</span></label>
                    <textarea class="sb-module-input opb-field-options-input" rows="4" required>${escapeHtml(options)}</textarea>
                    <small class="sb-module-help-text">One option per line. Use <code>value : label</code> format</small>
                </div>
            `;
        }

        return html;
    }

    /**
     * Update fields order
     */
    function updateFieldsOrder() {
        fieldsData = [];
        $('.opb-field-item').each(function(index) {
            const $field = $(this);
            const fieldData = {
                id: $field.data('field-id'),
                type: $field.data('field-type'),
                label: $field.find('.opb-field-label-input').val(),
                field_id: $field.find('.opb-field-id-input').val(),
                description: $field.find('.opb-field-description-input').val(),
                default: $field.find('.opb-field-default-value-input').val() || '',
                options: $field.find('.opb-field-options-input').val() || '',
                required: $field.find('.opb-field-required-input').is(':checked'),
                width: $field.find('.opb-field-width-input').val() || 'full',
                order: index
            };
            fieldsData.push(fieldData);
        });
    }

    /**
     * Update field data
     */
    function updateFieldData($field) {
        const label = $field.find('.opb-field-label-input').val();
        const id = $field.find('.opb-field-id-input').val();
        const required = $field.find('.opb-field-required-input').is(':checked');
        const width = $field.find('.opb-field-width-input').val() || 'full';

        // Update header display - title with required badge
        const $title = $field.find('.opb-field-title');
        $title.html(escapeHtml(label) + (required ? '<span class="opb-field-required-badge">*</span>' : ''));

        // Update field ID display
        $field.find('.opb-field-id').text(id);

        // Update width badge
        const $meta = $field.find('.opb-field-meta');
        $meta.find('.opb-field-width-badge').remove();
        if (width !== 'full') {
            $meta.append(`<span class="opb-field-width-badge">${getWidthLabel(width)}</span>`);
        }

        updateFieldsOrder();
    }

    /**
     * Load existing fields
     */
    function loadExistingFields() {
        // This would load from page data passed via wp_localize_script
        if (typeof switchboard_opb_page_data !== 'undefined' && switchboard_opb_page_data.fields) {
            switchboard_opb_page_data.fields.forEach(function(fieldData) {
                addField(fieldData.type, fieldData);
            });
        }
    }

    /**
     * Check empty state
     */
    function checkEmptyState() {
        const $fieldsList = $('#opb-fields-list');
        const hasFields = $fieldsList.find('.opb-field-item').length > 0;

        if (!hasFields) {
            $fieldsList.html(`
                <div class="sb-module-empty">
                    <div class="sb-module-empty-icon"></div>
                    <h3 class="sb-module-empty-title">No Fields Added Yet</h3>
                    <p class="sb-module-empty-desc">Click a field type in the Quick Add panel to get started</p>
                </div>
            `);
        }
    }

    /**
     * Auto save
     */
    function autoSave() {
        // Don't auto-save if we're creating a new page (no page ID yet)
        if (!currentPageId) {
            return;
        }

        clearTimeout(saveTimeout);
        saveTimeout = setTimeout(function() {
            savePage(true);
        }, 1000);
    }

    /**
     * Save page
     */
    function savePage(isAutoSave = false) {
        const $form = $('#opb-form');
        const $saveIndicator = $('#opb-save-indicator');
        const $saveBtn = $('#opb-save-page');

        // Validate required fields
        if (!isAutoSave) {
            const pageTitle = $('#opb-page-title').val().trim();
            const menuTitle = $('#opb-menu-title').val().trim();
            const menuSlug = $('#opb-menu-slug').val().trim();

            if (!pageTitle || !menuTitle || !menuSlug) {
                showToast('Please fill in all required fields', 'error');
                return;
            }
        }

        updateFieldsOrder();

        const pageData = {
            action: 'switchboard_save_options_page',
            nonce: switchboard_opb.nonce,
            page_id: currentPageId || '',
            page_title: $('#opb-page-title').val(),
            page_description: $('#opb-page-description').val(),
            menu_title: $('#opb-menu-title').val(),
            menu_slug: $('#opb-menu-slug').val(),
            parent_menu: $('#opb-parent-menu').val(),
            capability: $('#opb-capability').val(),
            icon: $('#opb-icon').val(),
            position: $('#opb-position').val(),
            fields: fieldsData
        };

        // Show saving state
        $saveIndicator.removeClass('saved error').addClass('saving')
            .html('<span class="opb-save-spinner"></span> Saving...');

        if (!isAutoSave) {
            $saveBtn.prop('disabled', true).text('Saving...');
        }

        $.post(ajaxurl, pageData, function(response) {
            if (response.success) {
                $saveIndicator.removeClass('saving').addClass('saved')
                    .html('<svg style="width:14px;height:14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/></svg> Saved');

                // Show toast for manual save
                if (!isAutoSave) {
                    showToast('Options page saved successfully!', 'success');
                    $saveBtn.prop('disabled', false).text('Save Options Page');
                }

                // Update page ID if this was a new page
                if (!currentPageId && response.data.page_id) {
                    currentPageId = response.data.page_id;
                    // Update URL without reload
                    const newUrl = window.location.pathname + '?page=switchboard-options-page-builder&action=edit&page_id=' + currentPageId;
                    window.history.replaceState({}, '', newUrl);
                }

                setTimeout(function() {
                    $saveIndicator.removeClass('saved').text('');
                }, 3000);
            } else {
                $saveIndicator.removeClass('saving').addClass('error')
                    .text('Error saving');
                showToast(response.data.message || 'Failed to save options page', 'error');

                if (!isAutoSave) {
                    $saveBtn.prop('disabled', false).text('Save Options Page');
                }
            }
        }).fail(function() {
            $saveIndicator.removeClass('saving').addClass('error')
                .text('Error saving');
            showToast('Failed to save options page. Please try again.', 'error');

            if (!isAutoSave) {
                $saveBtn.prop('disabled', false).text('Save Options Page');
            }
        });
    }

    /**
     * Delete page
     */
    function deletePage() {
        if (!currentPageId) return;

        $.post(ajaxurl, {
            action: 'switchboard_delete_options_page',
            nonce: switchboard_opb.nonce,
            page_id: currentPageId
        }, function(response) {
            if (response.success) {
                showToast('Options page deleted successfully!', 'success');
                setTimeout(function() {
                    window.location.href = 'admin.php?page=switchboard-options-page-builder';
                }, 1000);
            } else {
                showToast(response.data.message || 'Failed to delete options page', 'error');
            }
        });
    }

    /**
     * Escape HTML
     */
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function(m) { return map[m]; });
    }

})(jQuery);
