/**
 * Bulk Manager Module
 * Handles: Schema list loading, bulk operations, selection
 */
(function($) {
    'use strict';

    window.SchemafyBulk = {
        // Data storage
        allBulkSchemas: [],
        currentBulkPage: 1,
        bulkPerPage: 25,

        /**
         * Load all schemas for bulk management
         */
        loadBulkSchemas: function() {
            const $container = $('#schemafy-bulk-table-container');
            $container.html('<div class="schemafy-loading-v2"><div class="schemafy-spinner-v2"></div><p>Loading schemas...</p></div>');

            this.refreshBulkHealthStats();

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_all_schemas',
                    page: 1,
                    per_page: 1000,
                    nonce: schemafy_ajax.nonce
                },
                success: (response) => {
                    if (response.success && response.data) {
                        const schemas = response.data.schemas || [];

                        this.allBulkSchemas = schemas;
                        this.currentBulkPage = 1;

                        // Populate type filter dropdown from loaded data
                        if (window.SchemafyFilters) {
                            window.SchemafyFilters.populateTypeFilter(schemas);
                        }

                        if (Array.isArray(schemas) && schemas.length > 0) {
                            this.updateBulkStats(schemas);
                            if (window.SchemafyFilters) {
                                window.SchemafyFilters.applyBulkFilters();
                            }
                        } else {
                            $container.html(`
                                <div class="schemafy-builder-placeholder">
                                    <span class="dashicons dashicons-grid-view"></span>
                                    <h3>No schemas found</h3>
                                    <p>Create your first schema using the Smart Builder or Manual JSON tabs</p>
                                    <button class="schemafy-btn-primary" onclick="jQuery('.schemafy-tab-btn-v2[data-tab=\\'builder\\']').trigger('click')">
                                        <span class="dashicons dashicons-plus"></span>
                                        Create First Schema
                                    </button>
                                </div>
                            `);
                        }
                    } else {
                        $container.html(`
                            <div class="schemafy-error-state">
                                <span class="dashicons dashicons-warning"></span>
                                <h3>Error Loading Schemas</h3>
                                <p>${response.data || 'Unknown error occurred'}</p>
                                <button class="schemafy-btn-secondary" onclick="window.SchemafyBulk.loadBulkSchemas()">
                                    <span class="dashicons dashicons-image-rotate"></span>
                                    Retry
                                </button>
                            </div>
                        `);
                    }
                },
                error: (xhr, status, error) => {
                    $container.html(`
                        <div class="schemafy-error-state">
                            <span class="dashicons dashicons-warning"></span>
                            <h3>Connection Error</h3>
                            <p>Failed to load schemas: ${error}</p>
                            <p style="font-size: 12px; color: #666;">Status: ${status}</p>
                            <button class="schemafy-btn-secondary" onclick="window.SchemafyBulk.loadBulkSchemas()">
                                <span class="dashicons dashicons-image-rotate"></span>
                                Retry
                            </button>
                        </div>
                    `);
                }
            });
        },

        /**
         * Render bulk schemas table
         */
        renderBulkTable: function(schemas, pagination) {
            const $container = $('#schemafy-bulk-table-container');

            if (schemas.length === 0) {
                $container.html(`
                    <div class="schemafy-builder-placeholder">
                        <span class="dashicons dashicons-grid-view"></span>
                        <h3>No schemas found</h3>
                        <p>Create your first schema to manage it here</p>
                    </div>
                `);
                return;
            }

            let html = this.renderBulkActionsToolbar();
            html += this.renderBulkTableHeader();

            schemas.forEach(schema => {
                html += this.renderBulkTableRow(schema);
            });

            html += '</tbody></table>';

            if (pagination && pagination.total_pages > 1) {
                html += window.SchemafyUtilities.renderPagination(pagination);
            }

            $container.html(html);
            this.initBulkSelectionHandlers();
            this.bindTableActions($container);
        },

        /**
         * Render bulk actions toolbar HTML
         */
        renderBulkActionsToolbar: function() {
            return `
                <div class="schemafy-bulk-actions-toolbar" style="display: none; padding: 20px; background: linear-gradient(135deg, #5f70de 0%, #3730a3 100%); border: 1px solid var(--schemafy-primary); border-radius: 12px; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(95, 112, 222, 0.2);">
                    <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
                        <div style="display: flex; align-items: center; gap: 12px; padding: 8px 16px; background: rgba(255,255,255,0.95); border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                            <span class="dashicons dashicons-yes-alt" style="color: var(--schemafy-primary); font-size: 20px;"></span>
                            <div>
                                <div class="schemafy-bulk-selected-count" style="font-weight: 700; font-size: 18px; color: var(--schemafy-primary); line-height: 1.2;">0</div>
                                <div style="font-size: 11px; color: var(--schemafy-gray-600); font-weight: 600;">Selected</div>
                            </div>
                        </div>

                        <div style="display: flex; gap: 8px; padding: 8px; background: rgba(255,255,255,0.15); border-radius: 8px;">
                            <button class="schemafy-bulk-activate schemafy-btn-secondary" style="font-size: 13px; background: white; border: none; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                <span class="dashicons dashicons-yes" style="font-size: 16px; color: #0d9488;"></span> Activate
                            </button>
                            <button class="schemafy-bulk-deactivate schemafy-btn-secondary" style="font-size: 13px; background: white; border: none; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                <span class="dashicons dashicons-no-alt" style="font-size: 16px; color: #7882e4;"></span> Deactivate
                            </button>
                        </div>

                        <div style="display: flex; gap: 8px; padding: 8px; background: rgba(255,255,255,0.25); border-radius: 8px; border: 1px solid rgba(255,255,255,0.4);">
                            <button class="schemafy-bulk-edit schemafy-btn-secondary" style="font-size: 13px; background: white; border: none; font-weight: 600; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                <span class="dashicons dashicons-edit" style="font-size: 16px; color: #5f70de;"></span> Edit Properties
                            </button>
                            <button class="schemafy-bulk-assign schemafy-btn-secondary" style="font-size: 13px; background: white; border: none; font-weight: 600; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                <span class="dashicons dashicons-admin-links" style="font-size: 16px; color: #5f70de;"></span> Assign URL
                            </button>
                        </div>

                        <div style="display: flex; gap: 8px; padding: 8px; background: rgba(255,255,255,0.15); border-radius: 8px;">
                            <button class="schemafy-bulk-duplicate schemafy-btn-secondary" style="font-size: 13px; background: white; border: none;">
                                <span class="dashicons dashicons-admin-page" style="font-size: 16px; color: #7a8ae9;"></span> Duplicate
                            </button>
                            <button class="schemafy-bulk-export schemafy-btn-secondary" style="font-size: 13px; background: white; border: none;">
                                <span class="dashicons dashicons-download" style="font-size: 16px; color: #5f70de;"></span> Export
                            </button>
                            <button class="schemafy-bulk-validate schemafy-btn-secondary" style="font-size: 13px; background: white; border: none;">
                                <span class="dashicons dashicons-yes-alt" style="font-size: 16px; color: #0d9488;"></span> Validate
                            </button>
                        </div>

                        <div style="display: flex; gap: 8px; padding: 8px; background: rgba(239, 68, 68, 0.15); border-radius: 8px; border: 1px solid rgba(239, 68, 68, 0.3);">
                            <button class="schemafy-bulk-delete schemafy-btn-secondary" style="font-size: 13px; background: white; border: none; color: var(--schemafy-danger);">
                                <span class="dashicons dashicons-trash" style="font-size: 16px;"></span> Delete
                            </button>
                        </div>

                        <button class="schemafy-bulk-clear schemafy-btn-secondary" style="font-size: 13px; margin-left: auto; background: rgba(255,255,255,0.25); border: 1px solid rgba(255,255,255,0.4); color: white; font-weight: 600;">
                            <span class="dashicons dashicons-no"></span> Clear Selection
                        </button>
                    </div>
                </div>
            `;
        },

        /**
         * Render table header
         */
        renderBulkTableHeader: function() {
            return `
                <table class="schemafy-table-v2" style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th style="text-align: center; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600; width: 40px;">
                                <input type="checkbox" id="schemafy-bulk-select-all" style="cursor: pointer;">
                            </th>
                            <th style="text-align: left; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600;">URL</th>
                            <th style="text-align: left; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600;">Name</th>
                            <th style="text-align: left; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600;">Type</th>
                            <th style="text-align: left; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600;">Created By</th>
                            <th style="text-align: left; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600;">Date</th>
                            <th style="text-align: center; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600;">Status</th>
                            <th style="text-align: center; padding: 12px; border-bottom: 2px solid var(--schemafy-gray-300); font-weight: 600;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
        },

        /**
         * Render single table row
         */
        renderBulkTableRow: function(schema) {
            const safeUrl = window.SchemafyUtilities.escapeHtml(schema.url);
            const safeName = window.SchemafyUtilities.escapeHtml(schema.schema_name);
            const safeType = window.SchemafyUtilities.escapeHtml(schema.schema_type);
            const createdBy = window.SchemafyUtilities.escapeHtml(schema.created_by_name || '—');

            let createdDate = '—';
            if (schema.created_at) {
                const d = new Date(schema.created_at);
                if (!isNaN(d.getTime())) {
                    createdDate = d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
                }
            }

            const statusBadge = schema.is_active
                ? '<span style="background: var(--schemafy-success); color: white; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">Active</span>'
                : '<span style="background: var(--schemafy-gray-400); color: white; padding: 4px 10px; border-radius: 12px; font-size: 12px; font-weight: 600;">Inactive</span>';

            return `
                <tr data-id="${schema.id}" data-type="${safeType}" data-status="${schema.is_active}" style="border-bottom: 1px solid var(--schemafy-gray-200);">
                    <td style="padding: 12px; text-align: center;">
                        <input type="checkbox" class="schemafy-bulk-checkbox" data-id="${schema.id}" style="cursor: pointer;">
                    </td>
                    <td class="schemafy-url-cell" data-url="${safeUrl}" style="padding: 12px; max-width: 300px; word-break: break-all; font-size: 13px; cursor: pointer; color: var(--schemafy-primary);" title="Click to view all schemas for this URL">${safeUrl}</td>
                    <td style="padding: 12px; font-weight: 500;">${safeName}</td>
                    <td style="padding: 12px;">${safeType}</td>
                    <td style="padding: 12px; font-size: 13px; white-space: nowrap;">
                        <span class="dashicons dashicons-admin-users" style="font-size: 14px; width: 14px; height: 14px; vertical-align: middle; color: var(--schemafy-gray-500); margin-right: 4px;"></span>${createdBy}
                    </td>
                    <td style="padding: 12px; font-size: 12px; color: var(--schemafy-gray-600); white-space: nowrap;">${createdDate}</td>
                    <td style="padding: 12px; text-align: center;">${statusBadge}</td>
                    <td style="padding: 12px; text-align: center;">
                        <button class="schemafy-btn-icon schemafy-edit-schema" data-id="${schema.id}" title="Edit">
                            <span class="dashicons dashicons-edit"></span>
                        </button>
                        <button class="schemafy-btn-icon schemafy-toggle-schema" data-id="${schema.id}" title="Toggle Status">
                            <span class="dashicons dashicons-image-rotate"></span>
                        </button>
                        <button class="schemafy-btn-icon schemafy-delete-schema" data-id="${schema.id}" title="Delete" style="color: var(--schemafy-danger);">
                            <span class="dashicons dashicons-trash"></span>
                        </button>
                    </td>
                </tr>
            `;
        },

        /**
         * Bind table action handlers
         */
        bindTableActions: function($container) {
            const self = this;

            $container.off('click', '.schemafy-edit-schema').on('click', '.schemafy-edit-schema', function(e) {
                e.stopPropagation();
                if (window.SchemafyOperations) {
                    window.SchemafyOperations.editSchema($(this).data('id'));
                }
            });

            $container.off('click', '.schemafy-toggle-schema').on('click', '.schemafy-toggle-schema', function(e) {
                e.stopPropagation();
                if (window.SchemafyOperations) {
                    window.SchemafyOperations.toggleSchema($(this).data('id'));
                }
            });

            $container.off('click', '.schemafy-delete-schema').on('click', '.schemafy-delete-schema', function(e) {
                e.stopPropagation();
                if (window.SchemafyOperations) {
                    window.SchemafyOperations.deleteSchema($(this).data('id'));
                }
            });

            $container.off('click', '.schemafy-url-cell').on('click', '.schemafy-url-cell', function(e) {
                e.stopPropagation();
                const url = $(this).data('url');
                if (window.SchemafyUrlManager) {
                    window.SchemafyUrlManager.loadUrlDetailViewInBulk(url);
                }
            });
        },

        /**
         * Initialize bulk selection handlers
         */
        initBulkSelectionHandlers: function() {
            const $container = $('#schemafy-bulk-table-container');
            const $toolbar = $container.find('.schemafy-bulk-actions-toolbar');
            const self = this;

            const updateSelectionCount = () => {
                const count = $container.find('.schemafy-bulk-checkbox:checked').length;
                $container.find('.schemafy-bulk-selected-count').text(count);

                if (count > 0) {
                    $toolbar.css('display', 'block');
                } else {
                    $toolbar.hide();
                }

                const total = $container.find('.schemafy-bulk-checkbox').length;
                const $selectAll = $('#schemafy-bulk-select-all');
                $selectAll.prop('checked', count === total && total > 0);
                $selectAll.prop('indeterminate', count > 0 && count < total);
            };

            $container.off('change', '#schemafy-bulk-select-all').on('change', '#schemafy-bulk-select-all', function(e) {
                const checked = $(e.target).is(':checked');
                $container.find('.schemafy-bulk-checkbox').prop('checked', checked);
                updateSelectionCount();
            });

            $container.off('change', '.schemafy-bulk-checkbox').on('change', '.schemafy-bulk-checkbox', updateSelectionCount);

            $container.off('click', '.schemafy-bulk-clear').on('click', '.schemafy-bulk-clear', () => {
                $container.find('.schemafy-bulk-checkbox').prop('checked', false);
                $('#schemafy-bulk-select-all').prop('checked', false);
                updateSelectionCount();
            });

            // Bulk action buttons
            $container.off('click', '.schemafy-bulk-activate').on('click', '.schemafy-bulk-activate', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                window.SchemafyUtilities.confirm(`Activate ${ids.length} schema(s)?`, () => this.bulkUpdateSchemas(ids, { is_active: 1 }));
            });

            $container.off('click', '.schemafy-bulk-deactivate').on('click', '.schemafy-bulk-deactivate', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                window.SchemafyUtilities.confirm(`Deactivate ${ids.length} schema(s)?`, () => this.bulkUpdateSchemas(ids, { is_active: 0 }));
            });

            $container.off('click', '.schemafy-bulk-delete').on('click', '.schemafy-bulk-delete', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                window.SchemafyUtilities.confirm(`Delete ${ids.length} schema(s)? This cannot be undone.`, () => this.bulkDeleteSchemas(ids));
            });

            $container.off('click', '.schemafy-bulk-duplicate').on('click', '.schemafy-bulk-duplicate', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                window.SchemafyUtilities.confirm(`Duplicate ${ids.length} schema(s)?`, () => this.bulkDuplicateSchemas(ids));
            });

            $container.off('click', '.schemafy-bulk-export').on('click', '.schemafy-bulk-export', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                if (window.SchemafyCsvExport) {
                    window.SchemafyCsvExport.bulkExportSchemas(ids);
                }
            });

            $container.off('click', '.schemafy-bulk-validate').on('click', '.schemafy-bulk-validate', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                if (window.SchemafyValidation) {
                    window.SchemafyValidation.bulkValidateSchemas(ids);
                }
            });

            $container.off('click', '.schemafy-bulk-edit').on('click', '.schemafy-bulk-edit', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                this.showBulkEditModal(ids);
            });

            $container.off('click', '.schemafy-bulk-assign').on('click', '.schemafy-bulk-assign', () => {
                const ids = this.getSelectedSchemaIds();
                if (ids.length === 0) {
                    window.SchemafyUtilities.showNotification('Please select at least one schema', 'warning');
                    return;
                }
                this.showBulkAssignModal(ids);
            });

            updateSelectionCount();
        },

        /**
         * Get selected schema IDs
         */
        getSelectedSchemaIds: function() {
            const ids = [];
            $('#schemafy-bulk-table-container .schemafy-bulk-checkbox:checked').each(function() {
                ids.push($(this).data('id'));
            });
            return ids;
        },

        /**
         * Bulk update schemas
         */
        bulkUpdateSchemas: function(ids, updates) {
            // Optimistic UI update: apply changes to local data immediately
            const idsSet = new Set(ids.map(id => parseInt(id)));
            this.allBulkSchemas.forEach(schema => {
                if (idsSet.has(parseInt(schema.id))) {
                    if (updates.is_active !== undefined) {
                        schema.is_active = updates.is_active;
                    }
                }
            });
            this.updateBulkStats(this.allBulkSchemas);
            if (window.SchemafyFilters) {
                window.SchemafyFilters.applyBulkFilters();
            }

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_bulk_update_schemas',
                    nonce: schemafy_ajax.nonce,
                    schema_ids: ids,
                    updates: updates
                },
                success: (response) => {
                    if (response.success) {
                        window.SchemafyUtilities.showNotification(`${ids.length} schema(s) updated successfully`, 'success');
                        this.refreshBulkHealthStats();
                        if (window.SchemafyDashboard && typeof window.SchemafyDashboard.refreshStats === 'function') {
                            window.SchemafyDashboard.refreshStats();
                        }
                    } else {
                        window.SchemafyUtilities.showNotification('Error updating schemas', 'error');
                        this.loadBulkSchemas();
                    }
                },
                error: () => {
                    window.SchemafyUtilities.showNotification('Network error', 'error');
                    this.loadBulkSchemas();
                }
            });
        },

        /**
         * Bulk delete schemas
         */
        bulkDeleteSchemas: function(ids) {
            // Optimistic UI update: remove deleted schemas immediately from local data
            const idsSet = new Set(ids.map(id => parseInt(id)));
            this.allBulkSchemas = this.allBulkSchemas.filter(s => !idsSet.has(parseInt(s.id)));
            this.updateBulkStats(this.allBulkSchemas);
            if (window.SchemafyFilters) {
                window.SchemafyFilters.applyBulkFilters();
            }

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_bulk_delete_schemas',
                    nonce: schemafy_ajax.nonce,
                    schema_ids: ids
                },
                success: (response) => {
                    if (response.success) {
                        window.SchemafyUtilities.showNotification(`${ids.length} schema(s) deleted successfully`, 'success');
                        // Refresh health stats and sync with server
                        this.refreshBulkHealthStats();
                        if (window.SchemafyDashboard && typeof window.SchemafyDashboard.refreshStats === 'function') {
                            window.SchemafyDashboard.refreshStats();
                        }
                    } else {
                        window.SchemafyUtilities.showNotification('Error deleting schemas', 'error');
                        // Revert: reload from server since delete failed
                        this.loadBulkSchemas();
                    }
                },
                error: () => {
                    window.SchemafyUtilities.showNotification('Network error', 'error');
                    // Revert: reload from server since request failed
                    this.loadBulkSchemas();
                }
            });
        },

        /**
         * Bulk duplicate schemas
         */
        bulkDuplicateSchemas: function(ids) {
            window.SchemafyUtilities.showNotification(`Duplicating ${ids.length} schema(s)...`, 'info');

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_bulk_duplicate_schemas',
                    nonce: schemafy_ajax.nonce,
                    schema_ids: ids
                },
                success: (response) => {
                    if (response.success) {
                        const duplicated = response.data?.duplicated || ids.length;
                        window.SchemafyUtilities.showNotification(`Successfully duplicated ${duplicated} schema(s)`, 'success');
                        this.loadBulkSchemas();
                        if (window.SchemafyDashboard && typeof window.SchemafyDashboard.refreshStats === 'function') {
                            window.SchemafyDashboard.refreshStats();
                        }
                    } else {
                        window.SchemafyUtilities.showNotification(response.data?.message || 'Error duplicating schemas', 'error');
                    }
                },
                error: () => {
                    window.SchemafyUtilities.showNotification('Network error while duplicating schemas', 'error');
                }
            });
        },

        /**
         * Show bulk edit modal
         */
        showBulkEditModal: function(ids) {
            const count = ids.length;
            const self = this;

            const sectionStyle = 'margin-bottom: 24px; padding: 16px; background: var(--schemafy-gray-50); border-radius: 8px; border: 1px solid var(--schemafy-gray-200);';
            const sectionTitleStyle = 'font-size: 13px; font-weight: 700; color: var(--schemafy-gray-700); margin-bottom: 12px; text-transform: uppercase; letter-spacing: 0.5px;';
            const fieldStyle = 'margin-bottom: 10px;';
            const labelStyle = 'display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 500; color: var(--schemafy-gray-700); margin-bottom: 6px; cursor: pointer;';

            const modalHtml = `
                <div class="schemafy-modal-overlay" id="schemafy-bulk-edit-modal">
                    <div class="schemafy-modal-v2" style="max-width: 750px;">
                        <div class="schemafy-modal-header-v2">
                            <h3><span class="dashicons dashicons-edit"></span> Bulk Edit Properties</h3>
                            <button class="schemafy-modal-close-v2">&times;</button>
                        </div>
                        <div class="schemafy-modal-body-v2" style="max-height: 65vh; overflow-y: auto;">
                            <p style="margin-bottom: 20px; color: var(--schemafy-gray-600);">
                                Editing <strong>${count} schema(s)</strong>. Enable only the fields you want to change.
                            </p>

                            <!-- General -->
                            <div style="${sectionStyle}">
                                <div style="${sectionTitleStyle}"><span class="dashicons dashicons-admin-generic" style="font-size: 14px; vertical-align: middle;"></span> General</div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-name"> Schema Name</label>
                                    <input type="text" id="bulk-edit-name" class="schemafy-input-v2 bulk-edit-field" placeholder="New schema name for all selected" disabled>
                                </div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-status"> Status</label>
                                    <select id="bulk-edit-status" class="schemafy-select-v2 bulk-edit-field" disabled>
                                        <option value="1">Active</option>
                                        <option value="0">Inactive</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Schema JSON Properties -->
                            <div style="${sectionStyle}">
                                <div style="${sectionTitleStyle}"><span class="dashicons dashicons-editor-code" style="font-size: 14px; vertical-align: middle;"></span> Schema Properties (JSON-LD)</div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-author"> Author Name</label>
                                    <input type="text" id="bulk-edit-author" class="schemafy-input-v2 bulk-edit-field" placeholder="e.g. John Doe" disabled>
                                </div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-publisher"> Publisher Name</label>
                                    <input type="text" id="bulk-edit-publisher" class="schemafy-input-v2 bulk-edit-field" placeholder="e.g. My Company" disabled>
                                </div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-org"> Organization Name</label>
                                    <input type="text" id="bulk-edit-org" class="schemafy-input-v2 bulk-edit-field" placeholder="e.g. Acme Inc." disabled>
                                </div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-description"> Description</label>
                                    <textarea id="bulk-edit-description" class="schemafy-input-v2 bulk-edit-field" placeholder="Schema description" rows="3" style="resize: vertical;" disabled></textarea>
                                </div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-image"> Image URL</label>
                                    <input type="url" id="bulk-edit-image" class="schemafy-input-v2 bulk-edit-field" placeholder="https://example.com/image.jpg" disabled>
                                </div>
                            </div>

                            <!-- SEO Meta -->
                            <div style="${sectionStyle}">
                                <div style="${sectionTitleStyle}"><span class="dashicons dashicons-search" style="font-size: 14px; vertical-align: middle;"></span> SEO Meta Tags</div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-meta-title"> Meta Title</label>
                                    <input type="text" id="bulk-edit-meta-title" class="schemafy-input-v2 bulk-edit-field" placeholder="SEO title tag" disabled>
                                </div>

                                <div style="${fieldStyle}">
                                    <label style="${labelStyle}"><input type="checkbox" class="bulk-edit-toggle" data-target="bulk-edit-meta-desc"> Meta Description</label>
                                    <textarea id="bulk-edit-meta-desc" class="schemafy-input-v2 bulk-edit-field" placeholder="SEO meta description" rows="2" style="resize: vertical;" disabled></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="schemafy-modal-footer-v2">
                            <button class="schemafy-btn-secondary" id="schemafy-bulk-edit-cancel">Cancel</button>
                            <button class="schemafy-btn-primary" id="schemafy-bulk-edit-apply">
                                <span class="dashicons dashicons-yes"></span> Apply Changes
                            </button>
                        </div>
                    </div>
                </div>
            `;

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

            // Toggle enable/disable for each field
            $('#schemafy-bulk-edit-modal').on('change', '.bulk-edit-toggle', function() {
                const targetId = $(this).data('target');
                $('#' + targetId).prop('disabled', !this.checked);
                if (this.checked) {
                    $('#' + targetId).focus();
                }
            });

            $('#schemafy-bulk-edit-modal .schemafy-modal-close-v2, #schemafy-bulk-edit-cancel').on('click', () => {
                $('#schemafy-bulk-edit-modal').remove();
            });

            $('#schemafy-bulk-edit-apply').on('click', () => {
                const updates = {};

                // General
                if ($('[data-target="bulk-edit-name"]').is(':checked')) {
                    updates.schema_name = $('#bulk-edit-name').val();
                }
                if ($('[data-target="bulk-edit-status"]').is(':checked')) {
                    updates.is_active = parseInt($('#bulk-edit-status').val());
                }

                // Schema JSON properties
                if ($('[data-target="bulk-edit-author"]').is(':checked')) {
                    updates.author = $('#bulk-edit-author').val();
                }
                if ($('[data-target="bulk-edit-publisher"]').is(':checked')) {
                    updates.publisher = $('#bulk-edit-publisher').val();
                }
                if ($('[data-target="bulk-edit-org"]').is(':checked')) {
                    updates.organization = $('#bulk-edit-org').val();
                }
                if ($('[data-target="bulk-edit-description"]').is(':checked')) {
                    updates.description = $('#bulk-edit-description').val();
                }
                if ($('[data-target="bulk-edit-image"]').is(':checked')) {
                    updates.image = $('#bulk-edit-image').val();
                }

                // SEO Meta
                if ($('[data-target="bulk-edit-meta-title"]').is(':checked')) {
                    updates.meta_title = $('#bulk-edit-meta-title').val();
                }
                if ($('[data-target="bulk-edit-meta-desc"]').is(':checked')) {
                    updates.meta_description = $('#bulk-edit-meta-desc').val();
                }

                if (Object.keys(updates).length === 0) {
                    window.SchemafyUtilities.showNotification('Please enable at least one field to update', 'warning');
                    return;
                }

                $('#schemafy-bulk-edit-modal').remove();
                self.applyBulkPropertyEdits(ids, updates);
            });
        },

        /**
         * Apply bulk property edits
         */
        applyBulkPropertyEdits: function(ids, updates) {
            window.SchemafyUtilities.showNotification(`Updating ${ids.length} schema(s)...`, 'info');

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_bulk_edit_properties',
                    nonce: schemafy_ajax.nonce,
                    schema_ids: ids,
                    updates: updates
                },
                success: (response) => {
                    if (response.success) {
                        const updated = response.data?.updated || ids.length;
                        window.SchemafyUtilities.showNotification(`Successfully updated ${updated} schema(s)`, 'success');
                        this.loadBulkSchemas();
                        if (window.SchemafyDashboard && typeof window.SchemafyDashboard.refreshStats === 'function') {
                            window.SchemafyDashboard.refreshStats();
                        }
                    } else {
                        window.SchemafyUtilities.showNotification(response.data?.message || 'Error updating schemas', 'error');
                    }
                },
                error: () => {
                    window.SchemafyUtilities.showNotification('Network error while updating schemas', 'error');
                }
            });
        },

        /**
         * Show bulk assign URLs modal with site URL dropdown
         */
        showBulkAssignModal: function(ids) {
            const count = ids.length;
            const self = this;

            const modalHtml = `
                <div class="schemafy-modal-overlay" id="schemafy-bulk-assign-modal">
                    <div class="schemafy-modal-v2" style="max-width: 700px;">
                        <div class="schemafy-modal-header-v2">
                            <h3><span class="dashicons dashicons-admin-links"></span> Assign URL</h3>
                            <button class="schemafy-modal-close-v2">&times;</button>
                        </div>
                        <div class="schemafy-modal-body-v2">
                            <p style="margin-bottom: 20px; color: var(--schemafy-gray-600);">
                                Assign ${count} selected schema(s) to a URL from your site.
                            </p>

                            <div class="schemafy-form-group-v2">
                                <label style="font-weight: 600; margin-bottom: 8px; display: block;">Search URL</label>
                                <input type="text" id="bulk-assign-search" class="schemafy-input-v2" placeholder="Type to filter URLs..." style="margin-bottom: 12px;">
                            </div>

                            <div class="schemafy-form-group-v2">
                                <label style="font-weight: 600; margin-bottom: 8px; display: block;">Select URL</label>
                                <div id="bulk-assign-url-list" style="border: 1px solid var(--schemafy-gray-300); border-radius: 8px; max-height: 300px; overflow-y: auto;">
                                    <div style="padding: 40px; text-align: center; color: var(--schemafy-gray-500);">
                                        <div class="schemafy-spinner-v2" style="margin: 0 auto 12px;"></div>
                                        <p>Loading site URLs...</p>
                                    </div>
                                </div>
                                <input type="hidden" id="bulk-assign-selected-url" value="">
                            </div>
                        </div>
                        <div class="schemafy-modal-footer-v2">
                            <button class="schemafy-btn-secondary" id="schemafy-bulk-assign-cancel">Cancel</button>
                            <button class="schemafy-btn-primary" id="schemafy-bulk-assign-apply" disabled>
                                <span class="dashicons dashicons-admin-links"></span> Assign URL
                            </button>
                        </div>
                    </div>
                </div>
            `;

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

            // Load site URLs
            self._loadAssignUrlList();

            // Search filter
            let filterTimeout = null;
            $('#bulk-assign-search').on('input', function() {
                clearTimeout(filterTimeout);
                const query = $(this).val().toLowerCase();
                filterTimeout = setTimeout(() => {
                    $('#bulk-assign-url-list .schemafy-assign-url-item').each(function() {
                        const text = $(this).text().toLowerCase();
                        $(this).toggle(text.indexOf(query) !== -1);
                    });
                }, 150);
            });

            // Close handlers
            $('#schemafy-bulk-assign-modal .schemafy-modal-close-v2, #schemafy-bulk-assign-cancel').on('click', () => {
                $('#schemafy-bulk-assign-modal').remove();
            });

            // Apply handler
            $('#schemafy-bulk-assign-apply').on('click', () => {
                const selectedUrl = $('#bulk-assign-selected-url').val();
                if (!selectedUrl) {
                    window.SchemafyUtilities.showNotification('Please select a URL', 'warning');
                    return;
                }
                $('#schemafy-bulk-assign-modal').remove();
                self.applyBulkUrlAssignment(ids, selectedUrl);
            });
        },

        /**
         * Load site URLs into the assign modal list
         */
        _loadAssignUrlList: function() {
            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_site_urls',
                    nonce: schemafy_ajax.nonce
                },
                success: (response) => {
                    if (response.success && response.data?.urls) {
                        const urls = response.data.urls;
                        const $list = $('#bulk-assign-url-list');

                        if (urls.length === 0) {
                            $list.html('<div style="padding: 20px; text-align: center; color: var(--schemafy-gray-500);">No URLs found</div>');
                            return;
                        }

                        // Group by post type
                        const groups = {};
                        urls.forEach(item => {
                            const group = item.post_type_label || 'Other';
                            if (!groups[group]) groups[group] = [];
                            groups[group].push(item);
                        });

                        let html = '';
                        Object.entries(groups).forEach(([group, items]) => {
                            html += `<div style="padding: 6px 12px; background: var(--schemafy-gray-100); font-size: 11px; font-weight: 700; color: var(--schemafy-gray-600); text-transform: uppercase; letter-spacing: 0.5px; border-bottom: 1px solid var(--schemafy-gray-200);">${window.SchemafyUtilities.escapeHtml(group)}</div>`;
                            items.forEach(item => {
                                const safeTitle = window.SchemafyUtilities.escapeHtml(item.title);
                                const safeUrl = window.SchemafyUtilities.escapeHtml(item.url);
                                html += `
                                    <div class="schemafy-assign-url-item" data-url="${item.url.replace(/"/g, '&quot;')}" style="padding: 10px 12px; border-bottom: 1px solid var(--schemafy-gray-100); cursor: pointer; transition: background 0.15s;">
                                        <div style="font-weight: 500; font-size: 13px; color: var(--schemafy-gray-800);">${safeTitle}</div>
                                        <div style="font-size: 12px; color: var(--schemafy-gray-500); margin-top: 2px; word-break: break-all;">${safeUrl}</div>
                                    </div>
                                `;
                            });
                        });

                        $list.html(html);

                        // Click to select URL
                        $list.on('click', '.schemafy-assign-url-item', function() {
                            $list.find('.schemafy-assign-url-item').css({ background: '', borderLeft: '' });
                            $(this).css({ background: 'var(--schemafy-gray-50)', borderLeft: '3px solid var(--schemafy-primary)' });
                            $('#bulk-assign-selected-url').val($(this).data('url'));
                            $('#schemafy-bulk-assign-apply').prop('disabled', false);
                        });
                    } else {
                        $('#bulk-assign-url-list').html('<div style="padding: 20px; text-align: center; color: var(--schemafy-danger);">Error loading URLs</div>');
                    }
                },
                error: () => {
                    $('#bulk-assign-url-list').html('<div style="padding: 20px; text-align: center; color: var(--schemafy-danger);">Connection error</div>');
                }
            });
        },

        /**
         * Apply bulk URL assignment
         */
        applyBulkUrlAssignment: function(ids, url) {
            window.SchemafyUtilities.showNotification(`Updating URLs for ${ids.length} schema(s)...`, 'info');

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_bulk_assign_urls',
                    nonce: schemafy_ajax.nonce,
                    schema_ids: ids,
                    value: url
                },
                success: (response) => {
                    if (response.success) {
                        const updated = response.data?.updated || ids.length;
                        window.SchemafyUtilities.showNotification(`Successfully assigned ${updated} schema(s) to new URL`, 'success');
                        this.loadBulkSchemas();
                        if (window.SchemafyDashboard && typeof window.SchemafyDashboard.refreshStats === 'function') {
                            window.SchemafyDashboard.refreshStats();
                        }
                    } else {
                        window.SchemafyUtilities.showNotification(response.data?.message || 'Error assigning URLs', 'error');
                    }
                },
                error: () => {
                    window.SchemafyUtilities.showNotification('Network error while assigning URLs', 'error');
                }
            });
        },

        /**
         * Update bulk stats display
         */
        updateBulkStats: function(schemas) {
            if (!schemas || schemas.length === 0) {
                // Reset all stats to zero when no schemas remain
                $('#stat-total').text('0');
                $('#stat-active').text('0');
                $('#stat-active-percent').text('0% of total');
                $('#stat-inactive').text('0');
                $('#stat-inactive-percent').text('0% of total');
                $('#stat-types').text('0');
                $('#stat-types-list').text('No types');
                $('#stat-active-rate').text('—');
                $('#stat-active-rate-bar').css('width', '0%');
                $('#schemafy-type-bars').empty();
                $('#schemafy-type-distribution').slideUp(200);
                return;
            }

            const total = schemas.length;
            const active = schemas.filter(s => s.is_active == 1).length;
            const inactive = total - active;

            const activePercent = ((active / total) * 100).toFixed(0);
            const inactivePercent = ((inactive / total) * 100).toFixed(0);

            const typeCount = {};
            schemas.forEach(schema => {
                try {
                    const data = JSON.parse(schema.schema_data);
                    const type = data['@type'] || 'Unknown';
                    typeCount[type] = (typeCount[type] || 0) + 1;
                } catch (e) {
                    typeCount['Invalid'] = (typeCount['Invalid'] || 0) + 1;
                }
            });

            const uniqueTypes = Object.keys(typeCount).length;
            const topTypes = Object.entries(typeCount)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 3)
                .map(([type]) => type)
                .join(', ');

            $('#stat-total').text(total);
            $('#stat-active').text(active);
            $('#stat-active-percent').text(`${activePercent}% of total`);
            $('#stat-inactive').text(inactive);
            $('#stat-inactive-percent').text(`${inactivePercent}% of total`);
            $('#stat-types').text(uniqueTypes);
            $('#stat-types-list').text(topTypes || 'No types');
            // Active Rate visible stat + progress bar
            $('#stat-active-rate').text(activePercent + '%');
            $('#stat-active-rate-bar').css('width', activePercent + '%')
                .css('background', activePercent >= 80 ? '#22c55e' : activePercent >= 50 ? '#f59e0b' : '#ef4444');

            this.renderTypeDistribution(typeCount, total);
        },

        /**
         * Render type distribution bars
         */
        renderTypeDistribution: function(typeCount, total) {
            const sorted = Object.entries(typeCount).sort((a, b) => b[1] - a[1]);
            if (sorted.length === 0) return;

            const colors = ['#5f70de', '#0d9488', '#7882e4', '#7a8ae9', '#3730a3', '#14b8a6', '#14b8a6', '#3730a3', '#4338ca', '#0369a1'];

            let barsHtml = '';
            sorted.forEach(([type, count], index) => {
                const percentage = ((count / total) * 100).toFixed(1);
                const color = colors[index % colors.length];

                barsHtml += `
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="flex: 0 0 120px; font-size: 13px; font-weight: 600; color: var(--schemafy-gray-700);">${type}</div>
                        <div style="flex: 1; position: relative; height: 32px; background: var(--schemafy-gray-100); border-radius: 6px; overflow: hidden;">
                            <div style="position: absolute; left: 0; top: 0; height: 100%; width: ${percentage}%; background: ${color};"></div>
                            <div style="position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; align-items: center; padding: 0 12px; font-size: 12px; font-weight: 600;">
                                ${count} schema${count !== 1 ? 's' : ''} (${percentage}%)
                            </div>
                        </div>
                    </div>
                `;
            });

            $('#schemafy-type-bars').html(barsHtml);
            $('#schemafy-type-distribution').slideDown(300);
        },

        /**
         * Refresh health stats
         */
        refreshBulkHealthStats: function() {
            $('#bulk-health-coverage, #bulk-health-valid, #bulk-health-errors, #bulk-health-orphans').text('...');

            $.ajax({
                url: schemafy_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'schemafy_get_bulk_health_stats',
                    nonce: schemafy_ajax.nonce
                },
                success: (response) => {
                    if (response.success) {
                        const data = response.data;
                        $('#bulk-health-coverage').text(data.coverage + '%');
                        $('#bulk-health-valid').text(data.valid);
                        $('#bulk-health-errors').text(data.errors);
                        $('#bulk-health-orphans').text(data.orphans);
                    }
                },
                error: () => {
                    $('#bulk-health-coverage, #bulk-health-valid, #bulk-health-errors, #bulk-health-orphans').text('--');
                }
            });
        }
    };

})(jQuery);
