(function () {
    'use strict';

    function fallbackCopy(input) {
        input.focus();
        input.select();
        input.setSelectionRange(0, input.value.length);
        return document.execCommand('copy');
    }

    function showCopyResult(button, succeeded) {
        var original = button.getAttribute('data-nexdirectory-copy-label') || button.textContent;
        button.setAttribute('data-nexdirectory-copy-label', original);
        button.textContent = succeeded ? 'Copied' : 'Select and copy';

        window.setTimeout(function () {
            button.textContent = original;
        }, 1800);
    }

    document.addEventListener('click', function (event) {
        var button = event.target.closest('[data-nexdirectory-copy-button]');
        var rotateTrigger = event.target.closest('[data-nexdirectory-pass-rotate-trigger]');
        var rotateCancel = event.target.closest('[data-nexdirectory-pass-rotate-cancel]');
        var confirmation;
        var key;
        var input;
        var value;
        var copyPromise;

        if (rotateTrigger) {
            confirmation = document.getElementById(rotateTrigger.getAttribute('aria-controls'));
            if (confirmation) {
                confirmation.hidden = false;
                rotateTrigger.setAttribute('aria-expanded', 'true');
                confirmation.querySelector('[type="submit"]').focus();
            }
            return;
        }

        if (rotateCancel) {
            confirmation = rotateCancel.closest('[data-nexdirectory-pass-rotate-confirmation]');
            if (confirmation) {
                confirmation.hidden = true;
                rotateTrigger = document.querySelector(
                    '[data-nexdirectory-pass-rotate-trigger][aria-controls="' + confirmation.id + '"]'
                );
                if (rotateTrigger) {
                    rotateTrigger.setAttribute('aria-expanded', 'false');
                    rotateTrigger.focus();
                }
            }
            return;
        }

        if (!button) {
            return;
        }

        key = button.getAttribute('data-nexdirectory-copy-button');
        input = document.querySelector('[data-nexdirectory-copy-source="' + key + '"]');
        if (!input) {
            return;
        }

        value = input.value || input.textContent || '';
        if (!value) {
            return;
        }

        if (navigator.clipboard && window.isSecureContext) {
            copyPromise = navigator.clipboard.writeText(value);
            copyPromise.then(function () {
                showCopyResult(button, true);
            }).catch(function () {
                showCopyResult(button, fallbackCopy(input));
            });
            return;
        }

        showCopyResult(button, fallbackCopy(input));
    });
}());
