const {__, _x, _n, _nx} = wp.i18n;

jQuery(document).ready(function ($) {
    $('.generate-magic-link').on('click', function () {
        var userId = $(this).data('user-id');
        var $linkContainer = $('#magic-link-' + userId);

        $.ajax({
            url: magicLinkAjax.ajax_url,
            type: 'POST',
            data: {
                action: 'generate_magic_link',
                user_id: userId,
                nonce: magicLinkAjax.nonce
            },
            success: function (response) {
                if (response.success) {
                    var magicLink = response.data.magic_link;
                    $linkContainer.html(
                        '<input type="text" value="' + magicLink + '" readonly><button class="copy-magic-link button">' + __('Copy', 'magic-link') + '</button>'
                    );
                } else {
                    alert('Error: ' + response.data);
                }
            }
        });
    });

    // Copy the magic link to clipboard
    $(document).on('click', '.copy-magic-link', function () {
        var $input = $(this).prev('input');
        $input.select();
        document.execCommand('copy');
        var message = __('Magic link copied to clipboard!', 'magic-link');
        alert(message);
    });

    // Highlight newly created magic link row.
    (function () {
        var urlParams = new URLSearchParams(window.location.search);
        var createdId = urlParams.get('created_id');
        if (createdId) {
            var $row = $(`table.wp-list-table tbody tr#item_id_${createdId}`);

            console.log($row);

            if ($row.length) {
                $row.css('background-color', '#fff8e1');
                setTimeout(function () {
                    $row.css('transition', 'background-color 3s ease');
                    $row.css('background-color', '');
                }, 100);
            }
        }
    })();

    // Copy magic link from list table row action.
    // After copying we surface confirmation with a "Copied!" tooltip that
    // briefly vibrates on the row, rather than a blocking alert.
    function showCopiedTooltip($trigger) {
        var $row = $trigger.closest('tr');

        // Wrap the button in a positioning context the first time it is
        // clicked. The wrapper carries position: relative so the tooltip
        // can sit directly above the button regardless of cell width.
        var $wrap = $trigger.parent('.kc-ml-copy-wrap');
        if (!$wrap.length) {
            $trigger.wrap('<span class="kc-ml-copy-wrap"></span>');
            $wrap = $trigger.parent('.kc-ml-copy-wrap');
        }

        // Remove any tooltip still on the way out so a rapid second click
        // does not stack indicators.
        $wrap.find('.kc-ml-copied-tooltip').remove();

        var label = __('Copied!', 'magic-link');
        var $tip  = $('<span class="kc-ml-copied-tooltip" role="status" aria-live="polite"></span>').text(label);
        $wrap.append($tip);

        // Force a layout pass so the transition fires when we add the class.
        $tip[0].offsetWidth; // eslint-disable-line no-unused-expressions
        $tip.addClass('is-visible');
        $row.addClass('kc-ml-row-vibrate');

        setTimeout(function () {
            $row.removeClass('kc-ml-row-vibrate');
        }, 420);

        setTimeout(function () {
            $tip.removeClass('is-visible');
            setTimeout(function () { $tip.remove(); }, 200);
        }, 1500);
    }

    $(document).on('click', '.kc-ml-copy-link', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var url  = $btn.data('magic-url');

        var done = function () { showCopiedTooltip($btn); };

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(done).catch(function () {
                // Fall through to the execCommand path on permission denial.
                fallbackCopy(url);
                done();
            });
        } else {
            fallbackCopy(url);
            done();
        }
    });

    function fallbackCopy(url) {
        var $temp = $('<input>');
        $('body').append($temp);
        $temp.val(url).select();
        document.execCommand('copy');
        $temp.remove();
    }
});
