/**
 * LeadMachine Connector Admin JavaScript
 * Handles settings UI interactions including Gravity Forms field mapping
 */

(function($) {
    'use strict';

    // Store form field caches
    var formFieldsCache = {};
    var currentMappings = {};

    // Initialize on document ready
    $(document).ready(function() {
        // Initialize color pickers
        $('.leadmachine-color-picker').wpColorPicker();

        // API Key visibility toggle
        $('#leadmachine-toggle-api-key').on('click', function() {
            var $input = $('#leadmachine_api_key');
            var currentType = $input.attr('type');
            $input.attr('type', currentType === 'password' ? 'text' : 'password');
        });

        // Copy button click handlers
        $('.leadmachine-copy-btn').on('click', function() {
            var textToCopy = $(this).data('copy');
            if (textToCopy && navigator.clipboard) {
                navigator.clipboard.writeText(textToCopy);
            }
        });

        // Load saved mappings
        var savedMappings = $('#leadmachine_gf_forms').val();
        if (savedMappings) {
            try {
                currentMappings = JSON.parse(savedMappings);
            } catch (e) {
                currentMappings = {};
            }
        }

        // Initialize Gravity Forms field mapping
        initGravityFormsMapping();

        // Handle form enable/disable toggles
        $('.gf-form-enabled').on('change', function() {
            var $container = $(this).closest('.gf-form-mapping');
            var $mappingFields = $container.find('.gf-mapping-fields');
            var formId = $container.data('form-id');

            if ($(this).is(':checked')) {
                $mappingFields.removeClass('hidden').slideDown();
                loadFormFields(formId, $container);
            } else {
                $mappingFields.slideUp(function() {
                    $(this).addClass('hidden');
                });
            }

            updateMappingsJson();
        });

        // Handle field selection changes
        $(document).on('change', '.gf-field-select', function() {
            updateMappingsJson();
        });

        // Handle tags input changes
        $(document).on('input', '.gf-form-tags', function() {
            updateMappingsJson();
        });

        // ===== Post Sync Tab =====

        // Sync Categories button
        $('#leadmachine-sync-categories').on('click', function() {
            var $btn = $(this);
            var $status = $('#leadmachine-sync-categories-status');

            $btn.prop('disabled', true);
            $status.html('<span style="color: #666;">Syncing categories...</span>');

            $.ajax({
                url: leadmachineAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'leadmachine_sync_categories',
                    nonce: leadmachineAdmin.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $status.html('<span style="color: green;">Synced ' + response.data.synced + ' categories</span>');
                    } else {
                        $status.html('<span style="color: red;">Error: ' + response.data.message + '</span>');
                    }
                },
                error: function(xhr, status, error) {
                    $status.html('<span style="color: red;">Request failed: ' + error + '</span>');
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });

        // Sync All Posts button
        $('#leadmachine-sync-all-posts').on('click', function() {
            var $btn = $(this);
            var $status = $('#leadmachine-sync-posts-status');

            $btn.prop('disabled', true);
            $status.html('<span style="color: #666;">Syncing posts... This may take a moment.</span>');

            $.ajax({
                url: leadmachineAdmin.ajax_url,
                type: 'POST',
                data: {
                    action: 'leadmachine_sync_all_posts',
                    nonce: leadmachineAdmin.nonce
                },
                timeout: 120000, // 2 minute timeout for large sites
                success: function(response) {
                    if (response.success) {
                        var msg = 'Synced ' + response.data.synced + ' of ' + response.data.total + ' posts';
                        if (response.data.errors > 0) {
                            msg += ' (' + response.data.errors + ' errors)';
                        }
                        $status.html('<span style="color: green;">' + msg + '</span>');
                    } else {
                        $status.html('<span style="color: red;">Error: ' + response.data.message + '</span>');
                    }
                },
                error: function(xhr, status, error) {
                    $status.html('<span style="color: red;">Request failed: ' + error + '</span>');
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });
    });

    /**
     * Initialize Gravity Forms field mapping on page load
     */
    function initGravityFormsMapping() {
        $('.gf-form-mapping').each(function() {
            var $container = $(this);
            var formId = $container.data('form-id');
            var isEnabled = $container.find('.gf-form-enabled').is(':checked');

            if (isEnabled) {
                loadFormFields(formId, $container);
            }
        });
    }

    /**
     * Load form fields via AJAX
     */
    function loadFormFields(formId, $container) {
        // Check cache first
        if (formFieldsCache[formId]) {
            populateFieldSelects($container, formFieldsCache[formId]);
            return;
        }

        // Show loading state
        $container.find('.gf-field-select').prop('disabled', true);

        $.ajax({
            url: leadmachineAdmin.ajax_url,
            type: 'POST',
            data: {
                action: 'leadmachine_get_gf_fields',
                nonce: leadmachineAdmin.nonce,
                form_id: formId
            },
            success: function(response) {
                if (response.success && response.data.fields) {
                    formFieldsCache[formId] = response.data.fields;
                    populateFieldSelects($container, response.data.fields);
                } else {
                    console.error('Failed to load form fields:', response);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error loading form fields:', error);
            },
            complete: function() {
                $container.find('.gf-field-select').prop('disabled', false);
            }
        });
    }

    /**
     * Populate field select dropdowns with form fields
     */
    function populateFieldSelects($container, fields) {
        var formId = $container.data('form-id');
        var savedMapping = currentMappings[formId] || {};

        $container.find('.gf-field-select').each(function() {
            var $select = $(this);
            var mappingType = $select.data('mapping');
            var currentValue = savedMapping[mappingType] || '';

            // Clear existing options (except first)
            $select.find('option:not(:first)').remove();

            // Add field options
            $.each(fields, function(index, field) {
                var $option = $('<option>')
                    .val(field.id)
                    .text(field.label + ' (' + field.type + ')');

                if (String(field.id) === String(currentValue)) {
                    $option.prop('selected', true);
                }

                $select.append($option);
            });
        });

        // Also restore tags value
        if (savedMapping.tags) {
            $container.find('.gf-form-tags').val(savedMapping.tags);
        }
    }

    /**
     * Update the hidden JSON field with current mappings
     */
    function updateMappingsJson() {
        var mappings = {};

        $('.gf-form-mapping').each(function() {
            var $container = $(this);
            var formId = $container.data('form-id');
            var isEnabled = $container.find('.gf-form-enabled').is(':checked');

            if (isEnabled) {
                var formMapping = {
                    enabled: true
                };

                $container.find('.gf-field-select').each(function() {
                    var mappingType = $(this).data('mapping');
                    var value = $(this).val();
                    if (value) {
                        formMapping[mappingType] = value;
                    }
                });

                // Get tags
                var tags = $container.find('.gf-form-tags').val();
                if (tags) {
                    formMapping.tags = tags;
                }

                mappings[formId] = formMapping;
            }
        });

        $('#leadmachine_gf_forms').val(JSON.stringify(mappings));
        currentMappings = mappings;
    }

})(jQuery);
