/**
 * Custom Schema by SCHEMAFY - JSON Validator
 * Version: 1.0.0
 * Real-time JSON validation and preview
 * Depends on: admin-utils.js
 */

(function() {
    'use strict';

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

    /**
     * Initialize JSON validator for a textarea
     * @param {string} textareaId - ID of the textarea
     * @param {object} options - Configuration options
     */
    window.SCHEMAFY.initJSONValidator = function(textareaId, options) {
        var settings = jQuery.extend({
            showLineNumbers: false,
            validateOnType: true,
            debounceDelay: 300,
            previewElementId: null,
            onValid: null,
            onInvalid: null
        }, options);

        var $textarea = jQuery('#' + textareaId);
        if (!$textarea.length) {
            console.warn('[SCHEMAFY Validator] Textarea not found:', textareaId);
            return;
        }

        var $wrapper = $textarea.parent();
        var validationTimeout = null;

        // Create validation indicator - insert after the wrapper, not inside the code editor
        var $validationIndicator = jQuery('<div class="schemafy-json-validation"></div>');
        var $errorMessage = jQuery('<div class="schemafy-json-error" style="display:none;"></div>');

        // Find the proper container to insert after (outside the dark code editor area)
        var $editorWrapper = $textarea.closest('.schemafy-json-editor-wrapper-enhanced');
        if ($editorWrapper.length) {
            $editorWrapper.after($errorMessage);
            $editorWrapper.after($validationIndicator);
        } else {
            // Fallback: insert after textarea's parent container
            var $container = $textarea.closest('.schemafy-code-editor-container');
            if ($container.length) {
                $container.after($errorMessage);
                $container.after($validationIndicator);
            } else {
                $textarea.after($errorMessage);
                $textarea.after($validationIndicator);
            }
        }

        /**
         * Validate JSON and update UI
         */
        function validateJSON() {
            var value = $textarea.val().trim();

            // Strip <script type="application/ld+json">...</script> wrapper if pasted from page source
            var scriptMatch = value.match(/^<script[^>]*>([\s\S]*?)<\/script>\s*$/i);
            if (scriptMatch) {
                value = scriptMatch[1].trim();
                $textarea.val(value);
            }

            if (!value) {
                $validationIndicator.removeClass('valid invalid').html('');
                $errorMessage.hide();
                return { valid: true, data: null };
            }

            try {
                var parsed = JSON.parse(value);

                // Valid JSON
                var i18n = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
                $validationIndicator
                    .removeClass('invalid')
                    .addClass('valid')
                    .html(i18n.valid_json_indicator || '✓ Valid JSON');

                $errorMessage.hide();

                // Update preview if configured
                if (settings.previewElementId) {
                    updatePreview(parsed);
                }

                // Callback
                if (typeof settings.onValid === 'function') {
                    settings.onValid(parsed);
                }

                return { valid: true, data: parsed };

            } catch (e) {
                // Invalid JSON
                var i18nInv = (typeof schemafy_ajax !== 'undefined' && schemafy_ajax.i18n) ? schemafy_ajax.i18n : {};
                $validationIndicator
                    .removeClass('valid')
                    .addClass('invalid')
                    .html(i18nInv.invalid_json_indicator || '✗ Invalid JSON');

                $errorMessage
                    .show()
                    .html('<strong>Error:</strong> ' + e.message);

                // Callback
                if (typeof settings.onInvalid === 'function') {
                    settings.onInvalid(e);
                }

                return { valid: false, error: e };
            }
        }

        /**
         * Update live preview with syntax highlighting
         */
        function updatePreview(data) {
            var $preview = jQuery('#' + settings.previewElementId);
            if (!$preview.length) return;

            var formatted = JSON.stringify(data, null, 2);
            var highlighted = syntaxHighlight(formatted);

            $preview.html(highlighted);
        }

        /**
         * Syntax highlighting for JSON
         */
        function syntaxHighlight(json) {
            json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
            return json.replace(
                /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
                function(match) {
                    var cls = 'json-number';
                    if (/^"/.test(match)) {
                        if (/:$/.test(match)) {
                            cls = 'json-key';
                        } else {
                            cls = 'json-string';
                        }
                    } else if (/true|false/.test(match)) {
                        cls = 'json-boolean';
                    } else if (/null/.test(match)) {
                        cls = 'json-null';
                    }
                    return '<span class="' + cls + '">' + match + '</span>';
                }
            );
        }

        /**
         * Format JSON in textarea
         */
        window.SCHEMAFY.formatJSON = function(textareaId) {
            var $ta = jQuery('#' + textareaId);
            var value = $ta.val().trim();

            try {
                var parsed = JSON.parse(value);
                var formatted = JSON.stringify(parsed, null, 2);
                $ta.val(formatted);
                validateJSON();
                return true;
            } catch (e) {
                return false;
            }
        };

        /**
         * Minify JSON in textarea
         */
        window.SCHEMAFY.minifyJSON = function(textareaId) {
            var $ta = jQuery('#' + textareaId);
            var value = $ta.val().trim();

            try {
                var parsed = JSON.parse(value);
                var minified = JSON.stringify(parsed);
                $ta.val(minified);
                validateJSON();
                return true;
            } catch (e) {
                return false;
            }
        };

        // Event listeners
        if (settings.validateOnType) {
            $textarea.on('input', function() {
                clearTimeout(validationTimeout);
                validationTimeout = setTimeout(validateJSON, settings.debounceDelay);
            });
        }

        $textarea.on('blur', validateJSON);

        // Initial validation
        if ($textarea.val().trim()) {
            validateJSON();
        }


        return {
            validate: validateJSON,
            format: function() { return window.SCHEMAFY.formatJSON(textareaId); },
            minify: function() { return window.SCHEMAFY.minifyJSON(textareaId); }
        };
    };

})();
