<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Display typing text for this section
if (function_exists('aysa_display_typing_text_section')) {
    $tone_of_voice_text = "Define the desired tone of voice for your brand's content. Whether you prefer a formal, casual, or witty style, Aysa will use this to help generate content suggestions that resonate with your audience.";
    echo aysa_display_typing_text_section($tone_of_voice_text, 'tone-of-voice');
}
?>

<div class="aysa-wizard-section">
    <div class="aysa-wizard-header">
        <h2>TONE of Voice</h2>
        <p class="aysa-text-muted">Select the tone of voice that best suits your brand and audience. This will guide the AI in generating content that aligns with your communication style.</p>
    
    <div class="aysa-info-box">
            <span class="dashicons dashicons-info-outline"></span>
            <p>Your tone of voice helps establish a consistent brand personality across all your content. Choose the tone that best represents how you want to communicate with your audience.</p>
        </div>
    </div>
    
    <form id="aysa-tone-form" method="post">
        <input type="hidden" name="action" value="aysa_save_wizard_data">
        <input type="hidden" name="step" value="tone-of-voice">
        <input type="hidden" name="nonce" value="<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>">
        <div class="aysa-form-container">
            <div class="aysa-tone-options">
                <!-- Tone options will be dynamically populated -->
                </div>
            <!-- <div class="aysa-button-container">
                <button type="button" id="save-tone" class="aysa-button-primary">
                    <span class="dashicons dashicons-saved"></span> Save
                </button>
            </div> -->
        </div>
    </form>
                </div>
                
