/**
 * Custom Schema SCHEMAFY - V2 Enhancements Integration
 * Version: 1.0.0
 *
 * Integrates all new functionalities into the V2 admin interface:
 * - JSON Validator
 * - Variables Dropdown
 * - Bulk Selector
 * - Schema Expander
 * - Toast Notifications
 */

(function($) {
    'use strict';

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

    /**
     * Initialize all enhancements for V2 admin
     */
    window.SCHEMAFY.initV2Enhancements = function() {

        // Wait for DOM to be fully loaded
        $(document).ready(function() {
            initAIPasteEnhancements();
            initManualEditorEnhancements();
            initBulkManagerEnhancements();
            initDashboardEnhancements();
            replaceAlertsWithNotifications();

        });
    };

    /**
     * Initialize AI Paste Tab Enhancements
     */
    function initAIPasteEnhancements() {
        const $aiJson = $('#schemafy-ai-json');
        if (!$aiJson.length) return;


        // 1. JSON Validator
        const aiValidator = SCHEMAFY.initJSONValidator('schemafy-ai-json', {
            validateOnType: true,
            debounceDelay: 400,
            onValid: function(parsed) {
                const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
                // Update validation status
                $('#schemafy-ai-validation-status')
                    .removeClass('schemafy-validation-error')
                    .addClass('schemafy-validation-success')
                    .html(i18n.valid_json_ready || '✓ Valid JSON - Ready to save');
            },
            onInvalid: function(error) {
                const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
                // Update validation status
                $('#schemafy-ai-validation-status')
                    .removeClass('schemafy-validation-success')
                    .addClass('schemafy-validation-error')
                    .html((i18n.invalid_json_prefix || '✗ Invalid JSON: ') + error.message);
            }
        });

        // 2. Hook format button to use JSON validator
        $('#schemafy-ai-format').off('click').on('click', function(e) {
            e.preventDefault();
            const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
            if (aiValidator.format()) {
                SCHEMAFY.showSuccess(i18n.json_formatted_success || 'JSON formatted successfully!');
            } else {
                SCHEMAFY.showError(i18n.cannot_format_json || 'Cannot format invalid JSON');
            }
        });

        // 3. Hook validate button
        $('#schemafy-ai-validate').off('click').on('click', function(e) {
            e.preventDefault();
            const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
            const result = aiValidator.validate();
            if (result.valid) {
                SCHEMAFY.showSuccess(i18n.json_is_valid || 'JSON is valid!');
            } else {
                SCHEMAFY.showError(i18n.json_validation_failed || 'JSON validation failed');
            }
        });

    }

    /**
     * Initialize Manual Editor Tab Enhancements
     */
    function initManualEditorEnhancements() {
        const $manualJson = $('#schemafy-manual-json');
        if (!$manualJson.length) return;


        // 1. JSON Validator with live preview
        const manualValidator = SCHEMAFY.initJSONValidator('schemafy-manual-json', {
            validateOnType: true,
            debounceDelay: 400,
            onValid: function(parsed) {
                // Show success indicator
                showManualValidationStatus('valid');
            },
            onInvalid: function(error) {
                // Show error indicator
                showManualValidationStatus('invalid', error.message);
            }
        });

        // 2. Variables Dropdown
        // Create insert button if it doesn't exist
        let $insertVarBtn = $('#schemafy-insert-variable-btn');
        if (!$insertVarBtn.length) {
            $insertVarBtn = $('<button type="button" class="schemafy-btn-mini" id="schemafy-insert-variable-btn">' +
                '<span class="dashicons dashicons-editor-code"></span> Insert Variable</button>');

            // Insert button only in the Manual JSON toolbar (not AI Generator)
            const $toolbar = $('#schemafy-manual-form .schemafy-editor-toolbar-v2');
            if ($toolbar.length) {
                $toolbar.append($insertVarBtn);
            }
        }

        // Initialize variables dropdown
        SCHEMAFY.initVariablesDropdown('schemafy-manual-json', 'schemafy-insert-variable-btn');

        // 3. Hook format button
        $('#schemafy-manual-format').off('click').on('click', function(e) {
            e.preventDefault();
            const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
            if (manualValidator.format()) {
                SCHEMAFY.showSuccess(i18n.json_formatted_short || 'JSON formatted!');
            } else {
                SCHEMAFY.showError(i18n.cannot_format_json || 'Cannot format invalid JSON');
            }
        });

        // 4. The validate button is handled by SchemafyValidation, delegated on
        // document in admin-modular.js. Binding a second handler here ran both
        // on one click: this one only reparses the JSON, so it reported success
        // while the structural check reported an error about the same content.
        // The inline indicator and preview stay current regardless — the
        // validator already runs on the textarea's input and blur events.

        // 5. Keep existing insert variable buttons functional
        $('#schemafy-manual-insert-meta-title').on('click', function(e) {
            e.preventDefault();
            insertAtCursor($manualJson[0], '{{meta_title}}');
            SCHEMAFY.showInfo('{{meta_title}} inserted');
        });

        $('#schemafy-manual-insert-meta-desc').on('click', function(e) {
            e.preventDefault();
            insertAtCursor($manualJson[0], '{{meta_description}}');
            SCHEMAFY.showInfo('{{meta_description}} inserted');
        });

    }

    /**
     * Initialize Bulk Manager Tab Enhancements
     */
    function initBulkManagerEnhancements() {

        // Wait for bulk schemas to be loaded first
        $(document).on('schemafy:bulk-schemas-loaded', function() {
            const $bulkList = $('#schemafy-bulk-list');
            if (!$bulkList.length) return;

            // 1. Schema Expander for bulk list
            const expander = SCHEMAFY.initSchemaExpander('schemafy-bulk-list', {
                onExpand: function(element) {
                },
                onCollapse: function(element) {
                }
            });

            // 2. Add Expand/Collapse All buttons if not exist
            const $bulkHeader = $('#schemafy-tab-bulk .schemafy-card-header-v2');
            if ($bulkHeader.length && !$('#schemafy-expand-all-btn').length) {
                const $expandAllBtn = $('<button type="button" class="schemafy-btn-mini" id="schemafy-expand-all-btn">' +
                    '<span class="dashicons dashicons-arrow-down"></span> Expand All</button>');
                const $collapseAllBtn = $('<button type="button" class="schemafy-btn-mini" id="schemafy-collapse-all-btn">' +
                    '<span class="dashicons dashicons-arrow-up"></span> Collapse All</button>');

                const $actions = $bulkHeader.find('.schemafy-card-actions');
                if ($actions.length) {
                    $actions.append($expandAllBtn);
                    $actions.append($collapseAllBtn);
                }

                // Bind events
                $expandAllBtn.on('click', function(e) {
                    e.preventDefault();
                    const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
                    expander.expandAll();
                    SCHEMAFY.showInfo(i18n.schemas_expanded || 'All schemas expanded');
                });

                $collapseAllBtn.on('click', function(e) {
                    e.preventDefault();
                    const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
                    expander.collapseAll();
                    SCHEMAFY.showInfo(i18n.schemas_collapsed || 'All schemas collapsed');
                });
            }

        });
    }

    /**
     * Initialize Dashboard Enhancements
     */
    function initDashboardEnhancements() {

        // Wait for URL map to be loaded
        $(document).on('schemafy:url-map-loaded', function() {
            const $urlMap = $('#schemafy-url-map-list');
            if (!$urlMap.length) return;

            // Schema Expander for dashboard URL map
            SCHEMAFY.initSchemaExpander('schemafy-url-map-list', {
                expandIcon: '▶',
                collapseIcon: '▼'
            });

        });
    }

    /**
     * Replace all alerts with toast notifications
     */
    function replaceAlertsWithNotifications() {
        // Override window.alert (use with caution)
        const originalAlert = window.alert;
        window.alert = function(message) {
            if (typeof SCHEMAFY.showInfo === 'function') {
                SCHEMAFY.showInfo(message);
            } else {
                originalAlert(message);
            }
        };

    }

    /**
     * Helper: Show manual editor validation status
     */
    function showManualValidationStatus(status, message) {
        // Use the existing validation status element in the template
        let $status = $('#schemafy-validation-status');

        if (!$status.length) {
            // Element not found - just use notifications instead
            console.warn('[SCHEMAFY] Validation status element not found');
            return;
        }

        const $badge = $status.find('.schemafy-validation-badge');
        const $msg = $status.find('.schemafy-validation-message');

        const i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
        if (status === 'valid') {
            $status.removeClass('error').addClass('success').show();
            if ($badge.length) $badge.text(i18n.valid_badge || 'Valid');
            if ($msg.length) $msg.html('<strong>Perfect!</strong> Your JSON-LD schema is valid and ready to use.');
        } else {
            $status.removeClass('success').addClass('error').show();
            if ($badge.length) $badge.text(i18n.invalid_badge || 'Invalid');
            if ($msg.length) $msg.html('<strong>Syntax Error:</strong> ' + (message || 'Unknown error'));
        }
    }

    /**
     * Helper: Insert text at cursor position
     */
    function insertAtCursor(element, text) {
        if (element.tagName === 'TEXTAREA' || element.tagName === 'INPUT') {
            const startPos = element.selectionStart;
            const endPos = element.selectionEnd;
            const value = element.value;

            element.value = value.substring(0, startPos) + text + value.substring(endPos);

            // Move cursor after inserted text
            const newPos = startPos + text.length;
            element.setSelectionRange(newPos, newPos);
            element.focus();

            // Trigger input event for validation
            $(element).trigger('input');
        }
    }

    /**
     * Public API for AJAX success handlers
     */
    window.SCHEMAFY.handleSaveSuccess = function(response, formId) {
        // Hide loading notification if exists
        const $form = $('#' + formId);
        const loadingId = $form.data('loading-id');
        if (loadingId) {
            SCHEMAFY.hideLoading(loadingId);
        }

        // Show success notification
        SCHEMAFY.showSuccess(response.message || 'Schema saved successfully!', 4000);

        // Reset form if needed
        if ($form.length) {
            $form[0].reset();
        }
    };

    window.SCHEMAFY.handleSaveError = function(xhr, formId) {
        // Hide loading notification if exists
        const $form = $('#' + formId);
        const loadingId = $form.data('loading-id');
        if (loadingId) {
            SCHEMAFY.hideLoading(loadingId);
        }

        // Show error notification
        const errorMessage = xhr.responseJSON?.message || 'An error occurred while saving';
        SCHEMAFY.showError(errorMessage, 5000);
    };

    /**
     * Public API for delete confirmation
     */
    window.SCHEMAFY.confirmDelete = function(schemaName, callback) {
        SCHEMAFY.confirm(
            'Are you sure you want to delete "' + schemaName + '"?',
            {
                confirmText: 'Yes, Delete',
                cancelText: 'Cancel',
                type: 'warning'
            }
        ).then(function(confirmed) {
            if (confirmed && typeof callback === 'function') {
                callback();
            }
        });
    };

    /**
     * Plugin Compatibility Settings handler
     */
    $(document).on('click', '#schemafy-save-compatibility', function() {
        var $btn = $(this);
        var originalHtml = $btn.html();
        var settings = {};

        $('.schemafy-compat-toggle').each(function() {
            settings[$(this).data('key')] = $(this).is(':checked') ? 1 : 0;
        });

        $btn.prop('disabled', true).html('<span class="dashicons dashicons-update-alt schemafy-spin"></span> Saving...');

        $.ajax({
            url: schemafy_ajax.ajax_url,
            type: 'POST',
            data: {
                action: 'schemafy_save_compatibility',
                nonce: schemafy_ajax.nonce,
                settings: settings
            },
            success: function(response) {
                if (response.success) {
                    if (window.SchemafyUtilities && typeof window.SchemafyUtilities.showNotification === 'function') {
                        window.SchemafyUtilities.showNotification(response.data.message || 'Settings saved', 'success');
                    }
                } else {
                    if (window.SchemafyUtilities && typeof window.SchemafyUtilities.showNotification === 'function') {
                        window.SchemafyUtilities.showNotification(response.data || 'Error saving settings', 'error');
                    }
                }
                $btn.prop('disabled', false).html(originalHtml);
            },
            error: function() {
                if (window.SchemafyUtilities && typeof window.SchemafyUtilities.showNotification === 'function') {
                    window.SchemafyUtilities.showNotification('Network error', 'error');
                }
                $btn.prop('disabled', false).html(originalHtml);
            }
        });
    });

    // Auto-initialize when script loads

})(jQuery);
