/**
 * Tam Rank — Auto-redirect on delete
 *
 * Handles admin notices for individual + bulk delete redirect prompts.
 * Server state: user-scoped transient `tamrank_pending_redirects_{user_id}`.
 */
(function ($) {
    'use strict';

    if (typeof tamrankAutoRedirect === 'undefined') {
        return;
    }

    var i18n = tamrankAutoRedirect.i18n || {};
    var ajaxUrl = tamrankAutoRedirect.ajaxUrl;

    function sprintf(str, args) {
        var i = 0;
        return str.replace(/%[ds]/g, function () {
            var v = args[i++];
            return typeof v === 'undefined' ? '' : v;
        });
    }

    function resolveTarget($notice) {
        var $select = $notice.find('.tr-redirect-target-select, .tr-redirect-bulk-target-select').first();
        var val = $select.val();
        if (val === 'custom') {
            var $input = $notice.find('.tr-redirect-custom-url');
            var url = ($input.val() || '').trim();
            if (! url) {
                return { error: i18n.customUrlRequired || 'Please enter a URL.' };
            }
            return { url: url };
        }
        var url = $select.find('option:selected').data('url');
        return { url: url };
    }

    function replaceNoticeWithMessage($notice, type, message) {
        var $p = $('<p></p>').text(message);
        $notice.removeClass('notice-info notice-warning notice-error')
            .addClass('notice-' + (type === 'error' ? 'error' : 'success'));
        $notice.empty().append($p);
        setTimeout(function () {
            $notice.fadeOut(400, function () { $notice.remove(); });
        }, 4000);
    }

    // Reload page after a short delay so new redirects appear in the table.
    // Only reload on admin pages where the user is likely looking at redirect data
    // (Redirects manager, 404 monitor). Elsewhere, skip to avoid jarring reloads.
    function maybeReloadAfterSuccess() {
        var params = new URLSearchParams(window.location.search);
        var page = params.get('page') || '';
        var reloadPages = ['tam-rank-redirects', 'tam-rank-404'];
        if (reloadPages.indexOf(page) !== -1) {
            setTimeout(function () { window.location.reload(); }, 1200);
        }
    }

    // Toggle custom URL input on select change
    $(document).on('change', '.tr-redirect-target-select, .tr-redirect-bulk-target-select', function () {
        var $select = $(this);
        var $input = $select.closest('.tr-redirect-prompt-form').find('.tr-redirect-custom-url');
        if ($select.val() === 'custom') {
            $input.show().focus();
        } else {
            $input.hide();
        }
    });

    // Individual: Create redirect
    $(document).on('click', '.tr-redirect-create-btn', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var $notice = $btn.closest('.tr-redirect-prompt');
        var postId = $btn.data('post-id');
        var nonce = $btn.data('nonce');
        var target = resolveTarget($notice);

        if (target.error) {
            alert(target.error);
            return;
        }

        $btn.prop('disabled', true);

        $.post(ajaxUrl, {
            action: 'tamrank_create_delete_redirect',
            nonce: nonce,
            post_id: postId,
            target_url: target.url
        }).done(function (res) {
            if (res && res.success) {
                var incoming = parseInt(res.data.incoming_count || 0, 10);
                var msg = incoming > 0
                    ? sprintf(i18n.successWithChain, [incoming])
                    : (i18n.success || 'Redirect created.');
                replaceNoticeWithMessage($notice, 'success', msg);
                maybeReloadAfterSuccess();
            } else {
                var errMsg = (res && res.data && res.data.i18n) || (res && res.data && res.data.detail) || (res && res.data && res.data.message) || 'error';
                replaceNoticeWithMessage($notice, 'error', sprintf(i18n.error, [errMsg]));
                $btn.prop('disabled', false);
            }
        }).fail(function (xhr) {
            var d = xhr.responseJSON && xhr.responseJSON.data;
            var errMsg = (d && (d.i18n || d.detail || d.message)) || 'network_error';
            replaceNoticeWithMessage($notice, 'error', sprintf(i18n.error, [errMsg]));
            $btn.prop('disabled', false);
        });
    });

    // Bulk: Create redirects
    $(document).on('click', '.tr-redirect-bulk-create-btn', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var $notice = $btn.closest('.tr-redirect-prompt');
        var nonce = $btn.data('nonce');
        var target = resolveTarget($notice);

        if (target.error) {
            alert(target.error);
            return;
        }

        $btn.prop('disabled', true);

        $.post(ajaxUrl, {
            action: 'tamrank_create_bulk_delete_redirects',
            nonce: nonce,
            target_url: target.url
        }).done(function (res) {
            if (res && res.success) {
                var d = res.data || {};
                var created = parseInt(d.created || 0, 10);
                var skipped = parseInt(d.skipped || 0, 10);
                var failed = parseInt(d.failed || 0, 10);
                var overflow = parseInt(d.overflow_skipped || 0, 10);

                var msg;
                if (failed > 0) {
                    msg = sprintf(i18n.bulkErrors, [created, failed]);
                } else if (overflow > 0 || skipped > 0) {
                    msg = sprintf(i18n.bulkPartialSuccess, [created, overflow + skipped]);
                } else {
                    msg = sprintf(i18n.bulkSuccess, [created]);
                }
                replaceNoticeWithMessage($notice, failed > 0 ? 'error' : 'success', msg);
                if (created > 0) {
                    maybeReloadAfterSuccess();
                }
            } else {
                var errMsg = (res && res.data && res.data.i18n) || (res && res.data && res.data.message) || 'error';
                replaceNoticeWithMessage($notice, 'error', sprintf(i18n.error, [errMsg]));
                $btn.prop('disabled', false);
            }
        }).fail(function (xhr) {
            var d = xhr.responseJSON && xhr.responseJSON.data;
            var errMsg = (d && (d.i18n || d.detail || d.message)) || 'network_error';
            replaceNoticeWithMessage($notice, 'error', sprintf(i18n.error, [errMsg]));
            $btn.prop('disabled', false);
        });
    });

    // Dismiss (both individual and bulk)
    $(document).on('click', '.tr-redirect-dismiss-btn', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var $notice = $btn.closest('.tr-redirect-prompt');
        var nonce = $btn.data('nonce');
        var isBulk = $btn.data('bulk') == 1 || $notice.hasClass('tr-redirect-prompt--bulk');

        var data = {
            action: 'tamrank_dismiss_delete_redirect',
            nonce: nonce
        };
        if (isBulk) {
            data.bulk = 1;
        } else {
            data.post_id = $btn.data('post-id');
        }

        $.post(ajaxUrl, data);
        $notice.fadeOut(300, function () { $notice.remove(); });
    });

    // Native WP dismiss ("x" from is-dismissible) also clears the server-side
    // transient so the prompt does not reappear on the next admin page load.
    $(document).on('click', '.tr-redirect-prompt .notice-dismiss', function () {
        var $notice = $(this).closest('.tr-redirect-prompt');
        var nonce = $notice.find('[data-nonce]').first().data('nonce');
        if (!nonce) { return; }
        var data = {
            action: 'tamrank_dismiss_delete_redirect',
            nonce: nonce
        };
        if ($notice.hasClass('tr-redirect-prompt--bulk')) {
            data.bulk = 1;
        } else {
            data.post_id = $notice.data('post-id');
        }
        $.post(ajaxUrl, data);
    });

})(jQuery);