<style>
.aysa-wizard-section {
    max-width: 100%;
    margin: 24px;
    padding: 0;
    font-family: 'Roboto', sans-serif;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.aysa-wizard-header {
    padding: 24px 32px;
    border-bottom: 1px solid #e0e0e0;
}

.aysa-wizard-header h2 {
    font-size: 24px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
}

.aysa-text-muted {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 16px;
}

.aysa-info-box {
    background: #f8f9fa;
    border-left: 4px solid #0066ff;
    padding: 16px;
    border-radius: 4px;
    margin: 16px 0 0 0;
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.aysa-info-box .dashicons {
    font-size: 24px;
    color: #0066ff;
    width: 24px;
    height: 24px;
}

.aysa-info-box p {
    margin: 0;
    font-size: 14px;
    color: #1a1a1a;
    line-height: 1.6;
}

.aysa-form-container {
    padding: 32px;
}

.aysa-tone-options {
    display: flex;
    flex-direction: column;
    gap: 16px;
    margin-bottom: 32px;
}

.tone-option {
    display: flex;
    align-items: flex-start;
    padding: 16px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    background: #fff;
    user-select: none;
}

.tone-option:hover {
    border-color: #0066ff;
    background-color: #f8f9fa;
}

.tone-option.selected {
    border-color: #0066ff;
    background-color: #f0f7ff;
}

.tone-option input[type="radio"] {
    margin-top: 4px;
    margin-right: 16px;
    cursor: pointer;
}

.tone-option-content {
    flex: 1;
}

.tone-option-title {
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 4px;
    font-size: 15px;
}

.tone-option-description {
    color: #666;
    font-size: 14px;
    line-height: 1.4;
}

.aysa-button-container {
    display: flex;
    justify-content: flex-start;
    gap: 8px;
}

.aysa-button-primary {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: #0066ff;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s;
}

.aysa-button-primary:hover {
    background: #0052cc;
}

.aysa-button-primary:disabled {
    background: #ccc;
    cursor: not-allowed;
}

.aysa-button-primary .dashicons {
    font-size: 16px;
    width: 16px;
    height: 16px;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .aysa-wizard-section {
        margin: 16px;
    }
    
    .aysa-wizard-header,
    .aysa-form-container {
        padding: 20px;
    }
    
    .tone-option {
        padding: 12px;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    const setupNonce = '<?php echo wp_create_nonce('aysa_nonce'); ?>';

    // Get project ID from local sources
    function getProjectId() {
        let projectId = localStorage.getItem('aysa_project_id');
        if (projectId && Number(projectId) > 0) {
            return projectId;
        }
        const phpProjectId = '<?php echo intval(get_option('aysa_project_id', 0)); ?>';
        if (phpProjectId && Number(phpProjectId) > 0) {
            localStorage.setItem('aysa_project_id', phpProjectId);
            return phpProjectId;
        }
        return null;
    }

    const projectId = getProjectId();
    // Store project ID in a hidden input
    $('#aysa-tone-form').append('<input type="hidden" name="project_id" value="' + String(projectId || 0) + '">');

    function loadToneOptions() {
        const options = [
            { value: 'Professional', name: 'Professional', description: 'Clear, credible and business-oriented communication.' },
            { value: 'Friendly', name: 'Friendly', description: 'Warm and approachable communication style.' },
            { value: 'Casual', name: 'Casual', description: 'Relaxed, conversational and easy-to-read content.' },
            { value: 'Persuasive', name: 'Persuasive', description: 'Conversion-focused language to encourage action.' },
            { value: 'Inspirational', name: 'Inspirational', description: 'Positive and motivating tone for your audience.' }
        ];
        const $container = $('.aysa-tone-options');
        $container.empty();

        options.forEach(function(option) {
            const id = 'tone-' + option.value.toLowerCase();
            const $option = $(`
                <label class="tone-option" for="${id}">
                    <input type="radio" name="tone" value="${option.value}" id="${id}">
                    <div class="tone-option-content">
                        <div class="tone-option-title">${option.name}</div>
                        <div class="tone-option-description">${option.description}</div>
                    </div>
                </label>
            `);
            $container.append($option);
        });

        // default + local restore
        const storedTone = localStorage.getItem('aysa_tone') || 'Professional';
        const radioId = '#tone-' + storedTone.toLowerCase();
        $(radioId).prop('checked', true);
        $(radioId).closest('.tone-option').addClass('selected');
        // Ensure tone is persisted even if user does not interact with the field.
        autoSaveTone();
    }

    // Handle tone option selection
    $(document).on('change', 'input[name="tone"]', function() {
        $('.tone-option').removeClass('selected');
        $(this).closest('.tone-option').addClass('selected');
        
        // Auto-save when selection changes
        autoSaveTone();
    });

    // Function to show save status
    function showSaveStatus(message, isSuccess = true) {
        // Remove any existing status messages
        $('.tone-save-status').remove();
        
        const $status = $(`
            <div class="tone-save-status ${isSuccess ? 'success' : 'error'}" style="
                background: ${isSuccess ? '#d4edda' : '#f8d7da'};
                color: ${isSuccess ? '#155724' : '#721c24'};
                border: 1px solid ${isSuccess ? '#c3e6cb' : '#f5c6cb'};
                padding: 8px 12px;
                border-radius: 4px;
                margin-top: 16px;
                font-size: 14px;
                display: flex;
                align-items: center;
                gap: 8px;
            ">
                <span class="dashicons dashicons-${isSuccess ? 'yes-alt' : 'warning'}"></span>
                ${message}
            </div>
        `);
        
        $('.aysa-tone-options').after($status);
        
        // Auto-hide after 3 seconds
        setTimeout(() => {
            $status.fadeOut(300, function() {
                $(this).remove();
            });
        }, 3000);
    }

    // Auto-save function
    function autoSaveTone() {
        const selectedTone = $('input[name="tone"]:checked').val();
        
        if (!selectedTone) {
            return;
        }

        showSaveStatus('Saving tone of voice...', true);
        localStorage.setItem('aysa_tone', selectedTone);
        const formData = $('#aysa-tone-form').serialize();
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: formData + '&action=aysa_save_wizard_data&step=tone-of-voice&nonce=' + encodeURIComponent(setupNonce),
            success: function(response) {
                if (response && response.success) {
                    showSaveStatus('Tone of voice saved successfully!', true);
                } else {
                    showSaveStatus('Failed to save tone of voice. Please try again.', false);
                }
            },
            error: function() {
                showSaveStatus('Failed to save tone of voice. Please try again.', false);
            }
        });
    }

    // Handle save button click (legacy code - button is commented out but keeping for compatibility)
    $('#save-tone').on('click', function() {
        autoSaveTone();
    });

    // Load tone options when page loads
    loadToneOptions();
});
</script>
