/**
 * Rich Snippet Editor - Smart Builder + Code Editor
 * For URL Detail View
 *
 * @package CustomSchemaSchemafy
 * @since 2.1.0
 */

(function($) {
    'use strict';

    window.SCHEMAFY = window.SCHEMAFY || {};

    window.SCHEMAFY.SnippetEditor = {
        currentSchema: {},
        schemaType: null,
        editorMode: 'visual', // 'visual' or 'code'
        currentUrl: null,
        editingSchemaId: null,

        init: function(url = null) {
            if (url) {
                this.currentUrl = url;
            }
            this.bindEvents();
        },

        // Modern notification system
        showNotification: function(message, type = 'info') {
            // Remove existing notifications
            $('.schemafy-notification').remove();

            const icons = {
                success: '✅',
                error: '❌',
                warning: '⚠️',
                info: 'ℹ️'
            };

            const colors = {
                success: '#0d9488',
                error: '#3730a3',
                warning: '#7882e4',
                info: '#7a8ae9'
            };

            const notification = $(`
                <div class="schemafy-notification schemafy-notification-${type}" style="
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    z-index: 9999999;
                    background: white;
                    padding: 16px 24px;
                    border-radius: 12px;
                    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
                    display: flex;
                    align-items: center;
                    gap: 12px;
                    min-width: 300px;
                    max-width: 500px;
                    border-left: 4px solid ${colors[type]};
                    animation: slideInRight 0.3s ease-out;
                ">
                    <span style="font-size: 24px;">${icons[type]}</span>
                    <span style="color: #334155; font-size: 14px; font-weight: 500; flex: 1;">${message}</span>
                    <button class="schemafy-notification-close" style="
                        background: none;
                        border: none;
                        cursor: pointer;
                        font-size: 20px;
                        color: #94a3b8;
                        padding: 0;
                        width: 24px;
                        height: 24px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    ">×</button>
                </div>
            `);

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

            // Auto-dismiss after 4 seconds
            setTimeout(() => {
                notification.fadeOut(300, () => notification.remove());
            }, 4000);

            // Manual close
            notification.find('.schemafy-notification-close').on('click', () => {
                notification.fadeOut(300, () => notification.remove());
            });
        },

        bindEvents: function() {
            // Add new snippet button
            $(document).on('click', '#schemafy-add-snippet-btn', (e) => {
                e.preventDefault();
                this.showEditor();
            });

            // Close modal button
            $(document).on('click', '#schemafy-close-snippet-modal', () => this.hideEditor());

            // Cancel editing
            $(document).on('click', '#schemafy-cancel-snippet-edit', () => this.hideEditor());

            // Mode toggle
            $(document).on('click', '.schemafy-snippet-mode-btn', (e) => this.toggleMode(e));

            // Schema type change
            $(document).on('change', '#schemafy-snippet-schema-type', (e) => this.onSchemaTypeChange(e));

            // Field changes
            $(document).on('input change', '.schemafy-snippet-field', (e) => this.onFieldChange(e));

            // Repeatable field actions
            $(document).on('click', '.schemafy-snippet-add-item', (e) => this.addRepeatableItem(e));
            $(document).on('click', '.schemafy-snippet-remove-item', (e) => this.removeRepeatableItem(e));

            // Dynamic array actions (for schemas like BreadcrumbList)
            $(document).on('click', '.schemafy-snippet-add-dynamic-item', (e) => this.addDynamicArrayItem(e));
            $(document).on('click', '.schemafy-snippet-remove-array-item', (e) => this.removeDynamicArrayItem(e));

            // Repeatable object actions (for FAQ, HowTo steps, etc.)
            $(document).on('click', '.schemafy-snippet-add-object-item', (e) => this.addRepeatableObjectItem(e));
            $(document).on('click', '.schemafy-snippet-remove-object-item', (e) => this.removeRepeatableObjectItem(e));

            // Save/Update actions
            $(document).on('click', '#schemafy-save-snippet', () => this.saveSnippet());
            $(document).on('click', '#schemafy-update-snippet', () => this.updateSnippet());

            // Code editor actions
            $(document).on('click', '#schemafy-snippet-code-format', () => this.formatCode());
            $(document).on('click', '#schemafy-snippet-code-validate', () => this.validateCode());
            $(document).on('input', '#schemafy-snippet-code-textarea', () => this.syncFromCode());
        },

        showEditor: function(schemaId = null, initialMode = 'visual') {
            this.editingSchemaId = schemaId;

            // Create modal if it doesn't exist
            if ($('#schemafy-snippet-modal').length === 0) {
                this.createEditorModal();
            }

            // Reset form
            this.resetEditor();

            // Set initial mode based on parameter
            if (initialMode === 'manual-json') {
                this.editorMode = 'code';
            } else {
                this.editorMode = 'visual';
            }

            // If editing existing schema, load it
            if (schemaId) {
                this.loadSchemaForEdit(schemaId);
                $('#schemafy-save-snippet').hide();
                $('#schemafy-update-snippet').show();
            } else {
                $('#schemafy-save-snippet').show();
                $('#schemafy-update-snippet').hide();
            }

            // Show modal
            $('#schemafy-snippet-modal').fadeIn(200);

            // Apply the initial mode after modal is shown
            setTimeout(() => {
                if (this.editorMode === 'code') {
                    $('.schemafy-snippet-mode-btn').removeClass('active');
                    $('.schemafy-snippet-mode-btn[data-mode="code"]').addClass('active');
                    $('.schemafy-snippet-visual-builder').addClass('hidden');
                    $('.schemafy-snippet-code-editor').addClass('active');
                } else {
                    $('.schemafy-snippet-mode-btn').removeClass('active');
                    $('.schemafy-snippet-mode-btn[data-mode="visual"]').addClass('active');
                    $('.schemafy-snippet-visual-builder').removeClass('hidden');
                    $('.schemafy-snippet-code-editor').removeClass('active');
                }
            }, 50);
        },

        createEditorModal: function() {
            const modalHtml = `
                <div id="schemafy-snippet-modal" class="schemafy-modal-overlay" style="display: none;">
                    <div class="schemafy-snippet-modal-content">
                        <div class="schemafy-snippet-modal-header">
                            <h2>
                                <span class="dashicons dashicons-hammer"></span>
                                Schema Editor
                            </h2>
                            <button class="schemafy-modal-close" id="schemafy-close-snippet-modal">
                                <span class="dashicons dashicons-no-alt"></span>
                            </button>
                        </div>
                        <div class="schemafy-snippet-modal-body">
                            <!-- Mode Toggle -->
                            <div class="schemafy-snippet-mode-toggle">
                                <button class="schemafy-snippet-mode-btn active" data-mode="visual">
                                    <span class="dashicons dashicons-edit"></span>
                                    Visual Builder
                                </button>
                                <button class="schemafy-snippet-mode-btn" data-mode="code">
                                    <span class="dashicons dashicons-editor-code"></span>
                                    Code Editor
                                </button>
                            </div>

                            <!-- Schema Type Selector -->
                            <div class="schemafy-snippet-type-selector">
                                <label for="schemafy-snippet-schema-type">Select Schema Type</label>
                                <select id="schemafy-snippet-schema-type">
                                    <option value="">Choose a schema type...</option>
                                    <option value="Article">📰 Article</option>
                                    <option value="Product">🛍️ Product</option>
                                    <option value="Organization">🏢 Organization</option>
                                    <option value="LocalBusiness">🏪 LocalBusiness</option>
                                    <option value="Person">👤 Person</option>
                                    <option value="Event">🎉 Event</option>
                                    <option value="Recipe">🍳 Recipe</option>
                                    <option value="Review">⭐ Review</option>
                                    <option value="FAQ">❓ FAQ</option>
                                    <option value="WebPage">📄 WebPage</option>
                                    <option value="Course">🎓 Course</option>
                                    <option value="HowTo">🔧 HowTo</option>
                                    <option value="JobPosting">💼 JobPosting</option>
                                    <option value="Service">🛠️ Service</option>
                                    <option value="Video">🎬 Video</option>
                                </select>
                            </div>

                            <!-- Schema Name -->
                            <div class="schemafy-snippet-basic-info">
                                <div class="schemafy-snippet-field-group">
                                    <label class="schemafy-snippet-field-label">
                                        Schema Name
                                        <span class="required">*</span>
                                    </label>
                                    <input type="text" id="schemafy-snippet-schema-name" class="schemafy-snippet-field" placeholder="Descriptive name for this schema" required>
                                </div>
                            </div>

                            <!-- Horizontal Layout: Visual Builder + Preview -->
                            <div class="schemafy-snippet-content-wrapper">
                                <!-- Left Column: Visual Builder or Code Editor -->
                                <div class="schemafy-snippet-editor-column">
                                    <!-- Visual Builder -->
                                    <div class="schemafy-snippet-visual-builder">
                                        <div class="schemafy-snippet-editor-empty">
                                            <span class="dashicons dashicons-hammer"></span>
                                            <h4>Select a Schema Type</h4>
                                            <p>Choose a schema type from the dropdown above to start building</p>
                                        </div>
                                    </div>

                                    <!-- Code Editor -->
                                    <div class="schemafy-snippet-code-editor">
                                        <div class="schemafy-snippet-code-toolbar">
                                            <button type="button" id="schemafy-snippet-code-format">
                                                <span class="dashicons dashicons-editor-alignleft"></span>
                                                Format
                                            </button>
                                            <button type="button" id="schemafy-snippet-code-validate">
                                                <span class="dashicons dashicons-yes"></span>
                                                Validate
                                            </button>
                                        </div>
                                        <textarea id="schemafy-snippet-code-textarea" placeholder='{
  "@context": "https://schema.org",
  "@type": "Article",
  "headline": "Your headline here"
}'></textarea>
                                    </div>
                                </div>

                                <!-- Right Column: JSON Preview (Sticky) -->
                                <div class="schemafy-snippet-preview-section">
                                    <h4>JSON Preview</h4>
                                    <pre id="schemafy-snippet-json-preview">{
  "@context": "https://schema.org",
  "@type": "...",
  "name": "..."
}</pre>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="schemafy-snippet-editor-actions">
                                <button type="button" id="schemafy-cancel-snippet-edit">
                                    <span class="dashicons dashicons-no"></span>
                                    Cancel
                                </button>
                                <button type="button" id="schemafy-save-snippet" style="display: none;">
                                    <span class="dashicons dashicons-saved"></span>
                                    Save Schema
                                </button>
                                <button type="button" id="schemafy-update-snippet" style="display: none;">
                                    <span class="dashicons dashicons-saved"></span>
                                    Update Schema
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

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

            // Bind close handlers
            $('#schemafy-close-snippet-modal, #schemafy-cancel-snippet-edit').on('click', () => this.hideEditor());
            $('#schemafy-snippet-modal').on('click', (e) => {
                if ($(e.target).is('#schemafy-snippet-modal')) {
                    this.hideEditor();
                }
            });
        },

        hideEditor: function() {
            $('#schemafy-snippet-modal').fadeOut(200);
            setTimeout(() => this.resetEditor(), 200);
        },

        resetEditor: function() {
            this.currentSchema = {};
            this.schemaType = null;
            this.editorMode = 'visual';
            this.editingSchemaId = null;

            $('#schemafy-snippet-schema-type').val('');
            $('#schemafy-snippet-schema-name').val('');
            $('.schemafy-snippet-visual-builder').html('<div class="schemafy-snippet-editor-empty"><span class="dashicons dashicons-hammer"></span><h4>Select a Schema Type</h4><p>Choose a schema type from the dropdown above to start building</p></div>');
            $('#schemafy-snippet-code-textarea').val('');
            $('#schemafy-snippet-json-preview').text('{\n  "@context": "https://schema.org",\n  "@type": "...",\n  "name": "..."\n}');

            // Reset mode toggle
            $('.schemafy-snippet-mode-btn').removeClass('active');
            $('.schemafy-snippet-mode-btn[data-mode="visual"]').addClass('active');
            $('.schemafy-snippet-visual-builder').removeClass('hidden');
            $('.schemafy-snippet-code-editor').removeClass('active');
        },

        toggleMode: function(e) {
            const mode = $(e.currentTarget).data('mode');
            this.editorMode = mode;

            // Update UI
            $('.schemafy-snippet-mode-btn').removeClass('active');
            $(e.currentTarget).addClass('active');

            if (mode === 'visual') {
                $('.schemafy-snippet-visual-builder').removeClass('hidden');
                $('.schemafy-snippet-code-editor').removeClass('active');
                this.syncToVisual();
            } else {
                $('.schemafy-snippet-visual-builder').addClass('hidden');
                $('.schemafy-snippet-code-editor').addClass('active');
                this.syncToCode();
            }
        },

        onSchemaTypeChange: function(e) {
            this.schemaType = $(e.target).val();

            if (!this.schemaType) {
                $('.schemafy-snippet-visual-builder').html('<div class="schemafy-snippet-editor-empty"><span class="dashicons dashicons-hammer"></span><h4>Select a Schema Type</h4><p>Choose a schema type from the dropdown above to start building</p></div>');
                return;
            }

            // Initialize schema with @context and @type
            this.currentSchema = {
                '@context': 'https://schema.org',
                '@type': this.schemaType
            };

            this.renderForm();
            this.updatePreview();
        },

        renderForm: function() {
            if (!this.schemaType) return;

            const $container = $('.schemafy-snippet-visual-builder');
            $container.empty();

            const predefinedFields = this.getFieldsForType(this.schemaType);

            let html = '<div class="schemafy-snippet-fields-container">';

            if (predefinedFields.length > 0) {
                // Use predefined template
                predefinedFields.forEach(field => {
                    html += this.renderField(field);
                });
            } else if (this.currentSchema && Object.keys(this.currentSchema).length > 2) {
                // Dynamic detection: render fields based on existing schema structure
                html += this.renderDynamicSchema(this.currentSchema);
            } else {
                // Show message for unknown schemas without data
                html = `
                    <div class="schemafy-snippet-editor-empty" style="padding: 40px; text-align: center;">
                        <span class="dashicons dashicons-editor-code" style="font-size: 48px; color: #94a3b8;"></span>
                        <h4 style="margin: 16px 0 8px; color: #334155;">${this.schemaType} Schema</h4>
                        <p style="color: #64748b; margin: 0;">No predefined template available. Switch to <strong>Code mode</strong> to edit this schema type.</p>
                    </div>
                `;
            }

            if (predefinedFields.length > 0 || (this.currentSchema && Object.keys(this.currentSchema).length > 2)) {
                html += '</div>';
            }

            $container.html(html);

            if (predefinedFields.length > 0 || (this.currentSchema && Object.keys(this.currentSchema).length > 2)) {
                // Use setTimeout to ensure DOM is fully ready before populating
                // Increased timeout to 100ms to ensure all nested fields are rendered
                setTimeout(() => {
                    this.populateFieldsFromSchema();
                }, 100);
            }
        },

        getFieldsForType: function(type) {
            const schemaFields = {
                'Article': [
                    { name: 'headline', label: 'Headline', type: 'text', required: true, help: 'The headline of the article' },
                    { name: 'description', label: 'Description', type: 'textarea', required: false },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    { name: 'datePublished', label: 'Date Published', type: 'datetime-local', required: false },
                    { name: 'dateModified', label: 'Date Modified', type: 'datetime-local', required: false },
                    {
                        name: 'author',
                        label: 'Author',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Person', 'Organization'], required: true, default: 'Person' },
                            { name: 'name', label: 'Name', type: 'text', required: true }
                        ]
                    },
                    {
                        name: 'publisher',
                        label: 'Publisher',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Organization'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            {
                                name: 'logo',
                                label: 'Logo',
                                type: 'object',
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['ImageObject'], required: true, default: 'ImageObject' },
                                    { name: 'url', label: 'URL', type: 'url', required: true }
                                ]
                            }
                        ]
                    }
                ],
                'Product': [
                    { name: 'name', label: 'Product Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    { name: 'sku', label: 'SKU', type: 'text', required: false },
                    {
                        name: 'brand',
                        label: 'Brand',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Brand'], required: true, default: 'Brand' },
                            { name: 'name', label: 'Name', type: 'text', required: true }
                        ]
                    },
                    {
                        name: 'offers',
                        label: 'Offer',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Offer'], required: true, default: 'Offer' },
                            { name: 'price', label: 'Price', type: 'number', required: true },
                            { name: 'priceCurrency', label: 'Currency', type: 'text', required: true, default: 'USD' },
                            { name: 'availability', label: 'Availability', type: 'select', options: ['InStock', 'OutOfStock', 'PreOrder'], required: true }
                        ]
                    },
                    {
                        name: 'aggregateRating',
                        label: 'Aggregate Rating (Optional)',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['AggregateRating'], required: true, default: 'AggregateRating' },
                            { name: 'ratingValue', label: 'Rating Value', type: 'number', required: true },
                            { name: 'bestRating', label: 'Best Rating', type: 'number', required: false, default: '5' },
                            { name: 'worstRating', label: 'Worst Rating', type: 'number', required: false, default: '1' },
                            { name: 'ratingCount', label: 'Rating Count', type: 'number', required: false },
                            { name: 'reviewCount', label: 'Review Count', type: 'number', required: false }
                        ]
                    },
                    {
                        name: 'review',
                        label: 'Review (Optional)',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Review'], required: true, default: 'Review' },
                            { name: 'name', label: 'Review Name', type: 'text', required: false },
                            { name: 'reviewBody', label: 'Review Text', type: 'textarea', required: false },
                            { name: 'datePublished', label: 'Date Published', type: 'date', required: false },
                            {
                                name: 'author',
                                label: 'Author',
                                type: 'object',
                                required: false,
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['Person'], required: true, default: 'Person' },
                                    { name: 'name', label: 'Name', type: 'text', required: true }
                                ]
                            },
                            {
                                name: 'reviewRating',
                                label: 'Review Rating',
                                type: 'object',
                                required: false,
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['Rating'], required: true, default: 'Rating' },
                                    { name: 'ratingValue', label: 'Rating Value', type: 'number', required: true },
                                    { name: 'bestRating', label: 'Best Rating', type: 'number', required: false, default: '5' },
                                    { name: 'worstRating', label: 'Worst Rating', type: 'number', required: false, default: '1' }
                                ]
                            },
                            {
                                name: 'publisher',
                                label: 'Publisher',
                                type: 'object',
                                required: false,
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['Organization'], required: true, default: 'Organization' },
                                    { name: 'name', label: 'Name', type: 'text', required: true }
                                ]
                            }
                        ]
                    }
                ],
                'Organization': [
                    { name: 'name', label: 'Organization Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: false },
                    { name: 'url', label: 'Website URL', type: 'url', required: true },
                    { name: 'logo', label: 'Logo URL', type: 'url', required: false },
                    { name: 'sameAs', label: 'Social Media Links', type: 'repeatable', itemType: 'url', required: false }
                ],
                'LocalBusiness': [
                    { name: 'name', label: 'Business Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: false },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    {
                        name: 'address',
                        label: 'Address',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['PostalAddress'], required: true, default: 'PostalAddress' },
                            { name: 'streetAddress', label: 'Street Address', type: 'text', required: true },
                            { name: 'addressLocality', label: 'City', type: 'text', required: true },
                            { name: 'addressRegion', label: 'State/Region', type: 'text', required: true },
                            { name: 'postalCode', label: 'Postal Code', type: 'text', required: true },
                            { name: 'addressCountry', label: 'Country', type: 'text', required: true }
                        ]
                    },
                    { name: 'telephone', label: 'Phone Number', type: 'tel', required: false },
                    { name: 'priceRange', label: 'Price Range', type: 'text', required: false, placeholder: '$$' }
                ],
                'Person': [
                    { name: 'name', label: 'Full Name', type: 'text', required: true },
                    { name: 'jobTitle', label: 'Job Title', type: 'text', required: false },
                    { name: 'url', label: 'Website URL', type: 'url', required: false },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    { name: 'sameAs', label: 'Social Media Links', type: 'repeatable', itemType: 'url', required: false }
                ],
                'Event': [
                    { name: 'name', label: 'Event Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'startDate', label: 'Start Date', type: 'datetime-local', required: true },
                    { name: 'endDate', label: 'End Date', type: 'datetime-local', required: false },
                    {
                        name: 'location',
                        label: 'Location',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Place'], required: true, default: 'Place' },
                            { name: 'name', label: 'Venue Name', type: 'text', required: true },
                            { name: 'address', label: 'Address', type: 'text', required: true }
                        ]
                    },
                    { name: 'image', label: 'Image URL', type: 'url', required: false }
                ],
                'Recipe': [
                    { name: 'name', label: 'Recipe Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    { name: 'prepTime', label: 'Prep Time (ISO 8601)', type: 'text', required: false, placeholder: 'PT30M' },
                    { name: 'cookTime', label: 'Cook Time (ISO 8601)', type: 'text', required: false, placeholder: 'PT1H' },
                    { name: 'totalTime', label: 'Total Time (ISO 8601)', type: 'text', required: false, placeholder: 'PT1H30M' },
                    { name: 'recipeYield', label: 'Yield/Servings', type: 'text', required: false, placeholder: '4 servings' },
                    { name: 'recipeCategory', label: 'Category', type: 'text', required: false, placeholder: 'Dessert' },
                    { name: 'recipeCuisine', label: 'Cuisine', type: 'text', required: false, placeholder: 'Mexican' },
                    { name: 'recipeIngredient', label: 'Ingredients', type: 'repeatable', itemType: 'text', required: false },
                    { name: 'recipeInstructions', label: 'Instructions', type: 'repeatable', itemType: 'text', required: false },
                    {
                        name: 'author',
                        label: 'Author',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Person', 'Organization'], required: true, default: 'Person' },
                            { name: 'name', label: 'Name', type: 'text', required: true }
                        ]
                    },
                    {
                        name: 'nutrition',
                        label: 'Nutrition Information',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['NutritionInformation'], required: true, default: 'NutritionInformation' },
                            { name: 'calories', label: 'Calories', type: 'text', required: false, placeholder: '250 calories' },
                            { name: 'servingSize', label: 'Serving Size', type: 'text', required: false, placeholder: '1 piece' }
                        ]
                    }
                ],
                'Review': [
                    { name: 'name', label: 'Review Title', type: 'text', required: false },
                    { name: 'reviewBody', label: 'Review Text', type: 'textarea', required: true },
                    { name: 'datePublished', label: 'Date Published', type: 'date', required: false },
                    {
                        name: 'author',
                        label: 'Author',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Person', 'Organization'], required: true, default: 'Person' },
                            { name: 'name', label: 'Name', type: 'text', required: true }
                        ]
                    },
                    {
                        name: 'itemReviewed',
                        label: 'Item Reviewed',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Product', 'LocalBusiness', 'Organization', 'Event', 'Movie', 'Book', 'Restaurant'], required: true, default: 'Product' },
                            { name: 'name', label: 'Name', type: 'text', required: true }
                        ]
                    },
                    {
                        name: 'reviewRating',
                        label: 'Rating',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Rating'], required: true, default: 'Rating' },
                            { name: 'ratingValue', label: 'Rating Value', type: 'number', required: true },
                            { name: 'bestRating', label: 'Best Rating', type: 'number', required: false, default: '5' },
                            { name: 'worstRating', label: 'Worst Rating', type: 'number', required: false, default: '1' }
                        ]
                    }
                ],
                'FAQ': [
                    {
                        name: 'mainEntity',
                        label: 'FAQ Items',
                        type: 'repeatable-object',
                        required: true,
                        itemFields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Question'], required: true, default: 'Question' },
                            { name: 'name', label: 'Question', type: 'text', required: true },
                            {
                                name: 'acceptedAnswer',
                                label: 'Answer',
                                type: 'object',
                                required: true,
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['Answer'], required: true, default: 'Answer' },
                                    { name: 'text', label: 'Answer Text', type: 'textarea', required: true }
                                ]
                            }
                        ]
                    }
                ],
                'FAQPage': [
                    {
                        name: 'mainEntity',
                        label: 'FAQ Items',
                        type: 'repeatable-object',
                        required: true,
                        itemFields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Question'], required: true, default: 'Question' },
                            { name: 'name', label: 'Question', type: 'text', required: true },
                            {
                                name: 'acceptedAnswer',
                                label: 'Answer',
                                type: 'object',
                                required: true,
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['Answer'], required: true, default: 'Answer' },
                                    { name: 'text', label: 'Answer Text', type: 'textarea', required: true }
                                ]
                            }
                        ]
                    }
                ],
                'WebPage': [
                    { name: 'name', label: 'Page Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: false },
                    { name: 'url', label: 'Page URL', type: 'url', required: true },
                    { name: 'datePublished', label: 'Date Published', type: 'date', required: false },
                    { name: 'dateModified', label: 'Date Modified', type: 'date', required: false },
                    { name: 'inLanguage', label: 'Language', type: 'text', required: false, placeholder: 'en-US' },
                    {
                        name: 'author',
                        label: 'Author',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Person', 'Organization'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Name', type: 'text', required: true }
                        ]
                    },
                    {
                        name: 'publisher',
                        label: 'Publisher',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Organization'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            { name: 'url', label: 'URL', type: 'url', required: false }
                        ]
                    }
                ],
                'Course': [
                    { name: 'name', label: 'Course Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'url', label: 'Course URL', type: 'url', required: false },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    { name: 'courseCode', label: 'Course Code', type: 'text', required: false },
                    { name: 'educationalLevel', label: 'Educational Level', type: 'text', required: false, placeholder: 'Beginner, Intermediate, Advanced' },
                    { name: 'inLanguage', label: 'Language', type: 'text', required: false, placeholder: 'en' },
                    {
                        name: 'provider',
                        label: 'Provider',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Organization', 'Person'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            { name: 'url', label: 'URL', type: 'url', required: false }
                        ]
                    },
                    {
                        name: 'offers',
                        label: 'Pricing',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Offer'], required: true, default: 'Offer' },
                            { name: 'price', label: 'Price', type: 'number', required: false },
                            { name: 'priceCurrency', label: 'Currency', type: 'text', required: false, default: 'USD' },
                            { name: 'availability', label: 'Availability', type: 'select', options: ['InStock', 'SoldOut', 'PreOrder'], required: false }
                        ]
                    }
                ],
                'HowTo': [
                    { name: 'name', label: 'Title', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    { name: 'totalTime', label: 'Total Time (ISO 8601)', type: 'text', required: false, placeholder: 'PT30M' },
                    { name: 'estimatedCost', label: 'Estimated Cost', type: 'text', required: false, placeholder: '$20-$50' },
                    { name: 'supply', label: 'Supplies Needed', type: 'repeatable', itemType: 'text', required: false },
                    { name: 'tool', label: 'Tools Needed', type: 'repeatable', itemType: 'text', required: false },
                    {
                        name: 'step',
                        label: 'Steps',
                        type: 'repeatable-object',
                        required: true,
                        itemFields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['HowToStep'], required: true, default: 'HowToStep' },
                            { name: 'name', label: 'Step Title', type: 'text', required: false },
                            { name: 'text', label: 'Step Instructions', type: 'textarea', required: true },
                            { name: 'image', label: 'Step Image URL', type: 'url', required: false }
                        ]
                    }
                ],
                'JobPosting': [
                    { name: 'title', label: 'Job Title', type: 'text', required: true },
                    { name: 'description', label: 'Job Description', type: 'textarea', required: true },
                    { name: 'datePosted', label: 'Date Posted', type: 'date', required: true },
                    { name: 'validThrough', label: 'Application Deadline', type: 'date', required: false },
                    { name: 'employmentType', label: 'Employment Type', type: 'select', options: ['FULL_TIME', 'PART_TIME', 'CONTRACTOR', 'TEMPORARY', 'INTERN', 'VOLUNTEER', 'PER_DIEM', 'OTHER'], required: true },
                    { name: 'workHours', label: 'Work Hours', type: 'text', required: false, placeholder: '40 hours per week' },
                    { name: 'experienceRequirements', label: 'Experience Required', type: 'text', required: false },
                    { name: 'educationRequirements', label: 'Education Required', type: 'text', required: false },
                    { name: 'skills', label: 'Required Skills', type: 'text', required: false },
                    { name: 'industry', label: 'Industry', type: 'text', required: false },
                    {
                        name: 'hiringOrganization',
                        label: 'Hiring Organization',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Organization'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Company Name', type: 'text', required: true },
                            { name: 'url', label: 'Company URL', type: 'url', required: false },
                            { name: 'logo', label: 'Logo URL', type: 'url', required: false }
                        ]
                    },
                    {
                        name: 'jobLocation',
                        label: 'Job Location',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Place'], required: true, default: 'Place' },
                            {
                                name: 'address',
                                label: 'Address',
                                type: 'object',
                                required: true,
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['PostalAddress'], required: true, default: 'PostalAddress' },
                                    { name: 'streetAddress', label: 'Street', type: 'text', required: false },
                                    { name: 'addressLocality', label: 'City', type: 'text', required: true },
                                    { name: 'addressRegion', label: 'State/Region', type: 'text', required: true },
                                    { name: 'postalCode', label: 'Postal Code', type: 'text', required: false },
                                    { name: 'addressCountry', label: 'Country', type: 'text', required: true }
                                ]
                            }
                        ]
                    },
                    {
                        name: 'baseSalary',
                        label: 'Salary',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['MonetaryAmount'], required: true, default: 'MonetaryAmount' },
                            { name: 'currency', label: 'Currency', type: 'text', required: true, default: 'USD' },
                            {
                                name: 'value',
                                label: 'Amount',
                                type: 'object',
                                required: true,
                                fields: [
                                    { name: '@type', label: 'Type', type: 'select', options: ['QuantitativeValue'], required: true, default: 'QuantitativeValue' },
                                    { name: 'value', label: 'Amount', type: 'number', required: true },
                                    { name: 'unitText', label: 'Per', type: 'select', options: ['HOUR', 'DAY', 'WEEK', 'MONTH', 'YEAR'], required: true, default: 'YEAR' }
                                ]
                            }
                        ]
                    }
                ],
                'Service': [
                    { name: 'name', label: 'Service Name', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'url', label: 'Service URL', type: 'url', required: false },
                    { name: 'image', label: 'Image URL', type: 'url', required: false },
                    { name: 'serviceType', label: 'Service Type', type: 'text', required: false },
                    { name: 'areaServed', label: 'Area Served', type: 'text', required: false, placeholder: 'e.g., United States, California' },
                    {
                        name: 'provider',
                        label: 'Provider',
                        type: 'object',
                        required: true,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Organization', 'Person', 'LocalBusiness'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            { name: 'url', label: 'URL', type: 'url', required: false }
                        ]
                    },
                    {
                        name: 'offers',
                        label: 'Pricing',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Offer'], required: true, default: 'Offer' },
                            { name: 'price', label: 'Price', type: 'text', required: false },
                            { name: 'priceCurrency', label: 'Currency', type: 'text', required: false, default: 'USD' }
                        ]
                    },
                    {
                        name: 'aggregateRating',
                        label: 'Aggregate Rating',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['AggregateRating'], required: true, default: 'AggregateRating' },
                            { name: 'ratingValue', label: 'Rating Value', type: 'number', required: true },
                            { name: 'bestRating', label: 'Best Rating', type: 'number', required: false, default: '5' },
                            { name: 'ratingCount', label: 'Rating Count', type: 'number', required: false }
                        ]
                    }
                ],
                'Video': [
                    { name: 'name', label: 'Video Title', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'thumbnailUrl', label: 'Thumbnail URL', type: 'url', required: true },
                    { name: 'uploadDate', label: 'Upload Date', type: 'date', required: true },
                    { name: 'duration', label: 'Duration (ISO 8601)', type: 'text', required: false, placeholder: 'PT5M30S' },
                    { name: 'contentUrl', label: 'Video File URL', type: 'url', required: false },
                    { name: 'embedUrl', label: 'Embed URL', type: 'url', required: false },
                    { name: 'interactionStatistic', label: 'View Count', type: 'number', required: false },
                    {
                        name: 'author',
                        label: 'Author/Creator',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Person', 'Organization'], required: true, default: 'Person' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            { name: 'url', label: 'URL', type: 'url', required: false }
                        ]
                    },
                    {
                        name: 'publisher',
                        label: 'Publisher',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Organization'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            { name: 'url', label: 'URL', type: 'url', required: false },
                            { name: 'logo', label: 'Logo URL', type: 'url', required: false }
                        ]
                    }
                ],
                'VideoObject': [
                    { name: 'name', label: 'Video Title', type: 'text', required: true },
                    { name: 'description', label: 'Description', type: 'textarea', required: true },
                    { name: 'thumbnailUrl', label: 'Thumbnail URL', type: 'url', required: true },
                    { name: 'uploadDate', label: 'Upload Date', type: 'date', required: true },
                    { name: 'duration', label: 'Duration (ISO 8601)', type: 'text', required: false, placeholder: 'PT5M30S' },
                    { name: 'contentUrl', label: 'Video File URL', type: 'url', required: false },
                    { name: 'embedUrl', label: 'Embed URL', type: 'url', required: false },
                    { name: 'interactionStatistic', label: 'View Count', type: 'number', required: false },
                    {
                        name: 'author',
                        label: 'Author/Creator',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Person', 'Organization'], required: true, default: 'Person' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            { name: 'url', label: 'URL', type: 'url', required: false }
                        ]
                    },
                    {
                        name: 'publisher',
                        label: 'Publisher',
                        type: 'object',
                        required: false,
                        fields: [
                            { name: '@type', label: 'Type', type: 'select', options: ['Organization'], required: true, default: 'Organization' },
                            { name: 'name', label: 'Name', type: 'text', required: true },
                            { name: 'url', label: 'URL', type: 'url', required: false },
                            { name: 'logo', label: 'Logo URL', type: 'url', required: false }
                        ]
                    }
                ]
            };

            return schemaFields[type] || [];
        },

        renderField: function(field, parentPath = '') {
            const fieldPath = parentPath ? `${parentPath}.${field.name}` : field.name;
            const fieldId = `field-${fieldPath.replace(/\./g, '-')}`;
            const requiredMark = field.required ? '<span class="required">*</span>' : '';

            if (field.type === 'object') {
                return this.renderObject(field, fieldPath);
            } else if (field.type === 'repeatable') {
                return this.renderRepeatable(field, fieldPath);
            } else if (field.type === 'repeatable-object') {
                return this.renderRepeatableObject(field, fieldPath);
            }

            let inputHtml = '';
            const placeholder = field.placeholder || '';
            const defaultValue = field.default || '';

            switch(field.type) {
                case 'textarea':
                    // Don't set default value in HTML - let populateFieldsFromSchema handle it
                    // This prevents defaults from overriding actual schema data
                    inputHtml = `<textarea id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" data-default-value="${this.escapeHtml(defaultValue)}" placeholder="${placeholder}"></textarea>`;
                    break;
                case 'select':
                    // Render all options without any pre-selection
                    // populateFieldsFromSchema will set the correct value
                    const options = field.options.map(opt => {
                        return `<option value="${opt}">${opt}</option>`;
                    }).join('');
                    inputHtml = `<select id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" data-default-value="${this.escapeHtml(defaultValue)}">${options}</select>`;
                    break;
                default:
                    // Don't set default value in HTML - store it in data attribute
                    inputHtml = `<input type="${field.type}" id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" data-default-value="${this.escapeHtml(defaultValue)}" placeholder="${placeholder}">`;
            }

            return `
                <div class="schemafy-snippet-field-item">
                    <label class="schemafy-snippet-field-label" for="${fieldId}">
                        ${field.label}
                        ${requiredMark}
                    </label>
                    ${inputHtml}
                </div>
            `;
        },

        renderObject: function(field, fieldPath) {
            const requiredMark = field.required ? '<span class="required">*</span>' : '';
            let html = `
                <div class="schemafy-snippet-field-item">
                    <label class="schemafy-snippet-field-label">
                        ${field.label}
                        ${requiredMark}
                    </label>
                    <div class="schemafy-snippet-object-group">
            `;

            field.fields.forEach(subField => {
                html += this.renderField(subField, fieldPath);
            });

            html += `
                    </div>
                </div>
            `;

            return html;
        },

        renderRepeatable: function(field, fieldPath) {
            const requiredMark = field.required ? '<span class="required">*</span>' : '';
            return `
                <div class="schemafy-snippet-field-item">
                    <label class="schemafy-snippet-field-label">
                        ${field.label}
                        ${requiredMark}
                    </label>
                    <div class="schemafy-snippet-repeatable-group" data-field-path="${fieldPath}">
                        <div class="schemafy-snippet-repeatable-items"></div>
                        <button type="button" class="schemafy-snippet-add-item" data-field-path="${fieldPath}" data-item-type="${field.itemType}">
                            <span class="dashicons dashicons-plus"></span>
                            Add ${field.label}
                        </button>
                    </div>
                </div>
            `;
        },

        /**
         * Render repeatable object fields (like FAQ items, HowTo steps)
         * Allows adding multiple complex objects with nested fields
         */
        renderRepeatableObject: function(field, fieldPath) {
            const requiredMark = field.required ? '<span class="required">*</span>' : '';
            const self = this;

            // Render the first item by default
            const renderObjectItem = (index) => {
                let itemHtml = `
                    <div class="schemafy-snippet-repeatable-object-item" data-index="${index}" style="
                        padding: 20px;
                        margin-bottom: 16px;
                        background: #f8fafc;
                        border: 2px solid #e2e8f0;
                        border-radius: 12px;
                        position: relative;
                    ">
                        <div style="
                            position: absolute;
                            top: -10px;
                            left: 16px;
                            background: #312e81;
                            color: white;
                            padding: 4px 12px;
                            border-radius: 12px;
                            font-size: 11px;
                            font-weight: 700;
                        ">
                            ITEM #${index + 1}
                        </div>
                        <button type="button" class="schemafy-snippet-remove-object-item" data-index="${index}" style="
                            position: absolute;
                            top: 12px;
                            right: 12px;
                            background: #f5f3ff;
                            border: none;
                            border-radius: 6px;
                            padding: 6px 10px;
                            cursor: pointer;
                            color: #dc2626;
                            font-size: 12px;
                            font-weight: 600;
                        ">
                            <span class="dashicons dashicons-trash" style="font-size: 16px; width: 16px; height: 16px;"></span>
                        </button>
                        <div class="schemafy-snippet-object-fields" style="margin-top: 16px;">
                `;

                // Render each field in the item
                field.itemFields.forEach(itemField => {
                    const itemFieldPath = `${fieldPath}[${index}].${itemField.name}`;

                    if (itemField.type === 'object') {
                        // Nested object within the repeatable item
                        itemHtml += `
                            <div class="schemafy-snippet-field-item" style="margin-top: 12px;">
                                <label class="schemafy-snippet-field-label">${itemField.label}</label>
                                <div class="schemafy-snippet-object-group" style="margin-left: 12px; padding-left: 12px; border-left: 2px solid #cbd5e1;">
                        `;
                        itemField.fields.forEach(nestedField => {
                            const nestedPath = `${itemFieldPath}.${nestedField.name}`;
                            itemHtml += self.renderSimpleField(nestedField, nestedPath);
                        });
                        itemHtml += `
                                </div>
                            </div>
                        `;
                    } else {
                        itemHtml += self.renderSimpleField(itemField, itemFieldPath);
                    }
                });

                itemHtml += `
                        </div>
                    </div>
                `;
                return itemHtml;
            };

            // Start with one item
            let html = `
                <div class="schemafy-snippet-field-item">
                    <label class="schemafy-snippet-field-label" style="display: flex; align-items: center; justify-content: space-between;">
                        <span>${field.label} ${requiredMark}</span>
                        <span style="
                            background: #ede9fe;
                            color: #3730a3;
                            padding: 2px 8px;
                            border-radius: 12px;
                            font-size: 11px;
                            font-weight: 600;
                        ">DYNAMIC LIST</span>
                    </label>
                    <div class="schemafy-snippet-repeatable-object-group" data-field-path="${fieldPath}" data-item-fields='${JSON.stringify(field.itemFields)}'>
                        <div class="schemafy-snippet-repeatable-object-items">
                            ${renderObjectItem(0)}
                        </div>
                        <button type="button" class="schemafy-snippet-add-object-item" data-field-path="${fieldPath}" style="
                            width: 100%;
                            padding: 14px;
                            background: white;
                            border: 2px dashed #cbd5e1;
                            border-radius: 10px;
                            color: #64748b;
                            cursor: pointer;
                            font-weight: 600;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;
                            transition: all 0.2s ease;
                        ">
                            <span class="dashicons dashicons-plus-alt2"></span>
                            Add Another ${field.label.replace(/s$/, '')}
                        </button>
                    </div>
                </div>
            `;

            return html;
        },

        /**
         * Render a simple field (text, textarea, select, etc.) - helper for repeatable objects
         */
        renderSimpleField: function(field, fieldPath) {
            const fieldId = `field-${fieldPath.replace(/\./g, '-').replace(/\[/g, '-').replace(/\]/g, '')}`;
            const requiredMark = field.required ? '<span class="required">*</span>' : '';
            const placeholder = field.placeholder || '';
            const defaultValue = field.default || '';

            let inputHtml = '';

            switch(field.type) {
                case 'textarea':
                    inputHtml = `<textarea id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" data-default-value="${this.escapeHtml(defaultValue)}" placeholder="${placeholder}" rows="3"></textarea>`;
                    break;
                case 'select':
                    const options = field.options.map(opt => `<option value="${opt}">${opt}</option>`).join('');
                    inputHtml = `<select id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" data-default-value="${this.escapeHtml(defaultValue)}">${options}</select>`;
                    break;
                default:
                    inputHtml = `<input type="${field.type || 'text'}" id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" data-default-value="${this.escapeHtml(defaultValue)}" placeholder="${placeholder}">`;
            }

            return `
                <div class="schemafy-snippet-field-item" style="margin-bottom: 12px;">
                    <label class="schemafy-snippet-field-label" for="${fieldId}">
                        ${field.label}
                        ${requiredMark}
                    </label>
                    ${inputHtml}
                </div>
            `;
        },

        /**
         * Dynamically render schema structure based on existing data
         * This allows the editor to handle any schema type without hardcoding
         */
        renderDynamicSchema: function(schemaData, parentPath = '') {
            let html = '';

            Object.keys(schemaData).forEach(key => {
                // Skip @context and @type at root level
                if (!parentPath && (key === '@context' || key === '@type')) {
                    return;
                }

                const value = schemaData[key];
                const fieldPath = parentPath ? `${parentPath}.${key}` : key;
                const label = this.formatLabel(key);

                if (Array.isArray(value)) {
                    // Handle arrays (like itemListElement in BreadcrumbList)
                    html += this.renderDynamicArray(key, value, fieldPath, label);
                } else if (typeof value === 'object' && value !== null) {
                    // Handle nested objects
                    html += this.renderDynamicObject(key, value, fieldPath, label);
                } else {
                    // Handle primitive values
                    html += this.renderDynamicField(key, value, fieldPath, label);
                }
            });

            return html;
        },

        /**
         * Render a dynamic array field (like BreadcrumbList items)
         */
        renderDynamicArray: function(key, arrayValue, fieldPath, label) {
            const firstItem = arrayValue[0];
            const isObjectArray = typeof firstItem === 'object' && firstItem !== null;
            const itemCount = arrayValue.length;

            return `
                <div class="schemafy-snippet-field-item" style="background: #f8fafc; border-left: 3px solid #312e81;">
                    <label class="schemafy-snippet-field-label" style="display: flex; align-items: center; justify-content: space-between;">
                        <span>
                            ${label}
                            <span style="color: #94a3b8; font-size: 11px; font-weight: normal; margin-left: 8px;">
                                (${itemCount} ${isObjectArray ? 'item' : 'value'}${itemCount !== 1 ? 's' : ''})
                            </span>
                        </span>
                        <span style="
                            background: #312e81;
                            color: white;
                            padding: 2px 8px;
                            border-radius: 12px;
                            font-size: 11px;
                            font-weight: 600;
                        ">
                            ${isObjectArray ? 'ARRAY OF OBJECTS' : 'ARRAY'}
                        </span>
                    </label>
                    <div class="schemafy-snippet-dynamic-array" data-field-path="${fieldPath}" data-is-object="${isObjectArray}" style="margin-top: 12px;">
                        <div class="schemafy-snippet-array-items">
                            ${arrayValue.map((item, index) => this.renderDynamicArrayItem(item, fieldPath, index, isObjectArray)).join('')}
                        </div>
                        <button type="button" class="schemafy-snippet-add-dynamic-item" data-field-path="${fieldPath}" data-is-object="${isObjectArray}" style="
                            width: 100%;
                            padding: 12px;
                            background: white;
                            border: 2px dashed #cbd5e1;
                            border-radius: 8px;
                            color: #64748b;
                            cursor: pointer;
                            transition: all 0.2s ease;
                            font-weight: 600;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            gap: 8px;
                            margin-top: 12px;
                        " onmouseover="this.style.borderColor='#312e81'; this.style.color='#312e81'; this.style.background='#f5f3ff';" onmouseout="this.style.borderColor='#cbd5e1'; this.style.color='#64748b'; this.style.background='white';">
                            <span class="dashicons dashicons-plus"></span>
                            Add New ${label} Item
                        </button>
                    </div>
                </div>
            `;
        },

        /**
         * Render a single array item
         */
        renderDynamicArrayItem: function(item, parentPath, index, isObject) {
            const itemPath = `${parentPath}[${index}]`;

            if (isObject) {
                // Render object fields
                let fieldsHtml = '';
                Object.keys(item).forEach(key => {
                    const value = item[key];
                    const fieldPath = `${itemPath}.${key}`;
                    const label = this.formatLabel(key);

                    if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
                        // Nested object within array item
                        fieldsHtml += `
                            <div class="schemafy-snippet-field-item" style="margin-left: 12px; padding-left: 12px; border-left: 2px solid #e2e8f0;">
                                <label class="schemafy-snippet-field-label">${label}</label>
                                <div class="schemafy-snippet-object-group">
                                    ${Object.keys(value).map(subKey => {
                                        const subValue = value[subKey];
                                        const subPath = `${fieldPath}.${subKey}`;
                                        const subLabel = this.formatLabel(subKey);
                                        return this.renderDynamicField(subKey, subValue, subPath, subLabel);
                                    }).join('')}
                                </div>
                            </div>
                        `;
                    } else {
                        fieldsHtml += this.renderDynamicField(key, value, fieldPath, label);
                    }
                });

                return `
                    <div class="schemafy-snippet-array-item" style="
                        padding: 20px;
                        padding-top: 16px;
                        margin-bottom: 12px;
                        background: white;
                        border: 2px solid #e2e8f0;
                        border-radius: 8px;
                        position: relative;
                        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
                        transition: all 0.2s ease;
                    " onmouseover="this.style.borderColor='#cbd5e1'; this.style.boxShadow='0 4px 12px rgba(0, 0, 0, 0.1)';" onmouseout="this.style.borderColor='#e2e8f0'; this.style.boxShadow='0 1px 3px rgba(0, 0, 0, 0.05)';">
                        <div style="
                            position: absolute;
                            top: -10px;
                            left: 12px;
                            background: #312e81;
                            color: white;
                            padding: 4px 12px;
                            border-radius: 12px;
                            font-size: 11px;
                            font-weight: 700;
                            letter-spacing: 0.5px;
                        ">
                            ITEM #${index + 1}
                        </div>
                        <button type="button" class="schemafy-snippet-remove-array-item" style="
                            position: absolute;
                            top: 12px;
                            right: 12px;
                            background: #f5f3ff;
                            border: none;
                            border-radius: 6px;
                            padding: 6px 10px;
                            cursor: pointer;
                            color: #dc2626;
                            font-size: 12px;
                            font-weight: 600;
                            transition: all 0.2s ease;
                        " onmouseover="this.style.background='#ede9fe'; this.style.transform='scale(1.05)';" onmouseout="this.style.background='#fee2e2'; this.style.transform='scale(1)';">
                            <span class="dashicons dashicons-trash" style="font-size: 16px; width: 16px; height: 16px;"></span>
                        </button>
                        <div style="margin-top: 12px;">
                            ${fieldsHtml}
                        </div>
                    </div>
                `;
            } else {
                // Simple value in array
                const inputType = this.detectInputType(item, parentPath);
                return `
                    <div class="schemafy-snippet-repeatable-item">
                        <input type="${inputType}" class="schemafy-snippet-field" data-field-path="${itemPath}" value="${this.escapeHtml(item)}">
                        <button type="button" class="schemafy-snippet-remove-item">
                            <span class="dashicons dashicons-no"></span>
                        </button>
                    </div>
                `;
            }
        },

        /**
         * Render a dynamic object field
         */
        renderDynamicObject: function(key, objectValue, fieldPath, label) {
            return `
                <div class="schemafy-snippet-field-item">
                    <label class="schemafy-snippet-field-label">${label}</label>
                    <div class="schemafy-snippet-object-group">
                        ${this.renderDynamicSchema(objectValue, fieldPath)}
                    </div>
                </div>
            `;
        },

        /**
         * Render a dynamic primitive field
         */
        renderDynamicField: function(key, value, fieldPath, label) {
            const inputType = this.detectInputType(value, key);
            const fieldId = `field-${fieldPath.replace(/\./g, '-').replace(/\[/g, '-').replace(/\]/g, '')}`;

            let inputHtml = '';
            if (inputType === 'textarea') {
                inputHtml = `<textarea id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" rows="4">${this.escapeHtml(value)}</textarea>`;
            } else if (inputType === 'checkbox') {
                const checked = value ? 'checked' : '';
                inputHtml = `<input type="checkbox" id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" ${checked}>`;
            } else {
                // Add helpful placeholders based on input type
                let placeholder = '';
                if (inputType === 'url') placeholder = 'https://example.com';
                else if (inputType === 'email') placeholder = 'email@example.com';
                else if (inputType === 'tel') placeholder = '+1-234-567-8900';
                else if (inputType === 'number') placeholder = '0';
                else if (inputType === 'date') placeholder = 'YYYY-MM-DD';

                inputHtml = `<input type="${inputType}" id="${fieldId}" class="schemafy-snippet-field" data-field-path="${fieldPath}" value="${this.escapeHtml(value)}" placeholder="${placeholder}">`;
            }

            // Generate contextual help text
            const helpText = this.getFieldHelpText(key, inputType);
            const helpHtml = helpText ? `
                <span class="schemafy-field-help" style="
                    display: inline-block;
                    margin-left: 6px;
                    color: #94a3b8;
                    cursor: help;
                    font-size: 14px;
                    position: relative;
                " title="${helpText}">
                    <span class="dashicons dashicons-info" style="font-size: 16px; width: 16px; height: 16px; vertical-align: middle;"></span>
                </span>
            ` : '';

            return `
                <div class="schemafy-snippet-field-item">
                    <label class="schemafy-snippet-field-label" for="${fieldId}">
                        ${label}
                        ${helpHtml}
                    </label>
                    ${inputHtml}
                </div>
            `;
        },

        /**
         * Get contextual help text for fields
         */
        getFieldHelpText: function(fieldName, inputType) {
            const lowerFieldName = fieldName.toLowerCase();

            // Common Schema.org field explanations
            const helpTexts = {
                'name': 'The name or title of this item',
                'description': 'A detailed description of this item',
                'url': 'The web address (URL) of this item',
                'image': 'URL of an image representing this item',
                'position': 'The position of this item in a list (starting from 1)',
                '@type': 'The Schema.org type for this item',
                'item': 'The URL or identifier of this item',
                'headline': 'The main headline or title',
                'author': 'The author or creator',
                'publisher': 'The publisher of this content',
                'datePublished': 'When this was first published',
                'dateModified': 'When this was last updated',
                'ratingValue': 'The rating score (e.g., 4.5 out of 5)',
                'reviewCount': 'Total number of reviews',
                'bestRating': 'The highest possible rating (usually 5)',
                'worstRating': 'The lowest possible rating (usually 1)',
                'price': 'The price in the specified currency',
                'priceCurrency': 'Currency code (USD, EUR, etc.)',
                'availability': 'Stock status (InStock, OutOfStock, etc.)',
                'telephone': 'Phone number for contact',
                'email': 'Email address for contact',
                'streetAddress': 'Street address including number',
                'addressLocality': 'City or locality',
                'addressRegion': 'State, province, or region',
                'postalCode': 'Postal or ZIP code',
                'addressCountry': 'Country name or code'
            };

            // Check for exact match
            if (helpTexts[lowerFieldName]) {
                return helpTexts[lowerFieldName];
            }

            // Check for partial matches
            for (const [key, text] of Object.entries(helpTexts)) {
                if (lowerFieldName.includes(key)) {
                    return text;
                }
            }

            // Generic help based on input type
            if (inputType === 'url') return 'Enter a complete URL starting with http:// or https://';
            if (inputType === 'email') return 'Enter a valid email address';
            if (inputType === 'tel') return 'Enter a phone number';
            if (inputType === 'date') return 'Select or enter a date (YYYY-MM-DD format)';
            if (inputType === 'datetime-local') return 'Select or enter date and time';
            if (inputType === 'number') return 'Enter a numeric value';

            return null;
        },

        /**
         * Format field key into readable label
         */
        formatLabel: function(key) {
            // Handle @type specially
            if (key === '@type') return 'Type';

            // Convert camelCase or snake_case to Title Case
            return key
                .replace(/([A-Z])/g, ' $1') // Add space before capital letters
                .replace(/_/g, ' ') // Replace underscores with spaces
                .replace(/^./, str => str.toUpperCase()) // Capitalize first letter
                .trim();
        },

        /**
         * Detect appropriate input type based on value and field name
         */
        detectInputType: function(value, fieldName = '') {
            // Type detection based on field name (semantic detection)
            const lowerFieldName = fieldName.toLowerCase();

            // Phone numbers
            if (lowerFieldName.includes('phone') || lowerFieldName.includes('telephone') || lowerFieldName.includes('tel')) {
                return 'tel';
            }

            // Email
            if (lowerFieldName.includes('email') || lowerFieldName.includes('mail')) {
                return 'email';
            }

            // URLs and links
            if (lowerFieldName.includes('url') || lowerFieldName.includes('link') || lowerFieldName.includes('href') ||
                lowerFieldName.includes('website') || lowerFieldName.includes('image') || lowerFieldName.includes('logo') ||
                lowerFieldName.includes('photo') || lowerFieldName.includes('picture') || lowerFieldName.includes('item')) {
                return 'url';
            }

            // Dates
            if (lowerFieldName.includes('date') || lowerFieldName.includes('published') || lowerFieldName.includes('modified') ||
                lowerFieldName.includes('created') || lowerFieldName.includes('updated')) {
                if (lowerFieldName.includes('time') || lowerFieldName.includes('datetime')) {
                    return 'datetime-local';
                }
                return 'date';
            }

            // Numbers and positions
            if (lowerFieldName.includes('position') || lowerFieldName.includes('index') || lowerFieldName.includes('order') ||
                lowerFieldName.includes('rating') || lowerFieldName.includes('value') || lowerFieldName.includes('count') ||
                lowerFieldName.includes('price') || lowerFieldName.includes('amount') || lowerFieldName.includes('quantity')) {
                return 'number';
            }

            // Long text fields
            if (lowerFieldName.includes('description') || lowerFieldName.includes('body') || lowerFieldName.includes('text') ||
                lowerFieldName.includes('content') || lowerFieldName.includes('summary') || lowerFieldName.includes('abstract')) {
                return 'textarea';
            }

            // Value-based detection
            if (typeof value === 'number') return 'number';
            if (typeof value === 'boolean') return 'checkbox';

            if (typeof value === 'string') {
                // Check for URL patterns
                if (value.match(/^https?:\/\//)) return 'url';

                // Check for email
                if (value.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) return 'email';

                // Check for phone number patterns
                if (value.match(/^[\d\s\-\+\(\)]+$/) && value.length >= 10) return 'tel';

                // Check for date (ISO format)
                if (value.match(/^\d{4}-\d{2}-\d{2}/)) {
                    if (value.includes('T')) return 'datetime-local';
                    return 'date';
                }

                // Long text
                if (value.length > 100) return 'textarea';
            }

            return 'text';
        },

        addRepeatableItem: function(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const fieldPath = $btn.data('field-path');
            const itemType = $btn.data('item-type');
            const $container = $btn.siblings('.schemafy-snippet-repeatable-items');
            const index = $container.children().length;

            const html = `
                <div class="schemafy-snippet-repeatable-item">
                    <input type="${itemType}" class="schemafy-snippet-field" data-field-path="${fieldPath}[${index}]" placeholder="Enter ${itemType}">
                    <button type="button" class="schemafy-snippet-remove-item">
                        <span class="dashicons dashicons-no"></span>
                    </button>
                </div>
            `;

            $container.append(html);
        },

        removeRepeatableItem: function(e) {
            e.preventDefault();
            $(e.currentTarget).closest('.schemafy-snippet-repeatable-item').remove();
            this.collectFormData();
            this.updatePreview();
        },

        /**
         * Add a new item to a repeatable object array (FAQ items, HowTo steps)
         */
        addRepeatableObjectItem: function(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const fieldPath = $btn.data('field-path');
            const $group = $btn.closest('.schemafy-snippet-repeatable-object-group');
            const $container = $group.find('.schemafy-snippet-repeatable-object-items');
            const itemFields = $group.data('item-fields');
            const index = $container.children('.schemafy-snippet-repeatable-object-item').length;

            const self = this;

            // Build the new item HTML
            let itemHtml = `
                <div class="schemafy-snippet-repeatable-object-item" data-index="${index}" style="
                    padding: 20px;
                    margin-bottom: 16px;
                    background: #f8fafc;
                    border: 2px solid #e2e8f0;
                    border-radius: 12px;
                    position: relative;
                ">
                    <div style="
                        position: absolute;
                        top: -10px;
                        left: 16px;
                        background: #312e81;
                        color: white;
                        padding: 4px 12px;
                        border-radius: 12px;
                        font-size: 11px;
                        font-weight: 700;
                    ">
                        ITEM #${index + 1}
                    </div>
                    <button type="button" class="schemafy-snippet-remove-object-item" data-index="${index}" style="
                        position: absolute;
                        top: 12px;
                        right: 12px;
                        background: #f5f3ff;
                        border: none;
                        border-radius: 6px;
                        padding: 6px 10px;
                        cursor: pointer;
                        color: #dc2626;
                        font-size: 12px;
                        font-weight: 600;
                    ">
                        <span class="dashicons dashicons-trash" style="font-size: 16px; width: 16px; height: 16px;"></span>
                    </button>
                    <div class="schemafy-snippet-object-fields" style="margin-top: 16px;">
            `;

            // Render each field in the item
            itemFields.forEach(itemField => {
                const itemFieldPath = `${fieldPath}[${index}].${itemField.name}`;

                if (itemField.type === 'object') {
                    // Nested object within the repeatable item
                    itemHtml += `
                        <div class="schemafy-snippet-field-item" style="margin-top: 12px;">
                            <label class="schemafy-snippet-field-label">${itemField.label}</label>
                            <div class="schemafy-snippet-object-group" style="margin-left: 12px; padding-left: 12px; border-left: 2px solid #cbd5e1;">
                    `;
                    itemField.fields.forEach(nestedField => {
                        const nestedPath = `${itemFieldPath}.${nestedField.name}`;
                        itemHtml += self.renderSimpleField(nestedField, nestedPath);
                    });
                    itemHtml += `
                            </div>
                        </div>
                    `;
                } else {
                    itemHtml += self.renderSimpleField(itemField, itemFieldPath);
                }
            });

            itemHtml += `
                    </div>
                </div>
            `;

            $container.append(itemHtml);
            this.collectFormData();
            this.updatePreview();
        },

        /**
         * Remove an item from a repeatable object array
         */
        removeRepeatableObjectItem: function(e) {
            e.preventDefault();
            const $item = $(e.currentTarget).closest('.schemafy-snippet-repeatable-object-item');

            $item.fadeOut(200, () => {
                $item.remove();
                this.collectFormData();
                this.updatePreview();
            });
        },

        /**
         * Add a new item to a dynamic array (like BreadcrumbList items)
         */
        addDynamicArrayItem: function(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const fieldPath = $btn.data('field-path');
            const isObject = $btn.data('is-object') === true || $btn.data('is-object') === 'true';
            const $container = $btn.siblings('.schemafy-snippet-array-items');
            const index = $container.children('.schemafy-snippet-array-item, .schemafy-snippet-repeatable-item').length;

            if (isObject) {
                // Get template from first item or create a basic template
                const $firstItem = $container.children('.schemafy-snippet-array-item').first();
                let fieldsHtml = '';

                if ($firstItem.length > 0) {
                    // Clone structure from first item
                    const firstItemFields = {};
                    $firstItem.find('.schemafy-snippet-field').each((i, field) => {
                        const $field = $(field);
                        const path = $field.data('field-path');
                        if (path) {
                            // Extract field name from path like itemListElement[0].name
                            const match = path.match(/\[0\]\.(.+)/);
                            if (match) {
                                const fieldName = match[1];
                                firstItemFields[fieldName] = '';
                            }
                        }
                    });

                    // Render fields for new item
                    Object.keys(firstItemFields).forEach(fieldName => {
                        const itemPath = `${fieldPath}[${index}].${fieldName}`;
                        const label = this.formatLabel(fieldName);
                        fieldsHtml += this.renderDynamicField(fieldName, '', itemPath, label);
                    });
                } else {
                    // Basic template for common object array items
                    fieldsHtml = this.renderDynamicField('@type', 'ListItem', `${fieldPath}[${index}].@type`, 'Type');
                    fieldsHtml += this.renderDynamicField('name', '', `${fieldPath}[${index}].name`, 'Name');
                    fieldsHtml += this.renderDynamicField('item', '', `${fieldPath}[${index}].item`, 'Item');
                }

                const html = `
                    <div class="schemafy-snippet-array-item" style="
                        padding: 16px;
                        margin-bottom: 12px;
                        background: white;
                        border: 2px solid #e2e8f0;
                        border-radius: 8px;
                        position: relative;
                    ">
                        <button type="button" class="schemafy-snippet-remove-array-item" style="
                            position: absolute;
                            top: 12px;
                            right: 12px;
                            background: #fee;
                            border: none;
                            border-radius: 4px;
                            padding: 4px 8px;
                            cursor: pointer;
                            color: #dc2626;
                            font-size: 12px;
                        ">
                            <span class="dashicons dashicons-no" style="font-size: 16px; width: 16px; height: 16px;"></span>
                        </button>
                        ${fieldsHtml}
                    </div>
                `;

                $container.append(html);
            } else {
                // Simple value array
                const html = `
                    <div class="schemafy-snippet-repeatable-item">
                        <input type="text" class="schemafy-snippet-field" data-field-path="${fieldPath}[${index}]" placeholder="Enter value">
                        <button type="button" class="schemafy-snippet-remove-item">
                            <span class="dashicons dashicons-no"></span>
                        </button>
                    </div>
                `;
                $container.append(html);
            }

            this.collectFormData();
            this.updatePreview();
        },

        /**
         * Remove an item from a dynamic array
         */
        removeDynamicArrayItem: function(e) {
            e.preventDefault();
            const $item = $(e.currentTarget).closest('.schemafy-snippet-array-item');
            $item.fadeOut(200, () => {
                $item.remove();
                this.collectFormData();
                this.updatePreview();
            });
        },

        onFieldChange: function(e) {
            this.collectFormData();
            this.updatePreview();
        },

        collectFormData: function() {
            const schema = {
                '@context': 'https://schema.org',
                '@type': this.schemaType
            };

            $('.schemafy-snippet-field').each((i, el) => {
                const $el = $(el);
                const path = $el.data('field-path');
                const value = $el.val();

                if (value) {
                    this.setNestedValue(schema, path, value);
                }
            });

            this.currentSchema = schema;
        },

        setNestedValue: function(obj, path, value) {
            // Handle array indices in path like itemListElement[0].name
            const parts = path.split('.');
            let current = obj;

            for (let i = 0; i < parts.length - 1; i++) {
                const part = parts[i];

                // Check if this part contains an array index like "itemListElement[0]"
                const arrayMatch = part.match(/^(.+)\[(\d+)\]$/);

                if (arrayMatch) {
                    const arrayName = arrayMatch[1];
                    const index = parseInt(arrayMatch[2], 10);

                    // Ensure array exists
                    if (!current[arrayName]) {
                        current[arrayName] = [];
                    }

                    // Ensure array has enough elements
                    while (current[arrayName].length <= index) {
                        current[arrayName].push({});
                    }

                    current = current[arrayName][index];
                } else {
                    // Regular object property
                    if (!current[part]) {
                        current[part] = {};
                    }
                    current = current[part];
                }
            }

            // Set the final value
            const lastPart = parts[parts.length - 1];
            const lastArrayMatch = lastPart.match(/^(.+)\[(\d+)\]$/);

            if (lastArrayMatch) {
                const arrayName = lastArrayMatch[1];
                const index = parseInt(lastArrayMatch[2], 10);

                if (!current[arrayName]) {
                    current[arrayName] = [];
                }

                while (current[arrayName].length <= index) {
                    current[arrayName].push(null);
                }

                current[arrayName][index] = value;
            } else {
                current[lastPart] = value;
            }
        },

        populateFieldsFromSchema: function() {
            if (!this.currentSchema || Object.keys(this.currentSchema).length === 0) {
                return;
            }


            // Handle repeatable fields (arrays) first
            $('.schemafy-snippet-repeatable-group').each(function() {
                const $group = $(this);
                const fieldPath = $group.data('field-path');
                const value = window.SCHEMAFY.SnippetEditor.getNestedValue(window.SCHEMAFY.SnippetEditor.currentSchema, fieldPath);

                if (Array.isArray(value) && value.length > 0) {
                    const $addBtn = $group.find('.schemafy-snippet-add-item');
                    const itemType = $addBtn.data('item-type');
                    const $itemsContainer = $group.find('.schemafy-snippet-repeatable-items');

                    // Clear existing items
                    $itemsContainer.empty();

                    // Add an item for each value in the array
                    value.forEach((itemValue, index) => {
                        const html = `
                            <div class="schemafy-snippet-repeatable-item">
                                <input type="${itemType}" class="schemafy-snippet-field" data-field-path="${fieldPath}[${index}]" value="${window.SCHEMAFY.SnippetEditor.escapeHtml(itemValue)}" placeholder="Enter ${itemType}">
                                <button type="button" class="schemafy-snippet-remove-item">
                                    <span class="dashicons dashicons-no"></span>
                                </button>
                            </div>
                        `;
                        $itemsContainer.append(html);
                    });
                }
            });

            // Handle simple fields and nested object fields
            const fieldCount = $('.schemafy-snippet-field').length;

            let populatedCount = 0;
            let skippedCount = 0;
            let defaultCount = 0;

            const self = this;

            $('.schemafy-snippet-field').each(function() {
                const $el = $(this);
                const path = $el.data('field-path');

                // Skip if no path defined
                if (!path) {
                    skippedCount++;
                    return;
                }

                const elementType = $el.prop('tagName');
                const inputType = $el.attr('type') || (elementType === 'SELECT' ? 'select' : 'textarea');

                // Skip repeatable items that were already populated above
                if ($el.closest('.schemafy-snippet-repeatable-item').length > 0) {
                    return;
                }

                let value = self.getNestedValue(self.currentSchema, path);
                const defaultValue = $el.data('default-value');


                // Determine which value to use
                let valueToSet = null;

                if (value !== undefined && value !== null && value !== '') {
                    // We have a real value from schema
                    if (typeof value === 'object' && !Array.isArray(value)) {
                        skippedCount++;
                        return;
                    }
                    valueToSet = value;
                } else if (defaultValue !== undefined && defaultValue !== '') {
                    // Use default value
                    valueToSet = defaultValue;
                    defaultCount++;
                } else {
                    skippedCount++;
                    return;
                }

                // Handle datetime-local fields - convert ISO datetime to local format
                if (inputType === 'datetime-local' && typeof valueToSet === 'string' && valueToSet.includes('T')) {
                    try {
                        const date = new Date(valueToSet);
                        if (!isNaN(date.getTime())) {
                            // Format: YYYY-MM-DDTHH:mm
                            const year = date.getFullYear();
                            const month = String(date.getMonth() + 1).padStart(2, '0');
                            const day = String(date.getDate()).padStart(2, '0');
                            const hours = String(date.getHours()).padStart(2, '0');
                            const minutes = String(date.getMinutes()).padStart(2, '0');
                            valueToSet = `${year}-${month}-${day}T${hours}:${minutes}`;
                        }
                    } catch (e) {
                        console.error('   ❌ Error converting datetime:', e);
                    }
                }

                // Set the value
                const valueBefore = $el.val();
                $el.val(valueToSet);
                const valueAfter = $el.val();


                // Verify it was set correctly (especially for SELECT elements)
                if (elementType === 'SELECT' && valueAfter !== String(valueToSet)) {
                    console.warn(`   ⚠️ WARNING: Select value not set correctly!`);
                    console.warn(`   Expected: "${valueToSet}", Got: "${valueAfter}"`);
                    const availableOptions = $el.find('option').map(function() { return $(this).val(); }).get();
                    console.warn(`   Available options:`, availableOptions);

                    // Try to find a matching option case-insensitively
                    const matchingOption = $el.find('option').filter(function() {
                        return $(this).val().toLowerCase() === String(valueToSet).toLowerCase();
                    });

                    if (matchingOption.length > 0) {
                        $el.val(matchingOption.val());
                    }
                }

                populatedCount++;
            });

        },

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

        getNestedValue: function(obj, path) {
            // Handle array indices in path like itemListElement[0].name
            const parts = path.split('.');
            let current = obj;

            for (const part of parts) {
                if (current === undefined || current === null) return undefined;

                // Check if this part contains an array index like "itemListElement[0]"
                const arrayMatch = part.match(/^(.+)\[(\d+)\]$/);

                if (arrayMatch) {
                    const arrayName = arrayMatch[1];
                    const index = parseInt(arrayMatch[2], 10);

                    if (!current[arrayName] || !Array.isArray(current[arrayName])) {
                        return undefined;
                    }

                    current = current[arrayName][index];
                } else {
                    current = current[part];
                }
            }

            return current;
        },

        syncToCode: function() {
            try {
                const json = JSON.stringify(this.currentSchema, null, 2);
                $('#schemafy-snippet-code-textarea').val(json);
            } catch(e) {
                console.error('Error syncing to code:', e);
            }
        },

        syncFromCode: function() {
            try {
                const json = $('#schemafy-snippet-code-textarea').val();
                this.currentSchema = JSON.parse(json);
                this.updatePreview();
            } catch(e) {
                // Invalid JSON, don't update
            }
        },

        syncToVisual: function() {
            if (this.currentSchema && this.currentSchema['@type']) {
                this.schemaType = this.currentSchema['@type'];
                $('#schemafy-snippet-schema-type').val(this.schemaType);
                this.renderForm();
            }
        },

        formatCode: function() {
            try {
                const json = $('#schemafy-snippet-code-textarea').val();

                if (!json.trim()) {
                    this.showNotification('Please enter some JSON code first', 'warning');
                    return;
                }

                const parsed = JSON.parse(json);
                const formatted = JSON.stringify(parsed, null, 2);
                $('#schemafy-snippet-code-textarea').val(formatted).removeClass('error');
                this.showNotification('JSON formatted successfully', 'success');
            } catch(e) {
                $('#schemafy-snippet-code-textarea').addClass('error');
                this.showNotification('Invalid JSON: ' + e.message, 'error');
            }
        },

        validateCode: function() {
            try {
                const json = $('#schemafy-snippet-code-textarea').val();

                if (!json.trim()) {
                    this.showNotification('Please enter some JSON code first', 'warning');
                    return;
                }

                JSON.parse(json);
                $('#schemafy-snippet-code-textarea').removeClass('error');
                this.showNotification('Valid JSON! ✓', 'success');
            } catch(e) {
                $('#schemafy-snippet-code-textarea').addClass('error');
                this.showNotification('Invalid JSON: ' + e.message, 'error');
            }
        },

        updatePreview: function() {
            try {
                const preview = JSON.stringify(this.currentSchema, null, 2);
                $('#schemafy-snippet-json-preview').text(preview);
            } catch(e) {
                $('#schemafy-snippet-json-preview').text('Error generating preview');
            }
        },

        saveSnippet: function() {
            const schemaName = $('#schemafy-snippet-schema-name').val().trim();

            // Validations
            if (!schemaName) {
                this.showNotification('Please enter a schema name', 'warning');
                $('#schemafy-snippet-schema-name').focus();
                return;
            }

            if (!this.schemaType) {
                this.showNotification('Please select a schema type', 'warning');
                $('#schemafy-snippet-schema-type').focus();
                return;
            }

            // Collect current data
            if (this.editorMode === 'visual') {
                this.collectFormData();
            } else {
                // Validate JSON in code mode
                try {
                    const jsonText = $('#schemafy-snippet-code-textarea').val();
                    this.currentSchema = JSON.parse(jsonText);
                } catch(e) {
                    this.showNotification('Invalid JSON in code editor: ' + e.message, 'error');
                    return;
                }
            }

            // Validate schema structure
            if (!this.currentSchema || !this.currentSchema['@type']) {
                this.showNotification('Schema must have a valid @type property', 'error');
                return;
            }

            // Show loading state
            const $saveBtn = $('#schemafy-save-snippet');
            const originalText = $saveBtn.html();
            $saveBtn.prop('disabled', true).html('<span class="dashicons dashicons-image-rotate" style="animation: rotation 1s infinite linear;"></span> Saving...');

            // Save via AJAX
            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_save_snippet',
                    nonce: schemafy_ajax.nonce,
                    url: this.currentUrl,
                    schema_name: schemaName,
                    schema_type: this.schemaType,
                    schema_data: JSON.stringify(this.currentSchema)
                },
                success: (response) => {
                    if (response.success) {
                        this.showNotification('Schema saved successfully!', 'success');
                        this.hideEditor();
                        // Reload URL detail view
                        if (window.SchemafyAdminV2 && window.SchemafyAdminV2.loadUrlDetailView) {
                            window.SchemafyAdminV2.loadUrlDetailView(this.currentUrl);
                        }
                    } else {
                        this.showNotification('Error: ' + (response.data || 'Unknown error'), 'error');
                        $saveBtn.prop('disabled', false).html(originalText);
                    }
                },
                error: (xhr, status, error) => {
                    this.showNotification('Network error: ' + error, 'error');
                    $saveBtn.prop('disabled', false).html(originalText);
                }
            });
        },

        updateSnippet: function() {
            if (!this.editingSchemaId) {
                this.showNotification('No schema selected for editing', 'error');
                return;
            }

            const schemaName = $('#schemafy-snippet-schema-name').val().trim();

            // Validations
            if (!schemaName) {
                this.showNotification('Please enter a schema name', 'warning');
                $('#schemafy-snippet-schema-name').focus();
                return;
            }

            if (!this.schemaType) {
                this.showNotification('Please select a schema type', 'warning');
                $('#schemafy-snippet-schema-type').focus();
                return;
            }

            // Collect current data
            if (this.editorMode === 'visual') {
                this.collectFormData();
            } else {
                // Validate JSON in code mode
                try {
                    const jsonText = $('#schemafy-snippet-code-textarea').val();
                    this.currentSchema = JSON.parse(jsonText);
                } catch(e) {
                    this.showNotification('Invalid JSON in code editor: ' + e.message, 'error');
                    return;
                }
            }

            // Validate schema structure
            if (!this.currentSchema || !this.currentSchema['@type']) {
                this.showNotification('Schema must have a valid @type property', 'error');
                return;
            }

            // Show loading state
            const $updateBtn = $('#schemafy-update-snippet');
            const originalText = $updateBtn.html();
            $updateBtn.prop('disabled', true).html('<span class="dashicons dashicons-image-rotate" style="animation: rotation 1s infinite linear;"></span> Updating...');

            // Update via AJAX
            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_update_snippet',
                    nonce: schemafy_ajax.nonce,
                    schema_id: this.editingSchemaId,
                    schema_name: schemaName,
                    schema_type: this.schemaType,
                    schema_data: JSON.stringify(this.currentSchema)
                },
                success: (response) => {
                    if (response.success) {
                        this.showNotification('Schema updated successfully!', 'success');
                        this.hideEditor();
                        // Reload URL detail view
                        if (window.SchemafyAdminV2 && window.SchemafyAdminV2.loadUrlDetailView) {
                            window.SchemafyAdminV2.loadUrlDetailView(this.currentUrl);
                        }
                    } else {
                        this.showNotification('Error: ' + (response.data || 'Unknown error'), 'error');
                        $updateBtn.prop('disabled', false).html(originalText);
                    }
                },
                error: (xhr, status, error) => {
                    this.showNotification('Network error: ' + error, 'error');
                    $updateBtn.prop('disabled', false).html(originalText);
                }
            });
        },

        loadSchemaForEdit: function(schemaId) {
            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_snippet',
                    nonce: schemafy_ajax.nonce,
                    schema_id: schemaId
                },
                success: (response) => {

                    if (response.success && response.data) {
                        const schema = response.data;

                        // Set schema name
                        $('#schemafy-snippet-schema-name').val(schema.schema_name);

                        // Parse and set schema data
                        try {
                            this.currentSchema = JSON.parse(schema.schema_data);
                            this.schemaType = this.currentSchema['@type'];

                            // Set type dropdown
                            $('#schemafy-snippet-schema-type').val(this.schemaType);

                            // Render form and populate fields
                            this.renderForm();

                            // Sync to code editor
                            this.syncToCode();

                            // Update preview
                            this.updatePreview();

                        } catch(e) {
                            this.showNotification('Error loading schema: ' + e.message, 'error');
                            console.error('Parse error:', e);
                        }
                    } else {
                        this.showNotification('Failed to load schema data', 'error');
                    }
                },
                error: (xhr, status, error) => {
                    this.showNotification('Error loading schema: ' + error, 'error');
                }
            });
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        // Initialize snippet editor (URL will be set when showEditor is called)
        window.SCHEMAFY.SnippetEditor.init();
    });

})(jQuery);
