/**
 * JavaScript for Dropbox functionality in the Text to Speech TTS plugin.
 *
 * This file handles the Dropbox "Test Connection" button functionality
 * and requires the PRO plugin to be active.
 */

(function($) {
    'use strict';

    // Only initialize if the PRO plugin is not active
    if (typeof mementorTTSProAdmin === 'undefined') {
        jQuery(document).ready(function($) {
            // Check if the Test Connection button exists
            if ($('#mementor-tts-test-dropbox-connection').length > 0) {
                $('#mementor-tts-test-dropbox-connection').on('click', function(e) {
                    e.preventDefault();
                    
                    var $button = $(this);
                    var $result = $('#mementor-tts-test-dropbox-result');
                    var $spinner = $('#dropbox-test-spinner');
                    
                    $button.prop('disabled', true).text('Testing...');
                    $spinner.addClass('is-active');
                    $result.html('<p>Testing connection to Dropbox...</p>');
                    
                    // Get the token value from the input field
                    var token = $('#mementor_tts_dropbox_token').val();
                    
                    // If token is empty, show error
                    if (!token) {
                        $result.html('<p class="error">Please enter a Dropbox access token first.</p>');
                        $button.prop('disabled', false).text('Test Connection');
                        $spinner.removeClass('is-active');
                        return;
                    }
                    
                    // Ensure we have the admin ajax data
                    if (typeof mementorTTSAdmin === 'undefined' || !mementorTTSAdmin.ajaxurl || !mementorTTSAdmin.nonce) {
                        $result.html('<p class="error">PRO plugin is required for Dropbox functionality.</p>');
                        $button.prop('disabled', false).text('Test Connection');
                        $spinner.removeClass('is-active');
                        return;
                    }
                    
                    // Send Ajax request to test the connection
                    $.ajax({
                        url: mementorTTSAdmin.ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'mementor_tts_test_dropbox_connection',
                            mementor_tts_test_dropbox_nonce: mementorTTSAdmin.nonce,
                            token: token
                        },
                        success: function(response) {
                            if (window.mementorTTSDebug) window.mementorTTSDebug.log('Dropbox test response:', response);
                            $spinner.removeClass('is-active');
                            $button.prop('disabled', false).text('Test Connection');
                            
                            if (response.success) {
                                $result.html('<p class="success"></p>').find('p').text(response.data.message);
                                if (response.data.account) {
                                    $result.append($('<p></p>').text('Connected as: ' + response.data.account));
                                }
                            } else {
                                let errorMessage = 'Unknown error';
                                if (response.data && response.data.message) {
                                    errorMessage = response.data.message;
                                }
                                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Dropbox error details:', response);
                                $result.html('<p class="error"></p>').find('p').text('Error: ' + errorMessage);
                            }
                        },
                        error: function(xhr, status, error) {
                            if (window.mementorTTSDebug) {
                                window.mementorTTSDebug.error('Dropbox test error:', status, error);
                                window.mementorTTSDebug.log('Response text:', xhr.responseText);
                            }
                            
                            let errorMessage = error || 'Connection failed';
                            try {
                                const responseData = JSON.parse(xhr.responseText);
                                if (responseData && responseData.data && responseData.data.message) {
                                    errorMessage = responseData.data.message;
                                }
                            } catch (e) {
                                if (window.mementorTTSDebug) window.mementorTTSDebug.error('Failed to parse error response:', e);
                            }
                            
                            $spinner.removeClass('is-active');
                            $button.prop('disabled', false).text('Test Connection');
                            $result.html('<p class="error"></p>').find('p').text('Error connecting to Dropbox: ' + errorMessage);
                        }
                    });
                });
            }
        });
    } else {
        if (window.mementorTTSDebug) window.mementorTTSDebug.log('PRO plugin active, using PRO version of Dropbox integration');
    }
})(jQuery);
