/**
 * signwpdf PDF Sign & Fill - License Page Admin JS
 * 
 * Handles AJAX activation, deactivation, and status checks.
 * Soft activation - plugin works without activation.
 */
(function($) {
    'use strict';

    // Copy to clipboard function
    function copyToClipboard(text, button) {
        navigator.clipboard.writeText(text).then(function() {
            var $btn = $(button);
            var originalHtml = $btn.html();
            $btn.html('<span class="dashicons dashicons-yes"></span> Copied!');
            setTimeout(function() {
                $btn.html(originalHtml);
            }, 1500);
        }).catch(function(err) {
            console.error('Failed to copy:', err);
            alert('Failed to copy to clipboard');
        });
    }
    
    // Copy diagnostics to clipboard (called from license page)
    $(document).on('click', '#psf-copy-diagnostics', function() {
        var $textarea = $('#psf-debug-info');
        var text = $textarea.val();
        copyToClipboard(text, this);
    });

    // Show message in the messages container
    function showMessage(message, type) {
        var $container = $('#psf-license-messages');
        var noticeClass = 'notice-' + (type || 'info');
        var $notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + message + '</p></div>');
        
        $container.html($notice);
        
        // Make dismissible
        $notice.on('click', '.notice-dismiss', function() {
            $notice.fadeOut(function() { $(this).remove(); });
        });
        
        // Auto-dismiss success messages
        if (type === 'success') {
            setTimeout(function() {
                $notice.fadeOut(function() { $(this).remove(); });
            }, 5000);
        }
    }

    // Set button loading state
    function setButtonLoading($button, loading) {
        if (loading) {
            $button.prop('disabled', true);
            $button.find('.psf-btn-spinner').addClass('is-active').css('visibility', 'visible');
        } else {
            $button.prop('disabled', false);
            $button.find('.psf-btn-spinner').removeClass('is-active').css('visibility', 'hidden');
        }
    }

    // Update UI after status change
    function updateUI(data) {
        var status = data.status || 'none';
        var isActivated = (status === 'active' || status === 'grace');
        
        // Update badge
        var $badge = $('#psf-status-badge');
        $badge.removeClass('active grace expired invalid none').addClass(status);
        
        var statusText = {
            'active': 'Active',
            'grace': 'Grace Period',
            'expired': 'Expired',
            'invalid': 'Invalid',
            'none': 'Not Activated'
        };
        $badge.text(statusText[status] || 'Not Activated');
        
        // Toggle views
        if (isActivated) {
            $('#psf-activate-form').hide();
            $('#psf-activated-view').show();
            $('#psf-updates-notice').hide();
        } else {
            $('#psf-activate-form').show();
            $('#psf-activated-view').hide();
            $('#psf-updates-notice').show();
        }
        
        // Update status table if visible
        if (data.updates_allowed !== undefined) {
            var updatesHtml = data.updates_allowed 
                ? '<span class="psf-status-ok"><span class="dashicons dashicons-yes-alt"></span> Enabled</span>'
                : '<span class="psf-status-disabled"><span class="dashicons dashicons-minus"></span> Disabled</span>';
            $('#psf-updates-status').html(updatesHtml);
        }
        
        if (data.premium_support !== undefined) {
            var supportHtml = data.premium_support 
                ? '<span class="psf-status-ok"><span class="dashicons dashicons-yes-alt"></span> Enabled</span>'
                : '<span class="psf-status-disabled"><span class="dashicons dashicons-minus"></span> Disabled</span>';
            $('#psf-support-status').html(supportHtml);
        }
        
        // Handle notices
        if (status === 'grace') {
            $('#psf-grace-notice').show();
            $('#psf-expired-notice').hide();
        } else if (status === 'expired') {
            $('#psf-grace-notice').hide();
            $('#psf-expired-notice').show();
        } else {
            $('#psf-grace-notice').hide();
            $('#psf-expired-notice').hide();
        }
    }

    // Initialize when document is ready
    $(document).ready(function() {
        
        // Activate button
        $('#psf-activate-btn').on('click', function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var purchaseCode = $('#psf_purchase_code').val().trim();
            var email = $('#psf_buyer_email').val().trim();
            
            // Validate
            if (!purchaseCode) {
                showMessage('Please enter your purchase code.', 'error');
                $('#psf_purchase_code').focus();
                return;
            }
            
            setButtonLoading($button, true);
            
            $.ajax({
                url: swpdfLicense.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'swpdf_activate_license',
                    nonce: swpdfLicense.nonce,
                    purchase_code: purchaseCode,
                    email: email
                },
                success: function(response) {
                    if (response.success) {
                        showMessage(response.data.message || 'License activated successfully!', 'success');
                        updateUI(response.data);
                    } else {
                        showMessage(response.data.message || 'Activation failed.', 'error');
                    }
                },
                error: function(xhr, status, error) {
                    showMessage('Network error. Please check your connection and try again.', 'error');
                },
                complete: function() {
                    setButtonLoading($button, false);
                }
            });
        });
        
        // Deactivate button
        $('#psf-deactivate-btn').on('click', function(e) {
            e.preventDefault();
            
            if (!confirm('Are you sure you want to deactivate the license? Automatic updates will be disabled.')) {
                return;
            }
            
            var $button = $(this);
            setButtonLoading($button, true);
            
            $.ajax({
                url: swpdfLicense.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'swpdf_deactivate_license',
                    nonce: swpdfLicense.nonce
                },
                success: function(response) {
                    if (response.success) {
                        showMessage(response.data.message || 'License deactivated.', 'warning');
                        updateUI({ status: 'none', updates_allowed: false, premium_support: false });
                    } else {
                        showMessage(response.data.message || 'Deactivation failed.', 'error');
                    }
                },
                error: function() {
                    showMessage('Network error. Please try again.', 'error');
                },
                complete: function() {
                    setButtonLoading($button, false);
                }
            });
        });
        
        // Refresh status button
        $('#psf-refresh-btn').on('click', function(e) {
            e.preventDefault();
            
            var $button = $(this);
            setButtonLoading($button, true);
            
            $.ajax({
                url: swpdfLicense.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'swpdf_check_license_status',
                    nonce: swpdfLicense.nonce
                },
                success: function(response) {
                    if (response.success) {
                        showMessage(response.data.message || 'License status verified.', 'success');
                        updateUI(response.data);
                        
                        // Update timestamps
                        if (response.data.last_check) {
                            var lastCheck = new Date(response.data.last_check * 1000);
                            $('#psf-last-check').text(lastCheck.toLocaleString());
                        }
                        if (response.data.next_check) {
                            var nextCheck = new Date(response.data.next_check * 1000);
                            $('#psf-next-check').text(nextCheck.toLocaleString());
                        }
                    } else {
                        showMessage(response.data.message || 'Status check failed.', 'warning');
                        updateUI(response.data);
                    }
                },
                error: function() {
                    showMessage('Could not connect to license server. Please try again later.', 'error');
                },
                complete: function() {
                    setButtonLoading($button, false);
                }
            });
        });

        // Copy diagnostics button
        $('#psf-copy-diagnostics').on('click', function(e) {
            e.preventDefault();
            var debugText = $('#psf-debug-info').val();
            copyToClipboard(debugText, this);
        });

        // License Test Runner
        $('#psf-run-license-tests').on('click', function(e) {
            e.preventDefault();
            
            var $button = $(this);
            var $report = $('#psf-license-test-report');
            var $results = $('#psf-test-results');
            
            // Show report container
            $report.show();
            $results.html('<span style="color: #6b7280;">⏳ Running tests...</span>');
            
            setButtonLoading($button, true);
            
            $.ajax({
                url: swpdfLicense.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'swpdf_run_license_tests',
                    nonce: swpdfLicense.nonce
                },
                success: function(response) {
                    if (response.success && response.data) {
                        var results = response.data.results || {};
                        var html = '';
                        
                        // Build result lines
                        var testOrder = ['health', 'activate', 'status', 'updates', 'deactivate', 'final'];
                        testOrder.forEach(function(key) {
                            if (results[key]) {
                                var r = results[key];
                                var icon = r.success ? '✅' : '❌';
                                var color = r.success ? '#059669' : '#dc2626';
                                html += '<div style="margin-bottom: 8px; color: ' + color + ';">';
                                html += icon + ' <strong>' + r.name + '</strong>';
                                if (r.message) {
                                    html += ' — <span style="color: #4b5563;">' + r.message + '</span>';
                                }
                                html += '</div>';
                            }
                        });
                        
                        // Summary
                        html += '<hr style="border: none; border-top: 1px solid #e5e7eb; margin: 15px 0;">';
                        if (response.data.all_passed) {
                            html += '<div style="color: #059669; font-weight: bold;">🎉 All tests passed!</div>';
                        } else if (response.data.stopped_early) {
                            html += '<div style="color: #dc2626; font-weight: bold;">⚠️ Tests stopped early: ' + (response.data.message || '') + '</div>';
                        } else {
                            html += '<div style="color: #dc2626; font-weight: bold;">❌ Some tests failed</div>';
                        }
                        
                        $results.html(html);
                        
                        // Refresh the page UI after tests (since state changed)
                        setTimeout(function() {
                            // Trigger a status refresh to update UI
                            $('#psf-refresh-btn').trigger('click');
                        }, 1000);
                        
                    } else {
                        $results.html('<span style="color: #dc2626;">❌ Test runner error: ' + (response.data?.message || 'Unknown error') + '</span>');
                    }
                },
                error: function(xhr, status, error) {
                    $results.html('<span style="color: #dc2626;">❌ Network error: ' + error + '</span>');
                },
                complete: function() {
                    setButtonLoading($button, false);
                }
            });
        });

    });

})(jQuery);
