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
    $(document).on('click', '.kc-ml-copy-link', function (e) {
        e.preventDefault();
        var url = $(this).data('magic-url');
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(function () {
                alert(__('Magic link copied to clipboard!', 'magic-link'));
            });
        } else {
            var $temp = $('<input>');
            $('body').append($temp);
            $temp.val(url).select();
            document.execCommand('copy');
            $temp.remove();
            alert(__('Magic link copied to clipboard!', 'magic-link'));
        }
    });
});
