(function ($) {
    'use strict';

    var i18n = datalumoAdmin.i18n;
    var syncPollTimers = {};
    var collectionsCache = null;
    var apiKeyValid = !!datalumoAdmin.apiKeyValid;
    var currentTab = datalumoAdmin.currentTab;

    // --- Save & Test API Key ---
    $('#datalumo-save-api-key').on('click', function () {
        var $btn = $(this);
        var $result = $('#datalumo-test-result');
        var apiKey = $('#datalumo_api_key').val();

        if (!apiKey) {
            $result.text(i18n.testFailed + 'API Key is required.').css('color', 'red');
            return;
        }

        $btn.prop('disabled', true);
        $result.text(i18n.testing).css('color', '');

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_save_api_key',
            nonce: datalumoAdmin.nonce,
            api_key: apiKey
        }, function (response) {
            if (response.success) {
                $result.text(i18n.testSuccess).css('color', 'green');

                // If this is the first time a valid key is saved, reload
                // the page so the other tabs become clickable.
                if (!apiKeyValid) {
                    window.location.reload();
                }
            } else {
                $result.text(i18n.testFailed + response.data.message).css('color', 'red');
            }
        }).fail(function () {
            $result.text(i18n.testFailed + 'Network error').css('color', 'red');
        }).always(function () {
            $btn.prop('disabled', false);
        });
    });

    // --- Fetch Collections (shared helper) ---
    function fetchCollections(callback) {
        if (collectionsCache) {
            callback(collectionsCache);
            return;
        }

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_fetch_collections',
            nonce: datalumoAdmin.nonce
        }, function (response) {
            if (response.success) {
                collectionsCache = response.data.collections;
                callback(collectionsCache);
            } else {
                callback([]);
            }
        }).fail(function () {
            callback([]);
        });
    }

    function populateCollectionSelect($select, collections) {
        var currentVal = $select.val();
        $select.find('option:not(:first)').remove();

        $.each(collections, function (i, collection) {
            $select.append(
                $('<option>').val(collection.id).text(collection.name)
            );
        });

        if (currentVal) {
            $select.val(currentVal);
        }
    }

    // --- Load all sync-block collection dropdowns ---
    function loadSyncCollections() {
        fetchCollections(function (collections) {
            $('.datalumo-sync-collection').each(function () {
                populateCollectionSelect($(this), collections);
            });
            syncFormReady = true;
            $('.datalumo-sync-now').show();
            updateSyncTitles();
        });
    }

    // --- Create collection for a sync block ---
    $(document).on('click', '.datalumo-create-sync-collection', function () {
        var name = prompt(i18n.collectionName);
        if (!name) return;

        var $btn = $(this);
        var $select = $btn.closest('td').find('.datalumo-sync-collection');
        $btn.prop('disabled', true).text(i18n.creating);

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_create_collection',
            nonce: datalumoAdmin.nonce,
            name: name
        }, function (response) {
            if (response.success) {
                var col = response.data.collection;
                collectionsCache = null;
                $select.append($('<option>').val(col.id).text(col.name));
                $select.val(col.id);
            } else {
                alert(response.data.message);
            }
        }).fail(function () {
            alert('Network error');
        }).always(function () {
            $btn.prop('disabled', false).text(i18n.createCollection);
        });
    });

    // --- Detect unsaved changes in content sync form ---
    var syncFormReady = false;

    function markSyncBlockDirty($block) {
        if (!syncFormReady) return;
        var $btn = $block.find('.datalumo-sync-now');
        $btn.prop('disabled', true);
        $block.find('.datalumo-sync-unsaved').remove();
        $btn.after(
            '<span class="datalumo-sync-unsaved" style="color: #646970; margin-left: 8px;">' + i18n.syncSaveFirst + '</span>'
        );
    }

    $('#datalumo-content-sync-form').on('change input', 'select, input[type="checkbox"], input[type="text"]', function () {
        markSyncBlockDirty($(this).closest('.datalumo-sync-block'));
    });

    // --- Toggle sync blocks ---
    $(document).on('click', '.datalumo-sync-header', function (e) {
        if ($(e.target).closest('button, .datalumo-sync-now').length) return;

        var $block = $(this).closest('.datalumo-sync-block');
        var $body = $block.find('.datalumo-sync-body');
        var $toggle = $block.find('.datalumo-sync-toggle');

        $block.toggleClass('datalumo-sync-block--open');
        $body.slideToggle(200);
        $toggle.toggleClass('dashicons-arrow-down-alt2 dashicons-arrow-up-alt2');
    });

    // Update sync title from collection dropdown
    $(document).on('change', '.datalumo-sync-collection', function () {
        var $block = $(this).closest('.datalumo-sync-block');
        var text = $(this).find('option:selected').text().trim();
        $block.find('.datalumo-sync-title').text(text || i18n.newSync);
    });

    function updateSyncTitles() {
        $('.datalumo-sync-block').each(function () {
            var $block = $(this);
            var text = $block.find('.datalumo-sync-collection option:selected').text().trim();
            if (text && text !== i18n.selectCollectionPlaceholder) {
                $block.find('.datalumo-sync-title').text(text);
            }
        });
    }

    // --- Meta Mappings ---
    var taxonomies = datalumoAdmin.taxonomies || [];

    function buildTaxonomySelect(name, currentValue) {
        var html = '<select name="' + name + '" class="datalumo-meta-source-taxonomy" style="width: 150px;">';
        html += '<option value="">' + i18n.metaSelectTaxonomy + '</option>';
        $.each(taxonomies, function (i, tax) {
            html += '<option value="' + escapeAttr(tax.name) + '"' + (tax.name === currentValue ? ' selected' : '') + '>' + escapeAttr(tax.label) + ' (' + escapeAttr(tax.name) + ')</option>';
        });
        html += '</select>';
        return html;
    }

    function buildMetaMappingRow(syncIndex, mappingIndex, data) {
        data = data || { name: '', type: 'post_meta', source: '', searchable: false };

        var prefix = 'datalumo_content_syncs[' + syncIndex + '][meta_mappings][' + mappingIndex + ']';
        var isTaxonomy = data.type === 'taxonomy';

        var $row = $('<div class="datalumo-meta-mapping-row" style="display: flex; gap: 8px; align-items: center; margin-bottom: 6px;"></div>');

        $row.append('<input type="text" name="' + prefix + '[name]" value="' + escapeAttr(data.name) + '" placeholder="' + i18n.metaName + '" class="regular-text" style="width: 120px;" />');
        $row.append(
            '<select name="' + prefix + '[type]" class="datalumo-meta-type" style="width: 130px;">' +
            '<option value="post_meta"' + (data.type === 'post_meta' ? ' selected' : '') + '>' + i18n.metaTypeCustomField + '</option>' +
            '<option value="taxonomy"' + (data.type === 'taxonomy' ? ' selected' : '') + '>' + i18n.metaTypeTaxonomy + '</option>' +
            '</select>'
        );

        var sourceInput = isTaxonomy
            ? buildTaxonomySelect(prefix + '[source]', data.source)
            : '<input type="text" name="' + prefix + '[source]" value="' + escapeAttr(data.source) + '" placeholder="' + i18n.metaSource + '" class="regular-text datalumo-meta-source-text" style="width: 150px;" />';
        $row.append(sourceInput);

        $row.append(
            '<label style="white-space: nowrap;"><input type="checkbox" name="' + prefix + '[searchable]" value="1"' + (data.searchable ? ' checked' : '') + ' /> ' + i18n.metaSearchable + '</label>'
        );
        $row.append('<button type="button" class="button button-link-delete datalumo-remove-meta-mapping">&times;</button>');

        return $row;
    }

    // Switch between text input and taxonomy dropdown when type changes
    $(document).on('change', '.datalumo-meta-type', function () {
        var $row = $(this).closest('.datalumo-meta-mapping-row');
        var $source = $row.find('.datalumo-meta-source-text, .datalumo-meta-source-taxonomy');
        var name = $source.attr('name');

        if ($(this).val() === 'taxonomy') {
            $source.replaceWith(buildTaxonomySelect(name, ''));
        } else {
            $source.replaceWith('<input type="text" name="' + name + '" value="" placeholder="' + i18n.metaSource + '" class="regular-text datalumo-meta-source-text" style="width: 150px;" />');
        }
    });

    function getSyncBlockIndex($block) {
        return $block.index('.datalumo-sync-block');
    }

    $(document).on('click', '.datalumo-add-meta-mapping', function () {
        var $block = $(this).closest('.datalumo-sync-block');
        var $container = $block.find('.datalumo-meta-mappings');
        var syncIndex = getSyncBlockIndex($block);
        var mappingIndex = $container.find('.datalumo-meta-mapping-row').length;

        $container.append(buildMetaMappingRow(syncIndex, mappingIndex, null));
        markSyncBlockDirty($block);
    });

    $(document).on('click', '.datalumo-remove-meta-mapping', function () {
        var $block = $(this).closest('.datalumo-sync-block');
        $(this).closest('.datalumo-meta-mapping-row').remove();
        reindexMetaMappings($block);
        markSyncBlockDirty($block);
    });

    $(document).on('click', '.datalumo-woocommerce-preset', function () {
        var $block = $(this).closest('.datalumo-sync-block');
        var $container = $block.find('.datalumo-meta-mappings');
        var syncIndex = getSyncBlockIndex($block);

        var presets = [
            { name: 'sku', type: 'post_meta', source: '_sku', searchable: true },
            { name: 'price', type: 'post_meta', source: '_price', searchable: false },
            { name: 'product_categories', type: 'taxonomy', source: 'product_cat', searchable: false },
            { name: 'product_tags', type: 'taxonomy', source: 'product_tag', searchable: false }
        ];

        var existing = [];
        $container.find('.datalumo-meta-mapping-row input[placeholder="' + i18n.metaSource + '"]').each(function () {
            existing.push($(this).val());
        });

        var startIndex = $container.find('.datalumo-meta-mapping-row').length;

        $.each(presets, function (i, preset) {
            if (existing.indexOf(preset.source) === -1) {
                $container.append(buildMetaMappingRow(syncIndex, startIndex + i, preset));
            }
        });

        markSyncBlockDirty($block);
    });

    function reindexMetaMappings($block) {
        var syncIndex = getSyncBlockIndex($block);
        $block.find('.datalumo-meta-mapping-row').each(function (mi) {
            var prefix = 'datalumo_content_syncs[' + syncIndex + '][meta_mappings][' + mi + ']';
            $(this).find('input, select').each(function () {
                var name = $(this).attr('name');
                if (name) {
                    var field = name.replace(/.*\[meta_mappings\]\[\d+\]\[(\w+)\]/, '$1');
                    $(this).attr('name', prefix + '[' + field + ']');
                }
            });
        });
    }

    function escapeAttr(str) {
        return $('<span>').text(str || '').html();
    }

    // --- Sync Now (per block) ---
    $(document).on('click', '.datalumo-sync-now', function () {
        var $block = $(this).closest('.datalumo-sync-block');
        var syncId = $block.data('sync-id');
        var $btn = $(this);
        var $status = $block.find('.datalumo-sync-status');

        $btn.prop('disabled', true);
        $status.text(i18n.syncing).css('color', '');

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_trigger_sync',
            nonce: datalumoAdmin.nonce,
            sync_id: syncId
        }, function (response) {
            if (response.success) {
                $status.text(i18n.syncStarted).css('color', 'green');
                $block.find('.datalumo-sync-cancel').show();
                startSyncPolling(syncId, $block);
            } else {
                $status.text(response.data.message).css('color', 'red');
                $btn.prop('disabled', false);
            }
        }).fail(function () {
            $status.text(i18n.syncFailed + 'Network error').css('color', 'red');
            $btn.prop('disabled', false);
        });
    });

    // --- Cancel Sync (per block) ---
    $(document).on('click', '.datalumo-sync-cancel', function () {
        if (!confirm(i18n.syncCancelConfirm)) return;

        var $block = $(this).closest('.datalumo-sync-block');
        var syncId = $block.data('sync-id');
        var $btn = $(this);
        var $status = $block.find('.datalumo-sync-status');

        $btn.prop('disabled', true);
        $status.text(i18n.syncCancelling).css('color', '');

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_cancel_sync',
            nonce: datalumoAdmin.nonce,
            sync_id: syncId
        }, function (response) {
            if (response.success) {
                $status.text(i18n.syncCancelled).css('color', '');
                $btn.hide().prop('disabled', false);
                $block.find('.datalumo-sync-now').prop('disabled', false);
                if (syncPollTimers[syncId]) {
                    clearInterval(syncPollTimers[syncId]);
                    delete syncPollTimers[syncId];
                }
            } else {
                $status.text(response.data.message).css('color', 'red');
                $btn.prop('disabled', false);
            }
        }).fail(function () {
            $status.text(i18n.syncFailed + 'Network error').css('color', 'red');
            $btn.prop('disabled', false);
        });
    });

    function startSyncPolling(syncId, $block) {
        if (syncPollTimers[syncId]) clearInterval(syncPollTimers[syncId]);

        syncPollTimers[syncId] = setInterval(function () {
            $.post(datalumoAdmin.ajaxUrl, {
                action: 'datalumo_sync_status',
                nonce: datalumoAdmin.nonce,
                sync_id: syncId
            }, function (response) {
                if (!response.success) return;

                var data = response.data;
                var $status = $block.find('.datalumo-sync-status');
                var $btn = $block.find('.datalumo-sync-now');
                var $cancel = $block.find('.datalumo-sync-cancel');

                if (data.in_progress) {
                    var msg = i18n.syncProgress
                        .replace('{processed}', data.processed)
                        .replace('{total}', data.total);
                    $status.text(msg).css('color', '');
                    $cancel.show();
                } else {
                    $status.text(i18n.syncComplete).css('color', 'green');
                    $btn.prop('disabled', false);
                    $cancel.hide();
                    clearInterval(syncPollTimers[syncId]);
                    delete syncPollTimers[syncId];
                }
            });
        }, 3000);
    }

    // --- Delete Content Sync ---
    $(document).on('click', '.datalumo-delete-sync', function () {
        if (!confirm(i18n.confirmDeleteSync)) return;

        var $block = $(this).closest('.datalumo-sync-block');
        var syncId = $block.data('sync-id');

        // Only call API delete if this was a saved sync (not a newly added unsaved block)
        if (syncId) {
            $.post(datalumoAdmin.ajaxUrl, {
                action: 'datalumo_delete_content_sync',
                nonce: datalumoAdmin.nonce,
                sync_id: syncId
            });
        }

        $block.remove();
        reindexSyncBlocks();
    });

    // --- Add Content Sync ---
    $('#datalumo-add-sync').on('click', function () {
        var index = $('.datalumo-sync-block').length;
        var syncId = generateSyncId();
        var template = $('#tmpl-datalumo-sync-block').html();

        template = template.replace(/\{\{SYNC_ID\}\}/g, syncId);
        template = template.replace(/\{\{INDEX\}\}/g, index);

        var $block = $(template);
        $('#datalumo-content-syncs').append($block);

        // Populate collection dropdown for the new block
        fetchCollections(function (collections) {
            populateCollectionSelect($block.find('.datalumo-sync-collection'), collections);
        });
    });

    function generateSyncId() {
        return 'sync_' + Date.now() + '_' + Math.random().toString(36).substr(2, 6);
    }

    function reindexSyncBlocks() {
        $('.datalumo-sync-block').each(function (index) {
            $(this).find('input, select').each(function () {
                var name = $(this).attr('name');
                if (name) {
                    $(this).attr('name', name.replace(/datalumo_content_syncs\[\d+\]/, 'datalumo_content_syncs[' + index + ']'));
                }
            });
        });
    }

    // --- Load Search Integrations ---
    function loadSearchIntegrations() {
        var $select = $('#datalumo_search_integration_id');
        var currentVal = $select.val();

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_fetch_integrations',
            nonce: datalumoAdmin.nonce,
            type: 'custom'
        }, function (response) {
            if (response.success) {
                $select.find('option:not(:first)').remove();

                $.each(response.data.integrations, function (i, integration) {
                    $select.append(
                        $('<option>').val(integration.id).text(integration.name)
                    );
                });

                if (currentVal) {
                    $select.val(currentVal);
                }
            }
        });
    }

    $('#datalumo-refresh-search-integrations').on('click', function () {
        loadSearchIntegrations();
    });

    // --- Load Search Box Integrations ---
    function loadSearchBoxIntegrations() {
        var $select = $('#datalumo_search_box_integration_id');
        if (!$select.length) return;

        var currentVal = $select.val();

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_fetch_integrations',
            nonce: datalumoAdmin.nonce,
            type: 'search_box'
        }, function (response) {
            if (response.success) {
                $select.find('option:not(:first)').remove();

                $.each(response.data.integrations, function (i, integration) {
                    $select.append(
                        $('<option>').val(integration.id).text(integration.name)
                    );
                });

                if (currentVal) {
                    $select.val(currentVal);
                }
            }
        });
    }

    $('#datalumo-refresh-search-box-integrations').on('click', function () {
        loadSearchBoxIntegrations();
    });

    // --- Create Search Box Integration ---
    $('#datalumo-create-search-box-integration').on('click', function () {
        var $form = $('#datalumo-create-search-box-integration-form');
        var $container = $('#datalumo-search-box-integration-collections');

        $container.html(i18n.loading);
        $('#datalumo-new-search-box-integration-name').val('');
        $form.slideDown(200);

        collectionsCache = null;
        fetchCollections(function (collections) {
            $container.empty();
            if (collections.length) {
                $.each(collections, function (i, col) {
                    $container.append(
                        '<label style="display:block; margin: 2px 0;"><input type="checkbox" value="' + $('<span>').text(col.id).html() + '"> ' + $('<span>').text(col.name).html() + '</label>'
                    );
                });
            } else {
                $container.html('<em>' + i18n.noItems + '</em>');
            }
        });
    });

    $('#datalumo-cancel-search-box-integration').on('click', function () {
        $('#datalumo-create-search-box-integration-form').slideUp(200);
    });

    $('#datalumo-submit-search-box-integration').on('click', function () {
        var name = $('#datalumo-new-search-box-integration-name').val().trim();
        if (!name) {
            $('#datalumo-new-search-box-integration-name').focus();
            return;
        }

        var collectionIds = [];
        $('#datalumo-search-box-integration-collections input:checked').each(function () {
            collectionIds.push($(this).val());
        });

        if (collectionIds.length === 0) {
            alert(i18n.selectCollection);
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true).text(i18n.creating);

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_create_integration',
            nonce: datalumoAdmin.nonce,
            name: name,
            type: 'search_box',
            collection_ids: collectionIds
        }, function (response) {
            if (response.success) {
                var integration = response.data.integration;
                var $select = $('#datalumo_search_box_integration_id');
                $select.append($('<option>').val(integration.id).text(integration.name));
                $select.val(integration.id);
                $('#datalumo-create-search-box-integration-form').slideUp(200);
            } else {
                alert(response.data.message);
            }
        }).fail(function () {
            alert('Network error');
        }).always(function () {
            $btn.prop('disabled', false).text(i18n.createIntegrationSubmit);
        });
    });

    // --- Create Search Integration ---
    $('#datalumo-create-search-integration').on('click', function () {
        var $form = $('#datalumo-create-integration-form');
        var $container = $('#datalumo-integration-collections');

        $container.html(i18n.loading);
        $('#datalumo-new-integration-name').val('');
        $form.slideDown(200);

        collectionsCache = null;
        fetchCollections(function (collections) {
            $container.empty();
            if (collections.length) {
                $.each(collections, function (i, col) {
                    $container.append(
                        '<label style="display:block; margin: 2px 0;"><input type="checkbox" value="' + $('<span>').text(col.id).html() + '"> ' + $('<span>').text(col.name).html() + '</label>'
                    );
                });
            } else {
                $container.html('<em>' + i18n.noItems + '</em>');
            }
        });
    });

    $('#datalumo-cancel-integration').on('click', function () {
        $('#datalumo-create-integration-form').slideUp(200);
    });

    $('#datalumo-submit-integration').on('click', function () {
        var name = $('#datalumo-new-integration-name').val().trim();
        if (!name) {
            $('#datalumo-new-integration-name').focus();
            return;
        }

        var collectionIds = [];
        $('#datalumo-integration-collections input:checked').each(function () {
            collectionIds.push($(this).val());
        });

        if (collectionIds.length === 0) {
            alert(i18n.selectCollection);
            return;
        }

        var $btn = $(this);
        $btn.prop('disabled', true).text(i18n.creating);

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_create_integration',
            nonce: datalumoAdmin.nonce,
            name: name,
            type: 'custom',
            collection_ids: collectionIds
        }, function (response) {
            if (response.success) {
                var integration = response.data.integration;
                var $select = $('#datalumo_search_integration_id');
                $select.append($('<option>').val(integration.id).text(integration.name));
                $select.val(integration.id);
                $('#datalumo-create-integration-form').slideUp(200);
            } else {
                alert(response.data.message);
            }
        }).fail(function () {
            alert('Network error');
        }).always(function () {
            $btn.prop('disabled', false).text(i18n.createIntegrationSubmit);
        });
    });

    // --- Load Chatbot Integrations ---
    function loadChatbots() {
        var $select = $('#datalumo_chatbot_integration_id');
        var currentVal = $select.val();

        $.post(datalumoAdmin.ajaxUrl, {
            action: 'datalumo_fetch_integrations',
            nonce: datalumoAdmin.nonce,
            type: 'chatbot'
        }, function (response) {
            if (response.success) {
                $select.find('option:not(:first)').remove();

                $.each(response.data.integrations, function (i, integration) {
                    $select.append(
                        $('<option>').val(integration.id).text(integration.name)
                    );
                });

                if (currentVal) {
                    $select.val(currentVal);
                }
            }
        });
    }

    $('#datalumo-refresh-chatbots').on('click', function () {
        loadChatbots();
    });

    // --- Toggle chatbot mode-specific rows ---
    function updateChatbotModeRows() {
        var mode = $('input[name="datalumo_chatbot_mode"]:checked').val();
        $('.datalumo-chatbot-row-popup').toggle(mode === 'popup');
        $('.datalumo-chatbot-row-sidebar').toggle(mode === 'sidebar');
    }

    $(document).on('change', '.datalumo-chatbot-mode', updateChatbotModeRows);

    // --- Load dropdowns for the current tab ---
    function loadDropdownsForCurrentTab() {
        if (currentTab === 'content-sync') {
            loadSyncCollections();
        } else if (currentTab === 'chatbot') {
            loadChatbots();
        } else if (currentTab === 'search-box') {
            loadSearchBoxIntegrations();
        } else if (currentTab === 'enhanced-search') {
            loadSearchIntegrations();
        }
    }

    // --- Summary Placement Mode Toggle ---
    $(document).on('change', '.datalumo-summary-placement-mode', function () {
        var $customFields = $('#datalumo-summary-custom-fields');
        var $selectorInput = $('#datalumo_search_summary_selector');

        if ($(this).val() === 'custom') {
            $customFields.slideDown(200);
        } else {
            $customFields.slideUp(200);
            $selectorInput.val('');
        }
    });

    // --- Auto-load on page load ---
    $(function () {
        if (apiKeyValid) {
            loadDropdownsForCurrentTab();
        }

        // Check if any syncs are currently running
        $('.datalumo-sync-block').each(function () {
            var $block = $(this);
            var syncId = $block.data('sync-id');

            if (!syncId) return;

            $.post(datalumoAdmin.ajaxUrl, {
                action: 'datalumo_sync_status',
                nonce: datalumoAdmin.nonce,
                sync_id: syncId
            }, function (response) {
                if (response.success && response.data.in_progress) {
                    $block.find('.datalumo-sync-now').prop('disabled', true);
                    $block.find('.datalumo-sync-cancel').show();
                    var msg = i18n.syncProgress
                        .replace('{processed}', response.data.processed)
                        .replace('{total}', response.data.total);
                    $block.find('.datalumo-sync-status').text(msg);
                    startSyncPolling(syncId, $block);
                }
            });
        });
    });

})(jQuery);
