(function ($) {
    'use strict';

    function buildPopupMarkup() {
        return `
            <div id="tw-lem-rating-popup-overlay" class="tw-lem-rating-popup-overlay" aria-hidden="true">
                <div class="tw-lem-rating-popup" role="dialog" aria-modal="true" aria-labelledby="tw-lem-rating-popup-title">
                    <button type="button" class="tw-lem-rating-popup-close" aria-label="Close">×</button>
                    <div class="tw-lem-rating-popup-header">
                        <h2 id="tw-lem-rating-popup-title">${tw_lem_rating_popup_vars.popupTitle}</h2>
                        <p>${tw_lem_rating_popup_vars.popupText}</p>
                    </div>
                    <form id="tw-lem-rating-popup-form" class="tw-lem-rating-popup-form">
                        <div class="tw-lem-rating-star-group">
                            <label class="tw-lem-rating-label">${tw_lem_rating_popup_vars.ratingLabel}</label>
                            <div class="tw-lem-rating-stars" role="radiogroup" aria-label="Rating stars">
                                <button type="button" class="tw-lem-rating-star" data-value="1" aria-pressed="false">★</button>
                                <button type="button" class="tw-lem-rating-star" data-value="2" aria-pressed="false">★</button>
                                <button type="button" class="tw-lem-rating-star" data-value="3" aria-pressed="false">★</button>
                                <button type="button" class="tw-lem-rating-star" data-value="4" aria-pressed="false">★</button>
                                <button type="button" class="tw-lem-rating-star" data-value="5" aria-pressed="false">★</button>
                            </div>
                        </div>
                        <div class="tw-lem-rating-field">
                            <label for="tw-lem-rating-message">${tw_lem_rating_popup_vars.messageLabel}</label>
                            <textarea id="tw-lem-rating-message" name="message" placeholder="${tw_lem_rating_popup_vars.messagePlaceholder}"></textarea>
                        </div>
                        <div class="tw-lem-rating-consent-field">
                            <label class="tw-lem-consent-label">
                                <input type="checkbox" id="tw-lem-consent-checkbox" name="consent_given" value="1">
                                <span>${tw_lem_rating_popup_vars.consentLabel}</span>
                            </label>
                        </div>
                        <div class="tw-lem-rating-error" aria-live="polite"></div>
                        <div class="tw-lem-rating-actions">
                            <button type="button" class="button button-primary tw-lem-rating-submit">${tw_lem_rating_popup_vars.submitLabel}</button>
                            <button type="button" class="button tw-lem-rating-cancel">${tw_lem_rating_popup_vars.closeLabel}</button>
                        </div>
                        <input type="hidden" name="action" value="tw_lem_send_rating_feedback">
                        <input type="hidden" name="rating" id="tw-lem-rating-value" value="">
                        <input type="hidden" name="source_page" value="${tw_lem_rating_popup_vars.sourcePage}">
                        <input type="hidden" name="_wpnonce" value="${tw_lem_rating_popup_vars.feedbackNonce}">
                    </form>
                </div>
            </div>`;
    }

    function sendPopupEvent(action) {
        var data = new FormData();
        data.append('action', 'tw_lem_record_rating_popup_shown');
        data.append('_wpnonce', tw_lem_rating_popup_vars.nonce);
        data.append('event', action);

        fetch(tw_lem_rating_popup_vars.ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            body: data,
        }).catch(function () {});
    }

    function updateStars($stars, value) {
        $stars.each(function () {
            var starValue = parseInt($(this).attr('data-value'), 10);
            var isActive = starValue <= value;
            $(this).toggleClass('active', isActive);
            $(this).attr('aria-pressed', isActive ? 'true' : 'false');
        });
    }

    $(document).ready(function () {
        if (!window.tw_lem_rating_popup_vars || !tw_lem_rating_popup_vars.ajaxUrl) {
            return;
        }

        var $popupOverlay = $(buildPopupMarkup());
        $('body').append($popupOverlay);

        var $popup = $popupOverlay.find('.tw-lem-rating-popup');
        var $stars = $popup.find('.tw-lem-rating-star');
        var $ratingValue = $popup.find('#tw-lem-rating-value');
        var $error = $popup.find('.tw-lem-rating-error');
        var $messageField = $popup.find('#tw-lem-rating-message');
        var pendingDeactivationUrl = '';
        var pluginBasename = tw_lem_rating_popup_vars.pluginBasename || '';
        var hasReviewed = !!tw_lem_rating_popup_vars.hasReviewed;
        var isPluginList = !!tw_lem_rating_popup_vars.isPluginList;

        function setPopupMode(isDeactivation) {
            if (isDeactivation) {
                $popup.find('#tw-lem-rating-popup-title').text(tw_lem_rating_popup_vars.deactivationPopupTitle);
                $popup.find('.tw-lem-rating-popup-header p').text(tw_lem_rating_popup_vars.deactivationPopupText);
            } else {
                $popup.find('#tw-lem-rating-popup-title').text(tw_lem_rating_popup_vars.popupTitle);
                $popup.find('.tw-lem-rating-popup-header p').text(tw_lem_rating_popup_vars.popupText);
            }
        }

        function closePopup() {
            $popupOverlay.removeClass('visible');
            if (pendingDeactivationUrl) {
                setTimeout(function () {
                    var url = pendingDeactivationUrl;
                    pendingDeactivationUrl = '';
                    window.location.href = url;
                }, 250);
            }
        }

        function showError(text) {
            $error.text(text);
        }

        function clearError() {
            $error.text('');
        }

        function submitFeedback() {
            clearError();
            var rating = parseInt($ratingValue.val(), 10);
            var message = $messageField.val().trim();

            if (!rating || rating < 1 || rating > 5) {
                showError(tw_lem_rating_popup_vars.ratingRequired);
                return;
            }

            var consentGiven = $('#tw-lem-consent-checkbox').is(':checked');

            if (!consentGiven) {
                showError('Please agree to the consent terms before submitting your feedback.');
                return;
            }

            var data = new FormData();
            data.append('action', 'tw_lem_send_rating_feedback');
            data.append('_wpnonce', tw_lem_rating_popup_vars.feedbackNonce);
            data.append('rating', rating);
            data.append('message', message);
            data.append('source_page', tw_lem_rating_popup_vars.sourcePage);

            fetch(tw_lem_rating_popup_vars.ajaxUrl, {
                method: 'POST',
                credentials: 'same-origin',
                body: data,
            })
                .then(function (response) {
                    return response.json();
                })
                .then(function (json) {
                    if (json.success) {
                        $popup.find('.tw-lem-rating-popup-header').html('<h2>' + tw_lem_rating_popup_vars.thankYouTitle + '</h2><p>' + json.data.message + '</p>');
                        $popup.find('.tw-lem-rating-star-group, .tw-lem-rating-field, .tw-lem-rating-consent-field, .tw-lem-rating-actions').remove();
                        if (pendingDeactivationUrl) {
                            setTimeout(function () {
                                var url = pendingDeactivationUrl;
                                pendingDeactivationUrl = '';
                                window.location.href = url;
                            }, 1800);
                        } else {
                            setTimeout(closePopup, 1800);
                        }
                    } else {
                        showError(json.data && json.data.message ? json.data.message : tw_lem_rating_popup_vars.defaultError);
                    }
                })
                .catch(function () {
                    showError(tw_lem_rating_popup_vars.defaultError);
                });
        }

        if (isPluginList && !hasReviewed && pluginBasename) {
            $(document).on('click', 'tr[data-plugin="' + pluginBasename + '"] .deactivate a', function (event) {
                event.preventDefault();
                event.stopImmediatePropagation();
                pendingDeactivationUrl = this.href;
                setPopupMode(true);
                $popupOverlay.addClass('visible');
                sendPopupEvent('shown');
            });
        }

        $popupOverlay.on('click', '.tw-lem-rating-popup-close, .tw-lem-rating-cancel', function (event) {
            event.preventDefault();
            sendPopupEvent('dismiss');
            closePopup();
        });

        $popupOverlay.on('click', '.tw-lem-rating-star', function (event) {
            event.preventDefault();
            var value = parseInt($(this).attr('data-value'), 10);
            if (!value) {
                return;
            }
            updateStars($stars, value);
            $ratingValue.val(value);
            clearError();
        });

        $popupOverlay.on('click', '.tw-lem-rating-submit', function (event) {
            event.preventDefault();
            submitFeedback();
        });

        if (tw_lem_rating_popup_vars.showPopupImmediately && !isPluginList) {
            setTimeout(function () {
                $popupOverlay.addClass('visible');
                sendPopupEvent('shown');
            }, 800);
        }
    });
})(jQuery);
