/**
 * Schemafy Admin V2 - Modular Entry Point
 * This file initializes all modules and provides backward compatibility
 *
 * Module Architecture:
 * - core/init.js         : Tab management, sidebar, core initialization
 * - dashboard/dashboard.js: Stats, URL map, charts
 * - utilities/notifications.js: Notifications, confirmations, UI helpers
 * - bulk/bulk-manager.js : Bulk schema management
 * - bulk/filters.js      : Filtering, sorting, pagination
 * - operations/schema-crud.js: Edit, delete, toggle, duplicate
 * - operations/url-management.js: URL detail views
 * - editor/manual-editor.js: Manual JSON editor
 * - editor/validation.js : JSON and schema validation
 * - builder/smart-builder.js: Visual schema builder
 * - import-export/csv-handler.js: CSV import/export
 *
 * Paid tools live in modules/premium/*__premium_only.js (AI Generator,
 * AutoGenerator, bulk maintenance). They self-initialize and are absent from
 * the free WordPress.org package, so nothing here may reference them.
 */

(function($) {
    'use strict';

    // Main Admin Object - Provides backward compatibility with existing code
    window.SchemafyAdminV2 = {
        /**
         * Initialize all modules
         */
        init: function() {
            // Wait for DOM ready
            $(document).ready(() => {
                this.initializeModules();
                this.bindGlobalEvents();
                this.initBackwardCompatibility();
            });
        },

        /**
         * Initialize individual modules
         */
        initializeModules: function() {
            // Core initialization
            if (window.SchemafyCore) {
                window.SchemafyCore.init();
            }

            // Dashboard
            if (window.SchemafyDashboard) {
                window.SchemafyDashboard.loadDashboard();
            }

            // Filters event bindings
            if (window.SchemafyFilters) {
                window.SchemafyFilters.initFilterEvents();
            }

            // Editor initialization
            if (window.SchemafyEditor) {
                window.SchemafyEditor.initEnhancedManualEditor();
            }

            // Builder array field handlers
            if (window.SchemafyBuilder) {
                window.SchemafyBuilder.initArrayFieldHandlers();
            }

            // Sitemap settings
            if (window.SchemafySitemap) {
                window.SchemafySitemap.init();
            }

            // The AI Generator and AutoGenerator tabs are paid tools: they
            // self-initialize from assets/js/modules/premium/, which ships only
            // in the paid build.
        },


        /**
         * Bind global events
         */
        bindGlobalEvents: function() {
            const self = this;

            // ========== SMART BUILDER ==========
            $('.schemafy-schema-type-card').on('click', function(e) {
                // Cancellable seam so an optional module can veto a selection
                // without core knowing why.
                const before = $.Event('schemafy:before-select-type');
                $(document).trigger(before, [this]);
                if (before.isDefaultPrevented()) {
                    return;
                }
                if (window.SchemafyBuilder) {
                    window.SchemafyBuilder.selectSchemaType(e);
                }
            });

            // Category filter pills
            $(document).on('click', '.schemafy-category-btn', function() {
                if (window.SchemafyBuilder) {
                    window.SchemafyBuilder.selectCategory($(this).data('category'));
                }
            });

            // Toggle raw JSON preview panel
            $(document).on('click', '#schemafy-toggle-json-preview', function() {
                if (window.SchemafyBuilder) {
                    window.SchemafyBuilder.toggleJsonPreview();
                }
            });

            // URL chip changes also update the friendly preview
            $(document).on('click', '.schemafy-chip-remove, .schemafy-url-result', function() {
                setTimeout(function() {
                    if (window.SchemafyBuilder && typeof window.SchemafyBuilder.updateFriendlyPreview === 'function') {
                        window.SchemafyBuilder.updateFriendlyPreview();
                    }
                }, 50);
            });

            $('#schemafy-copy-json').on('click', function() {
                if (window.SchemafyBuilder) {
                    window.SchemafyBuilder.copyJson();
                }
            });

            $('#schemafy-save-builder-schema').on('click', function() {
                if (window.SchemafyBuilder) {
                    window.SchemafyBuilder.saveBuilderSchema();
                }
            });

            // ========== MANUAL EDITOR ==========
            $(document).on('submit', '#schemafy-manual-form', function(e) {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.saveManualSchema(e);
                }
            });

            $(document).on('click', '#schemafy-manual-format', function() {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.formatJson('#schemafy-manual-json');
                }
            });

            $(document).on('click', '#schemafy-manual-validate', function() {
                if (window.SchemafyValidation) {
                    window.SchemafyValidation.validateJsonEnhanced();
                }
            });

            $(document).on('click', '#schemafy-manual-minify', function() {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.minifyJson('#schemafy-manual-json');
                }
            });

            $(document).on('change', '#schemafy-manual-url', function(e) {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.handleUrlSelection(e);
                }
            });

            $(document).on('input', '#schemafy-manual-json', function() {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.updateEditorStats();
                    window.SchemafyEditor.runRealtimeValidation();
                }
            });

            // ========== VARIABLES PANEL ==========
            $(document).on('click', '#schemafy-toggle-variables-panel', function(e) {
                e.preventDefault();
                e.stopPropagation();
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.toggleVariablesPanel();
                }
            });

            $(document).on('click', '.schemafy-variable-btn', function(e) {
                e.preventDefault();
                e.stopPropagation();
                const variable = $(this).attr('data-variable');
                if (variable && window.SchemafyEditor) {
                    // Determine which JSON editor is currently active
                    const target = $('#schemafy-ai-json').is(':visible') ? '#schemafy-ai-json' : '#schemafy-manual-json';
                    window.SchemafyEditor.insertVariable(target, variable);
                    if (window.SchemafyUtilities) {
                        window.SchemafyUtilities.showNotification('Variable inserted: ' + variable, 'success');
                    }
                }
            });

            // ========== MANUAL JSON REDESIGN ==========
            // Copy button
            $(document).on('click', '#schemafy-manual-copy', function() {
                if (window.SchemafyEditor) {
                    const $btn = $(this);
                    window.SchemafyEditor.copyJson('#schemafy-manual-json');
                    $btn.addClass('copied').find('.dashicons').removeClass('dashicons-clipboard').addClass('dashicons-yes');
                    setTimeout(function() {
                        $btn.removeClass('copied').find('.dashicons').removeClass('dashicons-yes').addClass('dashicons-clipboard');
                    }, 1800);
                }
            });

            // Template picker toggle
            $(document).on('click', '#schemafy-template-trigger', function(e) {
                e.stopPropagation();
                const $btn = $(this);
                const $drop = $('#schemafy-template-dropdown');
                const isOpen = $drop.is(':visible');
                $drop.toggle(!isOpen);
                $btn.toggleClass('open', !isOpen);
                $btn.attr('aria-expanded', !isOpen);
            });

            // Template item click — insert and close dropdown
            $(document).on('click', '.schemafy-mj-tpl-item', function() {
                const key = $(this).data('template');
                if (key && window.SchemafyEditor) {
                    window.SchemafyEditor.insertTemplate(key);
                }
                $('#schemafy-template-dropdown').hide();
                $('#schemafy-template-trigger').removeClass('open').attr('aria-expanded', 'false');
            });

            // Close template dropdown when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.schemafy-mj-tpl-wrap').length) {
                    $('#schemafy-template-dropdown').hide();
                    $('#schemafy-template-trigger').removeClass('open').attr('aria-expanded', 'false');
                }
            });

            // Clear editor button
            $(document).on('click', '#schemafy-manual-clear', function() {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.clearEditor('#schemafy-manual-json');
                }
            });

            // Cancel edit mode
            $(document).on('click', '#schemafy-manual-cancel-edit', function() {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.resetManualForm($('#schemafy-manual-form'));
                }
            });

            // ========== BULK MANAGER FILTERS ==========
            // Prevent Enter key from causing form submission or page reload in Rich Snippets tab
            $(document).on('keydown', '#schemafy-bulk-search', function(e) {
                if (e.key === 'Enter' || e.keyCode === 13) {
                    e.preventDefault();
                    if (window.SchemafyFilters) {
                        window.SchemafyFilters.applyBulkFilters();
                    }
                }
            });

            let searchTimeout = null;
            $(document).on('input', '#schemafy-bulk-search', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(function() {
                    if (window.SchemafyFilters) {
                        window.SchemafyFilters.applyBulkFilters();
                    }
                }, 300);
            });

            $(document).on('change', '#schemafy-bulk-filter-type', function() {
                if (window.SchemafyFilters) {
                    window.SchemafyFilters.applyBulkFilters();
                }
            });

            $(document).on('change', '#schemafy-bulk-filter-status', function() {
                if (window.SchemafyFilters) {
                    window.SchemafyFilters.applyBulkFilters();
                }
            });

            $(document).on('change', '#schemafy-bulk-filter-date', function() {
                if (window.SchemafyFilters) {
                    window.SchemafyFilters.applyBulkFilters();
                }
            });

            $(document).on('change', '#schemafy-bulk-sort', function(e) {
                if (window.SchemafyFilters) {
                    window.SchemafyFilters.sortBulkSchemas(e.target.value);
                }
            });

            $(document).on('change', '#schemafy-bulk-per-page', function(e) {
                if (window.SchemafyFilters) {
                    window.SchemafyFilters.changeBulkPerPage(e.target.value);
                }
            });

            $(document).on('click', '#schemafy-bulk-clear-filters', function() {
                if (window.SchemafyFilters) {
                    window.SchemafyFilters.clearBulkFilters();
                }
            });

            $(document).on('click', '#schemafy-bulk-export-csv', function() {
                if (window.SchemafyCsvExport) {
                    window.SchemafyCsvExport.exportSchemasCSV();
                }
            });

            $(document).on('click', '#schemafy-bulk-import-csv', function() {
                if (window.SchemafyCsvExport) {
                    window.SchemafyCsvExport.showImportModal();
                }
            });

            $(document).on('click', '#schemafy-csv-help', function() {
                if (window.SchemafyCsvExport) {
                    window.SchemafyCsvExport.showCSVHelpModal();
                }
            });

            // ========== QUICK ACTIONS PANEL ==========
            $(document).on('click', '#schemafy-bulk-validate-all', function() {
                if (window.SchemafyValidation) {
                    window.SchemafyValidation.validateAllSchemas();
                }
            });

            // Fix Errors / Clean Orphans / Remove Duplicates / Clean Embedded are
            // paid tools: their buttons and their handlers ship only in the paid
            // build (assets/js/modules/premium/quick-actions__premium_only.js).

            $(document).on('click', '#schemafy-bulk-refresh-health', function() {
                if (window.SchemafyBulk) {
                    window.SchemafyBulk.refreshBulkHealthStats();
                }
            });

            // Dashboard header refresh buttons (icon + labeled)
            $(document).on('click', '#schemafy-refresh-stats, #schemafy-refresh-dashboard', function() {
                if (window.SchemafyDashboard) {
                    window.SchemafyDashboard.loadDashboard();
                }
            });

            // ========== UI TOGGLES ==========
            $(document).on('click', '#schemafy-toggle-tools', function() {
                if (window.SchemafyCore) {
                    window.SchemafyCore.toggleToolsPanel();
                }
            });

            $(document).on('click', '#schemafy-toggle-more-filters', function() {
                if (window.SchemafyCore) {
                    window.SchemafyCore.toggleExtendedFilters();
                }
            });

            // Note: Sidebar toggle is handled in init.js to avoid duplicate handlers

            // ========== DASHBOARD ==========
            $(document).on('keydown', '#schemafy-url-map-search', function(e) {
                if (e.key === 'Enter' || e.keyCode === 13) {
                    e.preventDefault();
                    if (window.SchemafyDashboard) {
                        window.SchemafyDashboard.filterUrlMap($(this).val());
                    }
                }
            });

            let dashboardSearchTimeout = null;
            $(document).on('input', '#schemafy-url-map-search', function() {
                const val = $(this).val();
                clearTimeout(dashboardSearchTimeout);
                dashboardSearchTimeout = setTimeout(function() {
                    if (window.SchemafyDashboard) {
                        window.SchemafyDashboard.filterUrlMap(val);
                    }
                }, 400);
            });

            $('#schemafy-dashboard-export-csv').on('click', function() {
                if (window.SchemafyCsvExport) {
                    window.SchemafyCsvExport.exportSchemasCSV();
                }
            });

            $('#schemafy-dashboard-import-csv').on('click', function() {
                if (window.SchemafyCsvExport) {
                    window.SchemafyCsvExport.showImportModal();
                }
            });
        },

        /**
         * Backward compatibility methods
         * These proxy to the appropriate modules for code that still uses SchemafyAdminV2.method()
         */
        initBackwardCompatibility: function() {
            const self = this;

            // Proxy common methods to modules
            this.showNotification = function(message, type) {
                if (window.SchemafyUtilities) {
                    window.SchemafyUtilities.showNotification(message, type);
                }
            };

            this.confirm = function(message, onConfirm, onCancel) {
                if (window.SchemafyUtilities) {
                    window.SchemafyUtilities.confirm(message, onConfirm, onCancel);
                }
            };

            this.loadBulkSchemas = function() {
                if (window.SchemafyBulk) {
                    window.SchemafyBulk.loadBulkSchemas();
                }
            };

            this.editSchema = function(id) {
                if (window.SchemafyOperations) {
                    window.SchemafyOperations.editSchema(id);
                }
            };

            this.deleteSchema = function(id) {
                if (window.SchemafyOperations) {
                    window.SchemafyOperations.deleteSchema(id);
                }
            };

            this.toggleSchema = function(id) {
                if (window.SchemafyOperations) {
                    window.SchemafyOperations.toggleSchema(id);
                }
            };

            this.loadUrlDetailViewInBulk = function(url) {
                if (window.SchemafyUrlManager) {
                    window.SchemafyUrlManager.loadUrlDetailViewInBulk(url);
                }
            };

            this.closeUrlDetailViewInBulk = function() {
                if (window.SchemafyUrlManager) {
                    window.SchemafyUrlManager.closeUrlDetailViewInBulk();
                }
            };

            this.refreshStats = function() {
                if (window.SchemafyDashboard) {
                    window.SchemafyDashboard.refreshStats();
                }
            };

            this.applyBulkFilters = function() {
                if (window.SchemafyFilters) {
                    window.SchemafyFilters.applyBulkFilters();
                }
            };

            this.formatJson = function(selector) {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.formatJson(selector);
                }
            };

            this.validateJson = function(selector) {
                if (window.SchemafyValidation) {
                    window.SchemafyValidation.validateJson(selector);
                }
            };

            this.getFormData = function($form) {
                if (window.SchemafyUtilities) {
                    return window.SchemafyUtilities.getFormData($form);
                }
                return {};
            };

            this.updateLineNumbers = function() {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.updateLineNumbers();
                }
            };

            this.updateEditorStats = function() {
                if (window.SchemafyEditor) {
                    window.SchemafyEditor.updateEditorStats();
                }
            };

            this.showSnippetEditor = function(id, url) {
                if (window.SchemafyOperations) {
                    if (id) {
                        window.SchemafyOperations.editSchema(id);
                    } else if (url) {
                        $('[data-tab="manual"]').trigger('click');
                        setTimeout(() => {
                            if (window.SchemafyEditor && typeof window.SchemafyEditor.addManualUrlChip === 'function') {
                                window.SchemafyEditor.addManualUrlChip(url);
                            }
                        }, 200);
                    }
                }
            };

            this.allBulkSchemas = [];
            Object.defineProperty(this, 'allBulkSchemas', {
                get: function() {
                    return window.SchemafyBulk ? window.SchemafyBulk.allBulkSchemas : [];
                }
            });
        }
    };

    // Auto-initialize
    window.SchemafyAdminV2.init();

    // Export global utilities for use by other scripts (backward compatibility)
    window.SCHEMAFY = window.SCHEMAFY || {};
    window.SCHEMAFY.showNotification = function(message, type) {
        if (window.SchemafyUtilities) {
            window.SchemafyUtilities.showNotification(message, type);
        }
    };
    window.SCHEMAFY.confirm = function(message, onConfirm, onCancel) {
        // If called with callback style (message, fn, fn) — delegate directly
        if (typeof onConfirm === 'function') {
            if (window.SchemafyUtilities) {
                window.SchemafyUtilities.confirm(message, onConfirm, onCancel);
            }
            return;
        }
        // If called with Promise style (message, options) — return a Promise
        return new Promise(function(resolve) {
            if (window.SchemafyUtilities) {
                window.SchemafyUtilities.confirm(message, function() {
                    resolve(true);
                }, function() {
                    resolve(false);
                });
            } else {
                resolve(window.confirm(message));
            }
        });
    };

})(jQuery);
