(function () {
    'use strict';

    var ctx = window.WPSN_TaskWorkbenchContext || null;
    if (!ctx || !ctx.enabled) {
        return;
    }

    var queueArgs = {};
    if (ctx.returnTo) {
        queueArgs.return_to = String(ctx.returnTo);
    }
    if (ctx.queueTitle) {
        queueArgs.wpsn_task_queue_title = String(ctx.queueTitle);
    }
    if (ctx.snapshotKey) {
        queueArgs.wpsn_task_queue_key = String(ctx.snapshotKey);
    }
    if (ctx.taskRef) {
        queueArgs.wpsn_task_ref = String(ctx.taskRef);
    }

    var transientKeys = ['wpsn_notice', 'wpsn_notice_type', '_wpnonce', 'wpsn_nonce', 'message', 'updated'];

    function getFileName(pathname) {
        var parts = String(pathname || '').split('/');
        return parts.length ? parts[parts.length - 1] : '';
    }

    function isSameAdminOrigin(url) {
        return url.origin === window.location.origin && /\/wp-admin\//.test(url.pathname);
    }

    function isWpsnPage(url) {
        var page = url.searchParams.get('page') || '';
        return page === 'wp-seo-next' || page.indexOf('wpsn-') === 0;
    }

    function supportsTarget(url) {
        if (!isSameAdminOrigin(url)) {
            return false;
        }

        var file = getFileName(url.pathname);
        if (file === 'admin-post.php') {
            return true;
        }

        if ((file === 'tools.php' || file === 'admin.php') && isWpsnPage(url)) {
            return true;
        }

        return false;
    }

    function currentWorkbenchUrl() {
        try {
            var url = new URL(window.location.href);
            transientKeys.forEach(function (key) {
                url.searchParams.delete(key);
            });
            return url.toString();
        } catch (err) {
            return window.location.href;
        }
    }

    function setIfMissing(url, key, value) {
        if (!value) {
            return;
        }
        if (!url.searchParams.has(key)) {
            url.searchParams.set(key, value);
        }
    }

    function ensureHiddenInput(form, name, value) {
        if (!value) {
            return;
        }

        var field = form.querySelector('input[name="' + name.replace(/"/g, '\\"') + '"]');
        if (!field) {
            field = document.createElement('input');
            field.type = 'hidden';
            field.name = name;
            form.appendChild(field);
        }
        field.value = value;
    }

    function ensureReturnTargets(url) {
        if (url.searchParams.has('return_to') || url.searchParams.has('return') || url.searchParams.has('back')) {
            return;
        }

        var workbenchUrl = currentWorkbenchUrl();
        url.searchParams.set('return_to', workbenchUrl);
        url.searchParams.set('return', workbenchUrl);
        url.searchParams.set('back', workbenchUrl);
    }

    function decorateAnchor(anchor) {
        if (!anchor || anchor.hasAttribute('data-wpsn-no-task-context')) {
            return;
        }

        var rawHref = anchor.getAttribute('href');
        if (!rawHref || rawHref.charAt(0) === '#') {
            return;
        }

        var url;
        try {
            url = new URL(rawHref, window.location.origin);
        } catch (err) {
            return;
        }

        if (!supportsTarget(url)) {
            return;
        }

        Object.keys(queueArgs).forEach(function (key) {
            setIfMissing(url, key, queueArgs[key]);
        });

        if (getFileName(url.pathname) === 'admin-post.php') {
            ensureReturnTargets(url);
        } else if (isWpsnPage(url)) {
            setIfMissing(url, 'return_to', ctx.returnTo || '');
        }

        anchor.href = url.toString();
    }

    function decorateForm(form) {
        if (!form || form.hasAttribute('data-wpsn-no-task-context')) {
            return;
        }

        var action = form.getAttribute('action') || window.location.href;
        var url;
        try {
            url = new URL(action, window.location.origin);
        } catch (err) {
            return;
        }

        if (!supportsTarget(url) && getFileName(url.pathname) !== 'tools.php' && getFileName(url.pathname) !== 'admin.php') {
            return;
        }

        Object.keys(queueArgs).forEach(function (key) {
            ensureHiddenInput(form, key, queueArgs[key]);
        });

        if (getFileName(url.pathname) === 'admin-post.php') {
            var workbenchUrl = currentWorkbenchUrl();
            if (!form.querySelector('input[name="return_to"], input[name="return"], input[name="back"]')) {
                ensureHiddenInput(form, 'return_to', workbenchUrl);
                ensureHiddenInput(form, 'return', workbenchUrl);
                ensureHiddenInput(form, 'back', workbenchUrl);
            }
        }

        if (supportsTarget(url)) {
            Object.keys(queueArgs).forEach(function (key) {
                setIfMissing(url, key, queueArgs[key]);
            });
            if (getFileName(url.pathname) !== 'admin-post.php') {
                setIfMissing(url, 'return_to', ctx.returnTo || '');
            }
            form.setAttribute('action', url.toString());
        }
    }

    function bootstrap() {
        document.querySelectorAll('a[href]').forEach(decorateAnchor);
        document.querySelectorAll('form').forEach(decorateForm);
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', bootstrap, { once: true });
    } else {
        bootstrap();
    }

    document.addEventListener('click', function (event) {
        var anchor = event.target && event.target.closest ? event.target.closest('a[href]') : null;
        if (anchor) {
            decorateAnchor(anchor);
        }
    }, true);

    document.addEventListener('submit', function (event) {
        var form = event.target;
        if (form && form.tagName === 'FORM') {
            decorateForm(form);
        }
    }, true);
})();
