/**
 * Custom Schema by SCHEMAFY - Variables Dropdown
 * Version: 1.0.0
 * Insert variables into schema fields
 */

(function() {
    'use strict';

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

    /**
     * Initialize variables dropdown for a field
     * @param {string} fieldId - ID of the textarea/input
     * @param {string} buttonId - ID of the trigger button
     * @param {array} variables - Array of variable objects
     */
    window.SCHEMAFY.initVariablesDropdown = function(fieldId, buttonId, variables) {
        var $field = jQuery('#' + fieldId);
        var $button = jQuery('#' + buttonId);

        if (!$field.length || !$button.length) {
            console.warn('[SCHEMAFY Variables] Field or button not found');
            return;
        }

        // Default variables if not provided
        var defaultVariables = [
            // Site & SEO
            { code: '{{site_name}}', description: 'WordPress site name', group: 'Site & SEO' },
            { code: '{{site_url}}', description: 'Site home URL', group: 'Site & SEO' },
            { code: '{{site_description}}', description: 'Site tagline/description', group: 'Site & SEO' },
            { code: '{{site_language}}', description: 'Site language code', group: 'Site & SEO' },
            { code: '{{current_url}}', description: 'Current page URL', group: 'Site & SEO' },
            { code: '{{current_year}}', description: 'Current year', group: 'Site & SEO' },
            { code: '{{meta_title}}', description: 'SEO meta title (Yoast/RankMath)', group: 'Site & SEO' },
            { code: '{{meta_description}}', description: 'SEO meta description', group: 'Site & SEO' },
            // Post / Page
            { code: '{{post_title}}', description: 'Post/Page title', group: 'Post / Page' },
            { code: '{{post_excerpt}}', description: 'Post excerpt or summary', group: 'Post / Page' },
            { code: '{{post_author}}', description: 'Author display name', group: 'Post / Page' },
            { code: '{{post_date}}', description: 'Publication date (ISO 8601)', group: 'Post / Page' },
            { code: '{{post_modified}}', description: 'Last modified date (ISO 8601)', group: 'Post / Page' },
            { code: '{{post_url}}', description: 'Post/page permalink', group: 'Post / Page' },
            { code: '{{featured_image}}', description: 'Featured image URL', group: 'Post / Page' },
            { code: '{{category}}', description: 'Primary category name', group: 'Post / Page' },
            { code: '{{tags}}', description: 'Tags (comma-separated)', group: 'Post / Page' },
            { code: '{{post_id}}', description: 'Post/page numeric ID', group: 'Post / Page' },
            { code: '{{post_type}}', description: 'Post type (post, page, product)', group: 'Post / Page' },
            // WooCommerce
            { code: '{{product_price}}', description: 'Current product price', group: 'WooCommerce' },
            { code: '{{product_regular_price}}', description: 'Regular price (before sale)', group: 'WooCommerce' },
            { code: '{{product_sale_price}}', description: 'Sale price', group: 'WooCommerce' },
            { code: '{{product_currency}}', description: 'Store currency code', group: 'WooCommerce' },
            { code: '{{product_sku}}', description: 'Product SKU', group: 'WooCommerce' },
            { code: '{{product_stock_status}}', description: 'Availability (Schema.org URL)', group: 'WooCommerce' },
            { code: '{{product_short_description}}', description: 'Product short description', group: 'WooCommerce' },
            { code: '{{product_weight}}', description: 'Product weight', group: 'WooCommerce' },
            { code: '{{product_category}}', description: 'Primary product category', group: 'WooCommerce' },
            { code: '{{product_rating}}', description: 'Average product rating', group: 'WooCommerce' },
            { code: '{{product_review_count}}', description: 'Number of reviews', group: 'WooCommerce' },
            { code: '{{product_image}}', description: 'Main product image URL', group: 'WooCommerce' }
        ];

        var vars = variables || defaultVariables;

        // Create dropdown
        var dropdownId = 'schemafy-vars-dropdown-' + fieldId;
        var $dropdown = jQuery('<div class="schemafy-variables-dropdown" id="' + dropdownId + '"></div>');

        // Populate dropdown with group headers
        var currentGroup = '';
        vars.forEach(function(variable) {
            if (variable.group && variable.group !== currentGroup) {
                currentGroup = variable.group;
                var $header = jQuery('<div class="schemafy-variable-group-header"></div>');
                $header.text(currentGroup);
                $dropdown.append($header);
            }
            var $item = jQuery('<div class="schemafy-variable-item"></div>');
            $item.attr('data-var', variable.code);
            $item.html(
                '<div class="schemafy-variable-code">' + variable.code + '</div>' +
                '<div class="schemafy-variable-desc">' + variable.description + '</div>'
            );
            $dropdown.append($item);
        });

        // Insert after button
        $button.after($dropdown);

        // Toggle dropdown
        $button.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();

            // Close other dropdowns
            jQuery('.schemafy-variables-dropdown').not($dropdown).removeClass('schemafy-dropdown-show');

            // Toggle this dropdown
            $dropdown.toggleClass('schemafy-dropdown-show');
        });

        // Insert variable on click
        $dropdown.on('click', '.schemafy-variable-item', function(e) {
            e.stopPropagation();

            var variable = jQuery(this).attr('data-var');
            // If the AI JSON editor is visible, insert there; otherwise use the bound field
            var $aiJson = jQuery('#schemafy-ai-json');
            var targetEl = ($aiJson.length && $aiJson.is(':visible')) ? $aiJson[0] : $field[0];
            insertAtCursor(targetEl, variable);

            // Hide dropdown
            $dropdown.removeClass('schemafy-dropdown-show');

            // Focus the active editor
            jQuery(targetEl).focus();

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

        // Close dropdown when clicking outside
        jQuery(document).on('click', function(e) {
            if (!$button.is(e.target) && !$dropdown.is(e.target) && $dropdown.has(e.target).length === 0) {
                $dropdown.removeClass('schemafy-dropdown-show');
            }
        });

        // Close on Escape
        jQuery(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                $dropdown.removeClass('schemafy-dropdown-show');
            }
        });

    };

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

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

            // Move cursor after inserted text
            var newPos = startPos + text.length;
            element.setSelectionRange(newPos, newPos);
        } else if (element.isContentEditable) {
            // For contenteditable
            var sel = window.getSelection();
            if (sel.rangeCount > 0) {
                var range = sel.getRangeAt(0);
                range.deleteContents();
                var textNode = document.createTextNode(text);
                range.insertNode(textNode);
                range.setStartAfter(textNode);
                range.setEndAfter(textNode);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    }

})();
