window.addEventListener("keydown", checkKey, false);

function getEditableContainer(element) {
    if (!element || typeof element.closest !== "function") {
        return null;
    }

    return element.closest('input, textarea, [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"], [role="textbox"], [role="searchbox"]');
}

function isElementEditable(element) {
    if (!element) {
        return false;
    }

    var editableContainer = getEditableContainer(element);
    if (editableContainer) {
        return true;
    }

    if (element.isContentEditable === true) {
        return true;
    }

    var contentEditableAttr = typeof element.getAttribute === "function" ? element.getAttribute("contenteditable") : null;
    if (contentEditableAttr && contentEditableAttr.toLowerCase() !== "false") {
        return true;
    }

    return false;
}

function isEventFromEditableContext(evt) {
    if (!evt) {
        return false;
    }

    if (isElementEditable(evt.target)) {
        return true;
    }

    if (isElementEditable(document.activeElement)) {
        return true;
    }

    var selection = window.getSelection ? window.getSelection() : null;
    if (selection && selection.anchorNode) {
        var anchorElement = selection.anchorNode.nodeType === 1 ? selection.anchorNode : selection.anchorNode.parentElement;
        if (isElementEditable(anchorElement)) {
            return true;
        }
    }

    if (typeof evt.composedPath === "function") {
        var path = evt.composedPath();
        for (var i = 0; i < path.length; i++) {
            if (isElementEditable(path[i])) {
                return true;
            }
        }
    }

    return false;
}

function checkKey(evt) {
    if (com_bzg_unite_del_key_disable == false) {
        return true;
    }

    evt = evt || window.event;
    const key = evt.key;
    var keyCode = evt.keyCode || evt.charCode;

    // Detect specific sites
    var isCopilotSite = window.location.hostname.includes("copilot.microsoft");
    var isRedditSite = window.location.hostname.includes("reddit");

    // General form elements (applies to all sites)
    const formElementsTags = ['INPUT', 'TEXTAREA', 'input', 'textarea'];
    const formElementsTypes = ['text', 'search', 'email', 'number', 'password', 'tel', 'url'];
    const formElementsIDs = ['username', 'userid', 'password', 'login'];

    // Add Reddit-specific form elements
    if (isRedditSite) {
        formElementsTags.push('reddit-search-large');
    }

    // Handle backspace, delete, and Copilot-specific keycode 51
    if (key === "Backspace" || key === "Delete" || keyCode == 8 || keyCode == 46 || (isCopilotSite && keyCode == 51)) {
        
        var tagName = evt.target.tagName;
        if (tagName) {
            var tagNameLower = tagName.toLowerCase();
            var tagNameFound = formElementsTags.some(tag => tagNameLower.includes(tag.toLowerCase()));
            if (tagNameFound) {
                return true;  // Allow backspace/delete in specific elements
            }
        }

        var type = evt.target.type;
        if (type && formElementsTypes.includes(type)) {
            return true;  // Allow backspace/delete in input types
        }

        var elementID = evt.target.id;
        if (elementID && formElementsIDs.includes(elementID)) {
            return true;  // Allow backspace/delete in specific IDs
        }

        var contentEditable = evt.target.contentEditable;
        if (contentEditable && (contentEditable === "true" || contentEditable.includes("text"))) {
            return true;  // Allow backspace/delete in content-editable elements
        }

        if (isEventFromEditableContext(evt)) {
            return true;  // Allow backspace/delete in complex editors (active element / shadow DOM / selection)
        }

        var role = evt.target.role;
        if (role && ['text', 'search', 'box'].includes(role.toLowerCase())) {
            return true;  // Allow backspace/delete in specific roles
        }

        var roleAttribute = typeof evt.target.getAttribute === "function" ? evt.target.getAttribute("role") : null;
        if (roleAttribute && ['textbox', 'searchbox', 'combobox'].includes(roleAttribute.toLowerCase())) {
            return true;  // Allow backspace/delete in ARIA text entry roles
        }

        var className = evt.target.className;
        if (className) {
            var classNameLower = className.toLowerCase();
            const formElementsClassNames = ['input', 'text', 'edit', 'cell', 'password', 'search', 'textarea', 'text-input', 'text-area', 'cib-serp-main', 'editor'];

            if (isRedditSite) {
                formElementsClassNames.push('reddit-search-large');  // Handle Reddit-specific elements
            }

            var classNameFound = formElementsClassNames.some(classNameTemp => classNameLower.includes(classNameTemp));
            if (classNameFound) {
                return true;  // Allow backspace/delete for specific classes
            }
        }

        // Prevent default action if no match found (site-specific actions)
        evt.preventDefault();
        evt.stopPropagation();
    } else {
        // Ensure # key and general shortcuts work on all sites
        return true;
    }
}
