/**
 * Schema Builder - JSON Editor Mode
 *
 * Simple JSON editor without Monaco to avoid WordPress conflicts
 *
 * @package CustomSchemaSchemafy
 * @since 2.0.0
 */

(function ($) {
    'use strict';

    window.SchemafyBuilder = window.SchemafyBuilder || {};

    /**
     * JSON Editor Handler
     */
    SchemafyBuilder.JSON = {

        /**
         * Textarea element
         */
        $textarea: null,

        /**
         * Container element
         */
        $container: null,

        /**
         * Initialization state
         */
        isInitialized: false,

        /**
         * Initialize JSON editor
         */
        init: function () {
            if (this.isInitialized) {
                return;
            }

            this.$container = $('#schemafy-json-editor');

            if (!this.$container.length) {
                console.warn('[SCHEMAFY] JSON editor container not found');
                return;
            }

            this.createEditor();
        },

        /**
         * Create textarea-based editor
         */
        createEditor: function () {
            const self = this;

            // Clear container and create textarea
            this.$container.empty();

            this.$textarea = $('<textarea>')
                .attr('id', 'schemafy-json-textarea')
                .css({
                    'width': '100%',
                    'height': '100%',
                    'min-height': '500px',
                    'font-family': 'Monaco, Menlo, "Ubuntu Mono", Consolas, monospace',
                    'font-size': '14px',
                    'line-height': '1.5',
                    'padding': '16px',
                    'border': 'none',
                    'resize': 'vertical',
                    'background': '#1e1e1e',
                    'color': '#d4d4d4',
                    'border-radius': '8px',
                    'tab-size': '2',
                    'white-space': 'pre',
                    'overflow-wrap': 'normal',
                    'overflow-x': 'auto'
                })
                .val('{\n  "@context": "https://schema.org",\n  "@type": "Article"\n}');

            this.$container.append(this.$textarea);

            // Bind events
            this.$textarea.on('input', function () {
                self.validateJSON();
            });

            // Handle tab key for indentation
            this.$textarea.on('keydown', function (e) {
                if (e.key === 'Tab') {
                    e.preventDefault();
                    const start = this.selectionStart;
                    const end = this.selectionEnd;
                    const value = $(this).val();

                    if (e.shiftKey) {
                        // Remove indent
                        const beforeCursor = value.substring(0, start);
                        const lineStart = beforeCursor.lastIndexOf('\n') + 1;
                        const lineContent = value.substring(lineStart, start);

                        if (lineContent.startsWith('  ')) {
                            $(this).val(value.substring(0, lineStart) + value.substring(lineStart + 2));
                            this.selectionStart = this.selectionEnd = start - 2;
                        }
                    } else {
                        // Add indent
                        $(this).val(value.substring(0, start) + '  ' + value.substring(end));
                        this.selectionStart = this.selectionEnd = start + 2;
                    }
                }
            });

            // Initial validation
            this.validateJSON();

            this.isInitialized = true;
        },

        /**
         * Show JSON editor with data
         */
        show: function (jsonData) {
            // Show JSON panel, hide visual panel
            $('#schemafy-visual-panel').hide();
            $('#schemafy-json-panel').show();

            if (!this.isInitialized) {
                this.init();
            }

            this.setValue(jsonData);
        },

        /**
         * Set editor value
         */
        setValue: function (jsonData) {
            if (!this.$textarea) {
                return;
            }

            const jsonString = typeof jsonData === 'string'
                ? jsonData
                : JSON.stringify(jsonData, null, 2);

            this.$textarea.val(jsonString);
            this.validateJSON();
        },

        /**
         * Get editor value
         */
        getValue: function () {
            if (!this.$textarea) {
                return {};
            }

            try {
                return JSON.parse(this.$textarea.val());
            } catch (e) {
                console.error('[SCHEMAFY] Invalid JSON:', e);
                return {};
            }
        },

        /**
         * Get raw editor value as string
         */
        getRawValue: function () {
            if (!this.$textarea) {
                return '';
            }
            return this.$textarea.val();
        },

        /**
         * Validate JSON in real-time
         */
        validateJSON: function () {
            if (!this.$textarea) {
                return;
            }

            const value = this.$textarea.val();
            const $validation = $('#schemafy-json-validation');

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

                // Check for schema.org essentials
                let warnings = [];
                if (!parsed['@context']) {
                    warnings.push('Missing @context (should be "https://schema.org")');
                }
                if (!parsed['@type']) {
                    warnings.push('Missing @type');
                }

                if (warnings.length > 0) {
                    $validation
                        .removeClass('error success')
                        .addClass('warning')
                        .html('⚠ Valid JSON but: ' + warnings.join(', '));
                    this.$textarea.css('border-color', '#7882e4');
                } else {
                    $validation
                        .removeClass('error warning')
                        .addClass('success')
                        .html('✓ Valid JSON-LD');
                    this.$textarea.css('border-color', '#0d9488');
                }

            } catch (e) {
                // Try to get line number from error
                let errorInfo = e.message;
                const posMatch = e.message.match(/position (\d+)/);
                if (posMatch) {
                    const pos = parseInt(posMatch[1]);
                    const lines = value.substring(0, pos).split('\n');
                    errorInfo = `Line ${lines.length}: ${e.message}`;
                }

                $validation
                    .removeClass('success warning')
                    .addClass('error')
                    .html('✕ ' + errorInfo);
                this.$textarea.css('border-color', '#3730a3');
            }
        },

        /**
         * Format JSON
         */
        format: function () {
            if (!this.$textarea) {
                console.warn('[SCHEMAFY] Editor not initialized');
                return;
            }

            try {
                const parsed = JSON.parse(this.$textarea.val());
                this.$textarea.val(JSON.stringify(parsed, null, 2));
                this.validateJSON();
            } catch (e) {
                alert('Cannot format: Invalid JSON\n' + e.message);
            }
        },

        /**
         * Copy JSON to clipboard
         */
        copy: function () {
            if (!this.$textarea) {
                console.warn('[SCHEMAFY] Editor not initialized');
                return;
            }

            const value = this.$textarea.val();

            if (navigator.clipboard) {
                navigator.clipboard.writeText(value).then(function() {
                    alert('JSON copied to clipboard!');
                }).catch(function(err) {
                    console.error('[SCHEMAFY] Failed to copy:', err);
                    // Fallback
                    SchemafyBuilder.JSON.copyFallback(value);
                });
            } else {
                this.copyFallback(value);
            }
        },

        /**
         * Fallback copy method
         */
        copyFallback: function (value) {
            const textarea = document.createElement('textarea');
            textarea.value = value;
            textarea.style.position = 'fixed';
            textarea.style.opacity = '0';
            document.body.appendChild(textarea);
            textarea.select();
            try {
                document.execCommand('copy');
                alert('JSON copied to clipboard!');
            } catch (err) {
                alert('Failed to copy. Please select and copy manually.');
            }
            document.body.removeChild(textarea);
        },

        /**
         * Validate against Schema.org
         */
        validateSchema: function () {
            const jsonData = this.getValue();

            if (!jsonData['@context']) {
                alert('Missing @context property (should be "https://schema.org")');
                return false;
            }

            if (!jsonData['@type']) {
                alert('Missing @type property');
                return false;
            }

            alert('Schema structure is valid! Use Google Rich Results Test for full validation.');
            return true;
        }
    };

    // Initialize on document ready - no AMD dependency
    $(document).ready(function () {
        // JSON editor will be initialized when first shown
    });

})(jQuery);
