(function () {
    'use strict';

    var config = window.datalumoSearch;

    if (!config || !config.query) {
        return;
    }

    // Create and insert the summary container
    var container = document.createElement('div');
    container.id = 'datalumo-search-summary';
    container.className = 'datalumo-search-summary';
    container.setAttribute('aria-live', 'polite');
    container.innerHTML =
        '<div class="datalumo-search-summary__heading">' + escapeHtml(config.headingText || 'AI Summary') + '</div>' +
        '<div class="datalumo-search-summary__skeleton">' +
            '<div class="datalumo-search-summary__skeleton-line" style="width:100%"></div>' +
            '<div class="datalumo-search-summary__skeleton-line" style="width:100%"></div>' +
            '<div class="datalumo-search-summary__skeleton-line" style="width:60%"></div>' +
        '</div>';

    var inserted = insertContainer(container);

    if (!inserted) {
        return;
    }

    var url = config.ajaxUrl +
        '?action=datalumo_summarise' +
        '&nonce=' + encodeURIComponent(config.nonce) +
        '&query=' + encodeURIComponent(config.query) +
        (config.integrationId ? '&integration_id=' + encodeURIComponent(config.integrationId) : '') +
        (config.locale ? '&locale=' + encodeURIComponent(config.locale) : '');

    fetch(url, {
        method: 'GET',
        credentials: 'same-origin',
    })
        .then(function (response) {
            return response.json();
        })
        .then(function (result) {
            if (!result.success || !result.data || !result.data.summary || result.data.has_relevant_results === false) {
                container.remove();
                return;
            }

            var summary = result.data.summary;
            var references = result.data.references || [];

            // The summary HTML is sanitized server-side via wp_kses_post.
            // Replace [1], [2], etc. with clickable citation links.
            var html = summary.replace(/\[(\d+)\]/g, function (match, num) {
                var refIndex = parseInt(num, 10) - 1;
                if (refIndex >= 0 && refIndex < references.length) {
                    var ref = references[refIndex];
                    return '<a href="' + escapeAttr(ref.url) + '" class="datalumo-citation" title="' + escapeAttr(ref.title) + '">[' + num + ']</a>';
                }
                return match;
            });

            container.innerHTML =
                '<div class="datalumo-search-summary__heading">' + escapeHtml(config.headingText || 'AI Summary') + '</div>' +
                '<div class="datalumo-search-summary__body">' +
                    '<div class="datalumo-search-summary__content">' + html + '</div>' +
                '</div>' +
                '<button type="button" class="datalumo-search-summary__toggle">' + escapeHtml(config.showMoreText || 'Show more') + '</button>';

            container.classList.add('datalumo-search-summary--loaded');

            // Check if content overflows the 240px cap
            var body = container.querySelector('.datalumo-search-summary__body');
            var toggle = container.querySelector('.datalumo-search-summary__toggle');

            if (body.scrollHeight > body.clientHeight) {
                body.classList.add('datalumo-search-summary__body--capped');
                toggle.classList.add('datalumo-search-summary__toggle--visible');

                toggle.addEventListener('click', function () {
                    var expanded = body.classList.toggle('datalumo-search-summary__body--expanded');
                    toggle.textContent = expanded
                        ? (config.showLessText || 'Show less')
                        : (config.showMoreText || 'Show more');
                });
            }
        })
        .catch(function () {
            container.remove();
        });

    function insertContainer(el) {
        var selector = config.summarySelector;
        var position = config.summaryPosition || 'prepend';

        // Custom selector mode
        if (selector) {
            var target = document.querySelector(selector);

            if (!target) {
                return false;
            }

            if (position === 'append') {
                target.appendChild(el);
            } else {
                target.insertBefore(el, target.firstChild);
            }

            return true;
        }

        // Auto-inject: block themes — insert before the query loop block
        var target =
            document.querySelector('.wp-block-query') ||
            document.querySelector('.wp-block-post-template') ||
            document.querySelector('main .wp-block-group');

        if (target) {
            target.parentNode.insertBefore(el, target);
            return true;
        }

        // Auto-inject: Storefront theme — insert after the page header
        target = document.querySelector('#primary .page-header');

        if (target) {
            target.after(el);
            return true;
        }

        // Auto-inject: classic themes — insert at the start of the main content area
        target =
            document.querySelector('main') ||
            document.querySelector('#main') ||
            document.querySelector('#content') ||
            document.querySelector('.site-content') ||
            document.querySelector('[role="main"]');

        if (target) {
            target.insertBefore(el, target.firstChild);
            return true;
        }

        return false;
    }

    function renderReferences(refs) {
        if (!refs || refs.length === 0) {
            return '';
        }

        var items = refs.map(function (ref) {
            return '<li><a href="' + escapeAttr(ref.url) + '">[' + ref.ref + '] ' + escapeHtml(ref.title) + '</a></li>';
        }).join('');

        return '<ol class="datalumo-search-summary__references">' + items + '</ol>';
    }

    function escapeHtml(str) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }

    function escapeAttr(str) {
        return str
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }
})();
