/**
 * Admin Orders JavaScript
 * 
 * @package LivraisonAPI
 */

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

    // Track button
    $('.livraison-track-btn').on('click', function() {
        var courseId = $(this).data('course');
        var modal = $('#livraison-track-modal');
        var content = $('#livraison-track-content');
        
        if (!courseId) {
            return;
        }
        
        modal.show();
        content.html('<div class="livraison-loading">' + livraisonAdmin.l10n.loading + '</div>');
        
        $.ajax({
            url: livraisonAdmin.ajaxUrl,
            type: 'POST',
            data: {
                action: 'livraison_track_order',
                course_id: courseId,
                nonce: livraisonAdmin.trackNonce
            },
            success: function(response) {
                if (response.success) {
                    var html = '<div class="livraison-track-status">';
                    if (response.data.steps) {
                        response.data.steps.forEach(function(step) {
                            var statusClass = step.completed ? 'completed' : (step.active ? 'active' : '');
                            var icon = step.completed ? '✓' : (step.active ? '●' : '○');
                            html += '<div class="livraison-track-step ' + statusClass + '">';
                            html += '<div class="step-icon">' + icon + '</div>';
                            html += '<div class="step-info">';
                            html += '<div class="step-label">' + step.label + '</div>';
                            if (step.date) {
                                html += '<div class="step-date">' + step.date + '</div>';
                            }
                            html += '</div>';
                            html += '</div>';
                        });
                    }
                    html += '</div>';
                    content.html(html);
                } else {
                    content.html('<p class="livraison-error">' + (response.data || livraisonAdmin.l10n.errorTracking) + '</p>');
                }
            },
            error: function() {
                content.html('<p class="livraison-error">' + livraisonAdmin.l10n.connectionError + '</p>');
            }
        });
    });
    
    // Close modal
    $('.livraison-modal-close, .livraison-modal-backdrop').on('click', function() {
        $('#livraison-track-modal').hide();
    });
    
    // Close on Escape
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            $('#livraison-track-modal').hide();
        }
    });
});