/**
 * Custom Schema by SCHEMAFY - Schema List Expander
 * Version: 1.0.0
 * Expandable schema items with JSON preview
 */

(function() {
    'use strict';

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

    /**
     * Initialize schema expander for a list
     * @param {string} containerId - ID of the schema list container
     * @param {object} options - Configuration options
     */
    window.SCHEMAFY.initSchemaExpander = function(containerId, options) {
        var settings = jQuery.extend({
            expandIcon: '▶',
            collapseIcon: '▼',
            showLineNumbers: false,
            onExpand: null,
            onCollapse: null
        }, options);

        var $container = jQuery('#' + containerId);
        if (!$container.length) {
            console.warn('[SCHEMAFY Expander] Container not found:', containerId);
            return;
        }

        var $schemaItems = $container.find('.schemafy-schema-item');

        /**
         * Create expandable structure for each schema item
         */
        $schemaItems.each(function() {
            var $item = jQuery(this);

            // Skip if already initialized
            if ($item.hasClass('schemafy-expander-initialized')) {
                return;
            }

            // Get schema JSON from data attribute
            var schemaJson = $item.attr('data-schema-json');
            if (!schemaJson) {
                return;
            }

            // Create expand button
            var $expandBtn = jQuery('<button class="schemafy-expand-btn" type="button"></button>');
            $expandBtn.html(settings.expandIcon);

            // Create collapsible content
            var $collapsibleContent = jQuery('<div class="schemafy-collapsible-content"></div>');

            // Format and highlight JSON
            try {
                var parsed = JSON.parse(schemaJson);
                var formatted = JSON.stringify(parsed, null, 2);
                var highlighted = syntaxHighlight(formatted);

                var $jsonPreview = jQuery('<pre class="schemafy-json-preview"></pre>');
                $jsonPreview.html(highlighted);

                // Add copy button
                var $copyBtn = jQuery('<button class="schemafy-copy-json-btn" type="button">📋 Copy JSON</button>');

                $collapsibleContent.append($jsonPreview);
                $collapsibleContent.append($copyBtn);

                // Add copy functionality
                $copyBtn.on('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    copyToClipboard(formatted);
                    showCopyFeedback($copyBtn);
                });

            } catch (e) {
                $collapsibleContent.html('<div class="schemafy-json-error">Invalid JSON</div>');
            }

            // Insert expand button and content
            var $header = $item.find('.schemafy-schema-item-header');
            if (!$header.length) {
                // If no header exists, create one
                $header = jQuery('<div class="schemafy-schema-item-header"></div>');
                var $title = $item.find('.schemafy-schema-title');
                if ($title.length) {
                    $title.wrap($header);
                    $header = $title.parent();
                } else {
                    $item.prepend($header);
                }
            }

            $header.prepend($expandBtn);
            $item.append($collapsibleContent);

            // Mark as initialized
            $item.addClass('schemafy-expander-initialized');
        });

        /**
         * Toggle expand/collapse
         */
        $container.on('click', '.schemafy-expand-btn', function(e) {
            e.preventDefault();
            e.stopPropagation();

            var $btn = jQuery(this);
            var $item = $btn.closest('.schemafy-schema-item');
            var $content = $item.find('.schemafy-collapsible-content');

            var isExpanded = $item.hasClass('schemafy-expanded');

            if (isExpanded) {
                // Collapse
                $item.removeClass('schemafy-expanded');
                $content.slideUp(200);
                $btn.html(settings.expandIcon);

                if (typeof settings.onCollapse === 'function') {
                    settings.onCollapse($item[0]);
                }
            } else {
                // Expand
                $item.addClass('schemafy-expanded');
                $content.slideDown(200);
                $btn.html(settings.collapseIcon);

                if (typeof settings.onExpand === 'function') {
                    settings.onExpand($item[0]);
                }
            }
        });

        /**
         * 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>';
                }
            );
        }

        /**
         * Copy text to clipboard
         */
        function copyToClipboard(text) {
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text);
            } else {
                // Fallback for older browsers
                var $temp = jQuery('<textarea>');
                jQuery('body').append($temp);
                $temp.val(text).select();
                document.execCommand('copy');
                $temp.remove();
            }
        }

        /**
         * Show copy feedback
         */
        function showCopyFeedback($btn) {
            var originalText = $btn.html();
            $btn.html('✓ Copied!').addClass('schemafy-copied');

            setTimeout(function() {
                $btn.html(originalText).removeClass('schemafy-copied');
            }, 2000);
        }

        /**
         * Expand all schemas
         */
        function expandAll() {
            $schemaItems.each(function() {
                var $item = jQuery(this);
                if (!$item.hasClass('schemafy-expanded')) {
                    $item.find('.schemafy-expand-btn').trigger('click');
                }
            });
        }

        /**
         * Collapse all schemas
         */
        function collapseAll() {
            $schemaItems.each(function() {
                var $item = jQuery(this);
                if ($item.hasClass('schemafy-expanded')) {
                    $item.find('.schemafy-expand-btn').trigger('click');
                }
            });
        }


        // Public API
        return {
            expandAll: expandAll,
            collapseAll: collapseAll
        };
    };

})();
