(function ($) {

    let terms = window.SS_RELATED_TERMS || [];
    let popup = null;

    // Create popup HTML once
    function createPopup() {
        popup = $(`
            <div id="ss-link-popup" style="
                position:absolute;
                z-index:999999;
                background:#fff;
                border:1px solid #ccc;
                padding:10px;
                border-radius:6px;
                box-shadow:0 4px 12px rgba(0,0,0,0.15);
                display:none;
                width:220px;
            ">
                <div id="ss-link-title" style="font-weight:bold;margin-bottom:6px;">Link to:</div>
                <button id="ss-insert-link-btn"
                    style="background:#0073aa;color:#fff;border:0;padding:6px 10px;border-radius:4px;width:100%;cursor:pointer;">
                    Insert Link
                </button>
            </div>
        `);

        $("body").append(popup);
    }

    function getSelectedText() {
        let selection = window.getSelection();
        return selection.toString().trim();
    }

    function findMatchingTerm(text) {
        text = text.toLowerCase();
        for (let t of terms) {
            if (t.title.toLowerCase() === text) {
                return t;
            }
        }
        return null;
    }

    function showPopup(term, x, y) {
        $("#ss-link-title").text("Link to: " + term.title);
        popup.data("url", term.url);

        popup.css({
            top: y + 10,
            left: x + 10
        }).show();
    }

    function hidePopup() {
        popup.hide();
    }

    function insertLink(url) {
        let selection = window.getSelection();

        if (!selection.rangeCount) return;

        let range = selection.getRangeAt(0);
        let link = document.createElement("a");
        link.href = url;
        link.textContent = selection.toString();

        range.deleteContents();
        range.insertNode(link);

        hidePopup();
    }

    $(document).ready(function () {
        createPopup();

        $(document).on("mouseup keyup", function (e) {

            let sel = getSelectedText();
            if (!sel) {
                hidePopup();
                return;
            }

            let term = findMatchingTerm(sel);

            if (term) {
                showPopup(term, e.pageX, e.pageY);
            } else {
                hidePopup();
            }
        });

        // Insert Link button
        $(document).on("click", "#ss-insert-link-btn", function () {
            let url = popup.data("url");
            insertLink(url);
        });
    });

})(jQuery);
