jQuery(document).ready(function ($) {
    'use strict';

    // Find the deactivate link for our plugin
    const pluginSlug = admilogu_deactivation.plugin_slug;
    const $deactivateLink = $(`tr[data-plugin*="${pluginSlug}"] .deactivate a`);

    if (!$deactivateLink.length) {
        return;
    }

    let deactivateUrl = '';

    // Intercept deactivate click
    $deactivateLink.on('click', function (e) {
        e.preventDefault();
        deactivateUrl = $(this).attr('href');
        showDeactivationModal();
    });

    function showDeactivationModal() {
        // Create modal HTML
        const modalHTML = `
            <div id="adminlgb-deactivation-modal" class="adminlgb-modal-overlay">
                <div class="adminlgb-modal-container">
                    <div class="adminlgb-modal-header">
                        <h2>Deactivation Reason</h2>
                        <button class="adminlgb-modal-close">&times;</button>
                    </div>
                    <div class="adminlgb-modal-body">
                        <div class="adminlgb-reasons-grid">
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="Just Debugging">
                                <span class="adminlgb-reason-icon dashicons dashicons-admin-tools"></span>
                                <span class="adminlgb-reason-text">Just Debugging</span>
                            </label>
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="Plugin Issues">
                                <span class="adminlgb-reason-icon dashicons dashicons-warning"></span>
                                <span class="adminlgb-reason-text">Plugin Issues</span>
                            </label>
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="Slow Performance">
                                <span class="adminlgb-reason-icon dashicons dashicons-update"></span>
                                <span class="adminlgb-reason-text">Slow Performance</span>
                            </label>
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="Switched to Alternative">
                                <span class="adminlgb-reason-icon dashicons dashicons-randomize"></span>
                                <span class="adminlgb-reason-text">Switched to Alternative</span>
                            </label>
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="No Longer Needed">
                                <span class="adminlgb-reason-icon dashicons dashicons-archive"></span>
                                <span class="adminlgb-reason-text">No Longer Needed</span>
                            </label>
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="Compatibility Issues">
                                <span class="adminlgb-reason-icon dashicons dashicons-dismiss"></span>
                                <span class="adminlgb-reason-text">Compatibility Issues</span>
                            </label>
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="Missing Feature">
                                <span class="adminlgb-reason-icon dashicons dashicons-star-empty"></span>
                                <span class="adminlgb-reason-text">Missing Feature</span>
                            </label>
                            <label class="adminlgb-reason-option">
                                <input type="radio" name="deactivation_reason" value="Other Reason">
                                <span class="adminlgb-reason-icon dashicons dashicons-editor-help"></span>
                                <span class="adminlgb-reason-text">Other Reason</span>
                            </label>
                        </div>

                        <div class="adminlgb-details-section" style="display: none;">
                            <textarea 
                                id="adminlgb-details" 
                                placeholder="Please share the reason"
                                rows="4"
                            ></textarea>
                        </div>

                        <div class="adminlgb-contact-section">
                            <p class="adminlgb-contact-text">
                                After submitting, we'll get in touch with you via email to provide the support you need. 
                                If you require any help, please <a href="https://wordpress.org/support/plugin/admin-login-guard-branding/" target="_blank">Create A Ticket</a>, 
                                we reply within 24 working hours.
                            </p>
                            
                            <label class="adminlgb-checkbox-label">
                                <input type="checkbox" id="adminlgb-agree-contact">
                                <span>I agree to be contacted via email for support with this plugin.</span>
                            </label>
                        </div>
                    </div>
                    <div class="adminlgb-modal-footer">
                        <a href="#" class="adminlgb-link-skip">Skip &amp; Deactivate</a>
                        <button class="adminlgb-btn-submit" disabled>Submit &amp; Deactivate</button>
                    </div>
                </div>
            </div>
        `;

        // Append modal to body
        $('body').append(modalHTML);

        const $modal = $('#adminlgb-deactivation-modal');
        const $detailsSection = $('.adminlgb-details-section');
        const $agreeCheckbox = $('#adminlgb-agree-contact');
        const $submitBtn = $('.adminlgb-btn-submit');

        // Function to check if submit should be enabled
        function updateSubmitButton() {
            const hasReason = $('input[name="deactivation_reason"]:checked').length > 0;
            const hasConsent = $agreeCheckbox.is(':checked');

            if (hasReason || hasConsent) {
                $submitBtn.prop('disabled', false);
            } else {
                $submitBtn.prop('disabled', true);
            }
        }

        // Show details textarea when a reason is selected
        $('input[name="deactivation_reason"]').on('change', function () {
            $('.adminlgb-reason-option').removeClass('is-selected');
            $(this).closest('.adminlgb-reason-option').addClass('is-selected');
            $detailsSection.slideDown();
            updateSubmitButton();
        });

        // Update submit button when checkbox changes
        $agreeCheckbox.on('change', function () {
            updateSubmitButton();
        });

        // Close modal
        $('.adminlgb-modal-close, .adminlgb-modal-overlay').on('click', function (e) {
            if (e.target === this) {
                $modal.remove();
            }
        });

        // Close modal on escape key
        $(document).on('keydown.admiloguDeactivate', function (e) {
            if (e.key === 'Escape') {
                $modal.remove();
                $(document).off('keydown.admiloguDeactivate');
            }
        });

        // Skip & Deactivate
        $('.adminlgb-link-skip').on('click', function (e) {
            e.preventDefault();
            window.location.href = deactivateUrl;
        });

        // Submit & Deactivate
        $('.adminlgb-btn-submit').on('click', function () {
            const reason = $('input[name="deactivation_reason"]:checked').val() || '';
            const details = $('#adminlgb-details').val();
            const agreeContact = $agreeCheckbox.is(':checked') ? 'yes' : 'no';

            // Disable button to prevent double submission
            $(this).prop('disabled', true).text('Submitting...');

            // Send AJAX request
            $.ajax({
                url: admilogu_deactivation.ajax_url,
                type: 'POST',
                data: {
                    action: 'admilogu_submit_deactivation_reason',
                    nonce: admilogu_deactivation.nonce,
                    reason: reason,
                    details: details,
                    agree_contact: agreeContact
                },
                success: function () {
                    window.location.href = deactivateUrl;
                },
                error: function () {
                    window.location.href = deactivateUrl;
                }
            });
        });
    }
});
