/**
 * 3CX Call Modal JavaScript Module
 * Single source of truth for 3CX call functionality
 * Used by both Admin Integrations and Task Detail pages
 * 
 * NOTE: Modal template is now handled ONLY by Blade template (call-modal.blade.php)
 * This JavaScript handles state management and API calls only
 */

window.ThreeCXCallModal = (function () {
    'use strict';

    let modal = null;
    let statusPollingInterval = null;
    let isRequestInProgress = false;
    let currentCall = null;
    let debugLogs = [];
    let callStartTime = null;
    let timerInterval = null;
    let currentCallState = 'ended'; // Track current state

    // Debug logging
    function addDebugLog(message, type = 'info') {
        const timestamp = new Date().toLocaleTimeString();
        debugLogs.push({
            time: timestamp,
            message: message,
            type: type
        });

        // Keep only last 50 logs
        if (debugLogs.length > 50) {
            debugLogs = debugLogs.slice(-50);
        }

        console.log('[3CX Debug ' + timestamp + '] ' + message);
        updateDebugConsole();
    }

    function updateDebugConsole() {
        const debugContainer = $('#debug-logs-container');
        if (debugContainer.length) {
            let html = '';
            debugLogs.forEach(log => {
                const colorClass = log.type === 'success' ? 'color: #28a745;' :
                    log.type === 'error' ? 'color: #dc3545;' :
                        'color: #17a2b8;';
                html += '<div style="margin: 2px 0;">' +
                    '<span style="color: #666;">' + log.time + '</span>' +
                    '<span style="' + colorClass + '">' + log.message + '</span>' +
                    '</div>';
            });
            debugContainer.html(html);
        }
    }

    // Timer functions
    function startCallTimer() {
        if (timerInterval) {
            clearInterval(timerInterval);
        }

        callStartTime = new Date();
        timerInterval = setInterval(updateTimer, 1000);
    }

    function updateTimer() {
        if (!callStartTime) return;

        const now = new Date();
        const diff = Math.floor((now - callStartTime) / 1000);
        const minutes = Math.floor(diff / 60);
        const seconds = diff % 60;
        const timeString = (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds;

        $('#timer-display').text(timeString);

        // Update Angular scope if available
        if (window.currentAngularScope) {
            window.currentAngularScope.callDuration = timeString;
            window.currentAngularScope.$apply();
        }
    }

    function stopCallTimer() {
        if (timerInterval) {
            clearInterval(timerInterval);
            timerInterval = null;
        }

        if (callStartTime) {
            const now = new Date();
            const diff = Math.floor((now - callStartTime) / 1000);
            const minutes = Math.floor(diff / 60);
            const seconds = diff % 60;
            const finalDuration = (minutes < 10 ? '0' : '') + minutes + ':' + (seconds < 10 ? '0' : '') + seconds;

            $('#final-duration').text('Duration: ' + finalDuration);

            // Update Angular scope if available
            if (window.currentAngularScope) {
                window.currentAngularScope.finalDuration = 'Duration: ' + finalDuration;
                window.currentAngularScope.$apply();
            }

            callStartTime = null;
        }
    }

    // Get current call state
    function getCurrentCallState() {
        return currentCallState;
    }

    // Get current call data
    function getCurrentCall() {
        return currentCall;
    }

    // Update current call data
    function updateCurrentCall(data) {
        if (currentCall) {
            currentCall = { ...currentCall, ...data };
        }
    }

    // Modal state management
    function showCallState(state, data = {}) {
        addDebugLog('State change: ' + currentCallState + ' → ' + state, 'info');

        // Check if we're transitioning TO connected state
        const isTransitioningToConnected = (state === 'connected' && currentCallState !== 'connected');

        // Update current state tracking
        currentCallState = state;

        // Hide all states by removing active class
        $('.call-state').removeClass('active');

        // Show specific state by adding active class
        switch (state) {
            case 'init':
                $('#call-state-init').addClass('active');
                break;
            case 'dialing':
                $('#call-state-dialing').addClass('active');
                break;
            case 'ringing':
                $('#call-state-ringing').addClass('active');
                break;
            case 'connected':
                $('#call-state-connected').addClass('active');
                // Only start timer if we're transitioning TO connected (not already connected)
                if (isTransitioningToConnected) {
                    startCallTimer();
                    addDebugLog('🕒 Timer started - transitioning to connected state', 'success');
                } else {
                    addDebugLog('⏱️ Already connected - keeping existing timer', 'info');
                }
                break;
            case 'ended':
                $('#call-state-ended').addClass('active');
                stopCallTimer();
                stopPolling();

                // Update ended message based on reason
                if (data.endReason === 'extension_rejected' || data.endReason === 'reception_rejected') {
                    $('#ended-status').text('Call Rejected');
                    const extensionNumber = data.extensionNumber || '324';
                    $('#final-duration').text('Rejected by Extension ' + extensionNumber);
                    $('#ended-icon')
                        .removeClass('fa-check-square ended fa-times-circle')
                        .addClass('fa-stop-circle')
                        .css('color', '#dc3545');
                } else if (data.endReason === 'customer_rejected') {
                    $('#ended-status').text('Customer Declined');
                    $('#final-duration').text('Customer did not answer or declined');
                    $('#ended-icon')
                        .removeClass('fa-check-square ended fa-stop-circle')
                        .addClass('fa-times-circle')
                        .css('color', '#ffc107');
                } else if (data.endReason === 'call_completed') {
                    $('#ended-status').text('Call Completed');
                    $('#final-duration').text('Call completed successfully');
                    $('#ended-icon')
                        .removeClass('fa-stop-circle fa-times-circle')
                        .addClass('fa-check-square ended')
                        .css('color', '#28a745');
                } else {
                    $('#ended-status').text('Call Ended');
                    $('#final-duration').text('Call completed');
                    $('#ended-icon')
                        .removeClass('fa-times-circle fa-stop-circle')
                        .addClass('fa-check-square ended')
                        .css('color', '#28a745');
                }

                // Don't auto-close, let user close manually
                break;
            case 'error':
                $('#call-state-error').addClass('active');
                stopCallTimer();
                stopPolling();

                // Update error message for both Angular and jQuery
                if (data.message) {
                    $('.error-message-display').text(data.message);
                    $('.modern-error').text(data.message);
                }
                if (data.suggestion) {
                    $('.error-suggestion-text').text(data.suggestion);
                    $('.error-suggestion-display').show();
                    $('.modern-suggestion').text(data.suggestion);
                } else {
                    $('.error-suggestion-display').hide();
                }
                break;
        }

        // Update Angular scope if available
        // State is managed via jQuery show/hide - no Angular scope needed
    }

    // Angular scope functions removed - modal now uses pure JavaScript/jQuery

    // Static call display - no real-time polling
    function showStaticCallProgress(participantId, extension) {
        addDebugLog('Showing static call progress for participant ' + participantId, 'info');

        // Show static "Call in progress" state
        showCallState('dialing');

        // Update display with static message including extension info
        $('.modern-status').text('Call In Progress');

        // Use provided extension or fallback to currentCall or default
        const extensionInfo = extension || currentCall?.extension || '324';
        $('.static-message').text('Extension ' + extensionInfo + ' is calling the customer.');
        $('.static-subtitle').text('Close this dialog when your call is complete.');

        addDebugLog('Static call progress display shown for extension ' + extensionInfo, 'info');
    }

    // Dummy startPolling function for backward compatibility (now using static display)
    function startPolling(participantId) {
        addDebugLog('startPolling called but using static display instead', 'info');
        // Do nothing - we now use static display instead of polling
    }

    function stopPolling() {
        if (statusPollingInterval) {
            clearTimeout(statusPollingInterval);
            statusPollingInterval = null;
            isRequestInProgress = false;
            addDebugLog('Polling stopped', 'info');
        }
    }

    // Fetch final call status when modal closes
    function fetchFinalCallStatus(participantId) {
        if (!participantId) {
            addDebugLog('No participant ID available for final status fetch', 'error');
            return;
        }

        addDebugLog('Fetching final call status for participant ' + participantId, 'info');

        // Use correct status URL based on context (admin vs task)
        const isTaskPage = document.querySelector('meta[name="task-id"]') !== null;
        const hasTaskId = currentCall && currentCall.taskId;

        const statusUrl = (isTaskPage || hasTaskId) ?
            '/api/v1/threecx/call/status/' + participantId :  // Task context - use ThreeCXController
            '/admin/integrations/threecx/call-status/' + participantId;  // Admin context - use IntegrationsController

        $.ajax({
            url: statusUrl,
            method: 'GET',
            success: function (response) {
                addDebugLog('Final call status fetched successfully', 'success');

                if (response.success && response.data) {
                    const status = response.data.status.toLowerCase();
                    const eventData = response.data.event_data || {};
                    const reason = eventData.reason || '';

                    addDebugLog(`Final call status: ${status} (reason: ${reason})`, 'info');

                    // Update database with final status by making a sync call
                    syncCallStatusToDatabase({
                        participantId: participantId,
                        callId: response.data.call_id,
                        status: status,
                        reason: reason,
                        eventData: eventData
                    });
                } else {
                    addDebugLog('Final call status: Call ended or not found', 'info');
                }
            },
            error: function (xhr) {
                const errorMessage = xhr.responseJSON?.message || xhr.statusText || 'Unknown error';
                addDebugLog('Failed to fetch final call status: ' + xhr.status + ' - ' + errorMessage, 'error');
            }
        });
    }

    // Sync call status back to database
    function syncCallStatusToDatabase(callData) {
        if (!callData.participantId) {
            addDebugLog('Cannot sync call status - no participant ID', 'error');
            return;
        }

        addDebugLog('Syncing call status to database: ' + callData.status, 'info');

        // Use correct sync URL based on context (admin vs task)
        const isTaskPage = document.querySelector('meta[name="task-id"]') !== null;
        const hasTaskId = currentCall && currentCall.taskId;

        const syncUrl = (isTaskPage || hasTaskId) ?
            '/api/v1/threecx/call/sync-status' :  // Task context - use ThreeCXController
            '/admin/integrations/threecx/sync-call-status';  // Admin context - use IntegrationsController

        $.ajax({
            url: syncUrl,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: JSON.stringify({
                participant_id: callData.participantId,
                call_id: callData.callId,
                final_status: callData.status,
                end_reason: callData.reason,
                event_data: callData.eventData,
                task_id: currentCall?.taskId || null
            }),
            success: function (response) {
                addDebugLog('Call status synced to database successfully', 'success');

                // Call history refresh handled by modal close event
            },
            error: function (xhr) {
                const errorMessage = xhr.responseJSON?.message || xhr.statusText || 'Unknown error';
                addDebugLog('Failed to sync call status to database: ' + xhr.status + ' - ' + errorMessage, 'error');
            }
        });
    }

    // No hangup logic in simplified flow

    // Modal creation and management
    function createModal(toNumber, extension = '650') {
        addDebugLog('Creating modal for ' + toNumber + ' via ' + extension, 'info');

        // Clean up any existing modals
        cleanupModal();

        // Create modal from template
        const modalId = 'threecx-call-modal-' + Date.now();

        const modalHtml = `
        <div class="modal fade" id="${modalId}" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-md">
                <div class="modal-content">
                    ${getModalTemplate()}
                </div>
            </div>
        </div>`;

        $('body').append(modalHtml);
        modal = $('#' + modalId);

        // Set up phone number display for jQuery elements
        $('.modern-number').text(toNumber);
        $('.call-number-display').text(toNumber);

        // Modal is now pure JavaScript/jQuery - no Angular scope needed
        // Phone number and extension are handled via jQuery selectors

        // Set up modal events - simplified (no status fetch)
        modal.on('hidden.bs.modal', function () {
            // Simplified flow - just refresh call history to show basic record
            if (window.refreshCallHistory && currentCall?.taskId) {
                addDebugLog('Triggering call history refresh', 'info');
                setTimeout(function () {
                    window.refreshCallHistory();
                }, 200);
            }

            stopPolling();
            stopCallTimer();
            cleanupModal();

            // Re-enable any test buttons
            $('.test-call-btn').prop('disabled', false).removeClass('processing');
            $('#test_to_number').prop('disabled', false);
        });

        // Show modal with proper close handlers
        modal.modal({
            backdrop: true,  // Allow closing by clicking outside
            keyboard: true,  // Allow closing with ESC key
            show: true
        });

        // Add close button handlers - simplified (no status fetch)
        modal.find('.close, [data-dismiss="modal"]').on('click', function () {
            // Call history refresh handled by modal hidden event
            stopPolling();
            stopCallTimer();
            cleanupModal();
        });

        // Set initial state immediately
        showCallState('init');
        addDebugLog('Modal created and initial state set', 'info');

        return modalId;
    }

    function getModalTemplate() {
        return `
        <div class="modal-header">
            <button type="button" class="close" onclick="window.ThreeCXCallModal.closeModal()">×</button>
            <h4 class="modal-title modern-title">3CX Call</h4>
        </div>
        <div class="modal-body">
            <!-- Initiating Call State -->
            <div id="call-state-init" class="call-state modern-state">
                <div class="modern-icon-container">
                    <i class="fa fa-phone-square fa-4x modern-icon connecting pulse"></i>
                </div>
                <h2 class="modern-status">Initiating Call</h2>
                <p class="modern-number call-number-display"></p>
                <span class="modern-extension">Setting up connection...</span>
            </div>
            
            <!-- Call In Progress State (Static) -->
            <div id="call-state-dialing" class="call-state modern-state">
                <div class="modern-icon-container">
                    <i class="fa fa-phone-square fa-4x modern-icon connecting ring-animation"></i>
                </div>
                <h2 class="modern-status">Call In Progress</h2>
                <p class="modern-number call-number-display"></p>
                <div class="call-status-message">
                    <p class="static-message">Your call is being processed by the phone system.</p>
                    <p class="static-subtitle">Please wait while we connect you...</p>
                </div>
            </div>
            
            <!-- Call In Progress State (Alternative) -->
            <div id="call-state-ringing" class="call-state modern-state">
                <div class="modern-icon-container">
                    <i class="fa fa-phone-square fa-4x modern-icon connecting ring-animation"></i>
                </div>
                <h2 class="modern-status">Call In Progress</h2>
                <p class="modern-number call-number-display"></p>
                <div class="call-status-message">
                    <p class="static-message">Your call is being processed by the phone system.</p>
                    <p class="static-subtitle">Please wait while we connect you...</p>
                </div>
            </div>
            
            <!-- Connected State -->
            <div id="call-state-connected" class="call-state modern-state">
                <div class="modern-icon-container">
                    <i class="fa fa-phone-square fa-4x modern-icon connected connected-glow"></i>
                </div>
                <h2 class="modern-status">Connected</h2>
                <p class="modern-number call-number-display"></p>
                <div class="modern-timer">
                    <span id="timer-display">00:00</span>
                </div>                
                <div class="alert alert-success" style="margin-top: 20px;">
                    <strong>Connected.</strong> The phone system manages the call lifecycle.
                </div>
            </div>
            
            <!-- Ended State -->
            <div id="call-state-ended" class="call-state modern-state">
                <div class="modern-icon-container">
                    <i class="fa fa-check-square fa-4x modern-icon ended" id="ended-icon"></i>
                </div>
                <h2 class="modern-status" id="ended-status">Call Ended</h2>
                <p class="modern-number call-number-display"></p>
                <div class="modern-duration">
                    <span id="final-duration">Call completed</span>
                </div>                
            </div>

            <!-- Error State -->
            <div id="call-state-error" class="call-state modern-state">
                <div class="modern-icon-container">
                    <i class="fa fa-exclamation-triangle fa-4x modern-icon error"></i>
                </div>
                <h2 class="modern-status">Call Failed</h2>
                <p class="modern-error error-message-display"></p>                
            </div>
            
        </div>
        
        <!-- Include CSS -->
        <style>
        /* Modern Call Modal CSS - FROM 3CX MODULE */
        .modern-call-modal {
            border: none;
            border-radius: 0;
            box-shadow: 0 8px 32px rgba(0,0,0,0.12);
        }
        
        .modern-header {
            background: #fff;
            border-bottom: 1px solid #e9ecef;
            border-radius: 0;
            padding: 20px 24px;
        }
        
        .modern-title {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
            margin: 0;
        }
        
        .modern-close {
            font-size: 24px;
            font-weight: 300;
            color: #6c757d;
            opacity: 1;
        }
        
        .modern-body {
            padding: 24px;
            background: #f8f9fa;
        }
        
        /* HIGH SPECIFICITY - Force override Bootstrap modal styles */
        .modal-content .modal-body .modern-state {
            text-align: center !important;
            padding: 48px 32px !important;
            background: white !important;
            min-height: 420px !important;
            display: none !important; /* Hidden by default */
            flex-direction: column !important;
            justify-content: center !important;
            align-items: center !important;
            border-radius: 8px;
            margin-bottom: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        }

        /* Show only the active state */
        .modal-content .modal-body .modern-state.active {
            display: flex !important;
        }
        
        .modern-icon-container {
            margin-bottom: 24px !important;
            padding: 16px !important;
        }
        
        .modern-icon {
            color: #6c757d;
            transition: all 0.3s ease;
        }
        
        .modern-icon.connecting { color: #6c757d; }
        .modern-icon.dialing { color: #ffc107; }
        .modern-icon.ringing { color: #17a2b8; }
        .modern-icon.connected { color: #28a745; }
        .modern-icon.ended { color: #28a745; }
        .modern-icon.error { color: #dc3545; }
        
        .modal-content .modal-body .modern-status {
            font-size: 28px !important;
            font-weight: 600 !important;
            color: #2c3e50 !important;
            margin: 0 0 16px 0 !important;
            text-transform: capitalize !important;
        }
        
        .modal-content .modal-body .modern-number {
            font-size: 28px !important;
            font-weight: 500 !important;
            color: #2c3e50 !important;
            margin: 12px 0 20px 0 !important;
            font-family: 'Segoe UI', sans-serif !important;
            letter-spacing: 1px !important;
        }
        
        .modern-extension,
        .modern-subtitle {
            font-size: 14px;
            color: #6c757d;
            display: block;
            margin-top: 12px;
        }
        
        .call-status-message {
            text-align: center;
            margin: 20px 0;
        }
        
        .static-message {
            font-size: 16px;
            color: #2c3e50;
            margin: 8px 0;
            font-weight: 500;
        }
        
        .static-subtitle {
            font-size: 14px;
            color: #6c757d;
            margin: 4px 0;
        }
        
        .modern-progress {
            width: 100%;
            height: 4px;
            background: #e9ecef;
            border-radius: 2px;
            overflow: hidden;
            margin: 16px 0;
        }
        
        .modern-progress-bar {
            height: 100%;
            transition: width 0.3s ease;
            border-radius: 2px;
        }
        
        .modern-progress-bar.dialing {
            width: 60%;
            background: linear-gradient(90deg, #ffc107, #ffca2c);
            animation: progress-pulse 2s infinite;
        }
        
        .modern-progress-bar.ringing {
            width: 85%;
            background: linear-gradient(90deg, #17a2b8, #20c0db);
            animation: progress-pulse 1.5s infinite;
        }
        
        .modal-content .modal-body .modern-timer {
            font-size: 40px !important;
            font-weight: 400 !important;
            color: #28a745 !important;
            margin: 16px 0 20px 0 !important;
            font-family: 'Segoe UI', 'Roboto', monospace !important;
            background: rgba(40,167,69,0.1) !important;
            padding: 12px 24px !important;
            border-radius: 12px !important;
            display: inline-block !important;
            letter-spacing: 2px !important;
            box-shadow: 0 2px 8px rgba(40,167,69,0.1) !important;
        }
        
        .modal-content .modal-body .modern-duration {
            font-size: 18px !important;
            font-weight: 600 !important;
            color: #2c3e50 !important;
            margin: 16px 0 20px 0 !important;
            font-family: 'Segoe UI', sans-serif !important;
            letter-spacing: 0.5px !important;
        }
        
        /* Special styling for rejection message */
        .modal-content .modal-body #final-duration {
            font-size: 18px !important;
            font-weight: 600 !important;
            line-height: 1.4 !important;
        }
        
        @keyframes progress-pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        @keyframes ring-animation {
            0% { 
                transform: rotate(-15deg) scale(1); 
                box-shadow: 0 0 0 0 rgba(23, 162, 184, 0.5);
            }
            25% { 
                transform: rotate(15deg) scale(1.02); 
                box-shadow: 0 0 0 5px rgba(23, 162, 184, 0.3);
            }
            50% { 
                transform: rotate(-10deg) scale(1); 
                box-shadow: 0 0 0 10px rgba(23, 162, 184, 0.1);
            }
            75% { 
                transform: rotate(10deg) scale(1.02); 
                box-shadow: 0 0 0 5px rgba(23, 162, 184, 0.3);
            }
            100% { 
                transform: rotate(-15deg) scale(1); 
                box-shadow: 0 0 0 0 rgba(23, 162, 184, 0.5);
            }
        }
        
        @keyframes connected-glow {
            0% { 
                box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7);
            }
            50% { 
                box-shadow: 0 0 20px 5px rgba(40, 167, 69, 0.5);
            }
            100% { 
                box-shadow: 0 0 0 0 rgba(40, 167, 69, 0.7);
            }
        }
        
        /* Apply animations to icons only */
        .modern-icon.pulse {
            animation: pulse 2s infinite;
        }
        
        .modern-icon.ring-animation {
            animation: ring-animation 0.8s infinite;
        }
        
        .modern-icon.connected-glow {
            animation: connected-glow 2s infinite;
        }
        
        </style>`;
    }

    function cleanupModal() {
        if (modal) {
            modal.modal('hide');
            modal.remove();
            modal = null;
        }

        // Clean up any lingering modals
        $('.modal').filter('[id*="threecx-call-modal"]').remove();
        $('.modal-backdrop').remove();
        $('body').removeClass('modal-open').removeAttr('style');

        window.currentAngularScope = null;
    }

    function closeModal() {
        // Call history refresh handled by modal hidden event
        stopPolling();
        stopCallTimer();
        cleanupModal();
    }

    // No hangup function in simplified flow

    // Main API function to start a call
    function makeCall(toNumber, options = {}) {
        const extension = options.extension || '650';
        const apiUrl = options.apiUrl || '/api/v1/threecx/call/start'; // Use proper ThreeCX endpoint
        const timeout = options.timeout || 30;

        addDebugLog('Starting call to ' + toNumber + ' via ' + extension, 'info');
        addDebugLog('Using API endpoint: ' + apiUrl, 'info');
        addDebugLog('Task ID: ' + (options.taskId || 'null'), 'info');

        // Create and show modal
        createModal(toNumber, extension);

        // Set initial state immediately after modal is created
        setTimeout(() => {
            showCallState('init');
            addDebugLog('Initial state set to: init', 'info');
        }, 100);

        // Disable any test buttons
        $('.test-call-btn').prop('disabled', true).addClass('processing');
        $('#test_to_number').prop('disabled', true);

        // Start the API call with CSRF retry logic (like clocking system)
        makeCallWithRetry(apiUrl, {
            phone_number: toNumber,
            extension: extension,
            timeout: timeout,
            task_id: options.taskId || null, // Include task ID for server-side logging
            static_display: true // Tell backend to skip WebSocket tracking for static display
        }, 0);
    }

    // CSRF retry function (similar to clocking system)
    function makeCallWithRetry(apiUrl, requestData, retryCount) {
        // Get CSRF token from meta tag
        let csrfToken = $('meta[name="csrf-token"]').attr('content');
        addDebugLog('CSRF token found: ' + (csrfToken ? 'Yes' : 'No'), 'info');

        $.ajax({
            url: apiUrl,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': csrfToken
            },
            data: JSON.stringify(requestData),
            success: function (response) {
                addDebugLog('API call successful', 'success');
                addDebugLog('Response data: ' + JSON.stringify(response), 'info');

                if (response.success) {
                    if (response.participant_id) {
                        addDebugLog('Participant ID received: ' + response.participant_id, 'success');
                        
                        // Check if call tracking started successfully (skip check for static display)
                        const isStaticDisplay = true; // We're always using static display now
                        if (response.tracking_started === false && !isStaticDisplay) {
                            showCallState('error', {
                                message: 'Call initiated but tracking failed to start. Please check system permissions.',
                                suggestion: 'Contact administrator to fix cache permissions'
                            });
                            addDebugLog('Call tracking failed to start - cache permission issue', 'error');
                            return;
                        }

                        currentCall = {
                            participantId: response.participant_id,
                            callId: response.call_id,
                            status: response.call_status,
                            extension: response.extension,
                            phoneNumber: requestData.phone_number,
                            taskId: requestData.task_id || null  // Store task context for automatic logging
                        };

                        // Store globally for integration with admin status polling
                        window.currentCall = currentCall;

                        addDebugLog('Current call stored: ' + JSON.stringify(currentCall), 'info');
                        
                        // Show static call progress instead of real-time polling
                        addDebugLog('About to call showStaticCallProgress with participant: ' + response.participant_id + ', extension: ' + response.extension, 'info');
                        showStaticCallProgress(response.participant_id, response.extension);
                    } else {
                        addDebugLog('No participant_id in response', 'error');
                        
                        // More helpful error message when participant_id is missing
                        let errorMessage = response.message || 'Call could not be initiated';
                        let suggestion = 'The 3CX phone system may be unavailable or your extension may not be configured properly. Please contact your administrator.';
                        
                        // Check if there's a specific reason in the response
                        if (response.message && response.message.includes('extension')) {
                            errorMessage = 'Extension configuration issue';
                            suggestion = 'Your extension may not be properly configured in the 3CX system. Please contact your administrator to verify your extension settings.';
                        } else if (response.message && response.message.includes('connect')) {
                            errorMessage = '3CX system connection failed';
                            suggestion = 'Could not connect to the 3CX phone system. Please try again or contact your administrator if the issue persists.';
                        }
                        
                        showCallState('error', {
                            message: errorMessage,
                            suggestion: suggestion
                        });
                    }
                } else {
                    addDebugLog('Response success = false: ' + response.message, 'error');
                    showCallState('error', {
                        message: response.message || 'Failed to initiate call',
                        suggestion: response.suggestion
                    });
                }
            },
            error: function (xhr) {
                addDebugLog('API call failed: ' + xhr.status + ' (retry count: ' + retryCount + ')', 'error');

                // Handle 419 CSRF errors with automatic retry using fresh token
                if (xhr.status === 419 && retryCount < 2) {
                    addDebugLog('419 error detected, attempting to get fresh token...', 'info');

                    // Make a simple GET request to refresh session and get new token
                    fetch(window.location.pathname, {
                        method: 'GET',
                        headers: { 'Accept': 'text/html' },
                        credentials: 'same-origin'
                    })
                    .then(response => response.text())
                    .then(html => {
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(html, 'text/html');
                        const newToken = doc.querySelector('meta[name="csrf-token"]')?.getAttribute('content');

                        if (newToken && newToken !== csrfToken) {
                            // Update the token in current page
                            const currentTokenEl = document.querySelector('meta[name="csrf-token"]');
                            if (currentTokenEl) {
                                currentTokenEl.setAttribute('content', newToken);
                            }
                            addDebugLog('Fresh token obtained: ' + newToken.substring(0, 10) + '...', 'success');
                            addDebugLog('Retrying API call with fresh token...', 'info');

                            // Retry with fresh token
                            setTimeout(() => {
                                makeCallWithRetry(apiUrl, requestData, retryCount + 1);
                            }, 500);
                        } else {
                            addDebugLog('Token refresh failed - same token returned', 'error');
                            showCallState('error', { 
                                message: 'Session expired - please refresh the page and try again',
                                suggestion: 'Your network connection may have changed (common with VPN/Cloudflare users)'
                            });
                        }
                    })
                    .catch(error => {
                        addDebugLog('Token refresh request failed: ' + error, 'error');
                        showCallState('error', { 
                            message: 'Session expired - please refresh the page and try again',
                            suggestion: 'Your network connection may have changed (common with VPN/Cloudflare users)'
                        });
                    });

                    return; // Don't show error state yet, we're retrying
                }

                let message = 'Failed to start call';
                let suggestion = null;

                if (xhr.responseJSON) {
                    message = xhr.responseJSON.message || message;
                    suggestion = xhr.responseJSON.suggestion;
                } else if (xhr.status === 419) {
                    message = 'Session expired - please refresh the page and try again';
                    suggestion = 'Your network connection may have changed (common with VPN/Cloudflare users)';
                }

                addDebugLog('Showing error state: ' + message, 'error');
                showCallState('error', { message, suggestion });
            }
        });
    }

    // Public API
    return {
        makeCall: makeCall,
        showCallState: showCallState,
        getCurrentCallState: getCurrentCallState,
        getCurrentCall: getCurrentCall,
        updateCurrentCall: updateCurrentCall,
        addDebugLog: addDebugLog,
        // hangupCall removed in simplified flow
        closeModal: closeModal,
        startPolling: startPolling,
        stopPolling: stopPolling,
        fetchFinalCallStatus: fetchFinalCallStatus,

        // Legacy compatibility methods (simplified for Blade template usage)
        show: function (toNumber, extension) {
            // Update modal content and trigger makeCall API
            $('.modern-number').text(toNumber);
            // Phone number is set via jQuery - no Angular scope needed
            showCallState('init');
        },

        showConnected: function (message) {
            showCallState('connected');
        },

        showError: function (message, suggestion) {
            showCallState('error', { message, suggestion });
        },

        hide: function () {
            closeModal();
        },

        updateStatus: function (status, message) {
            showCallState(status, { message });
        }
    };
})();

// Export for CommonJS if available
if (typeof module !== 'undefined' && module.exports) {
    module.exports = window.ThreeCXCallModal;
}

// Angular controller registration removed - modal now uses pure JavaScript/jQuery
// No Angular scope or controller dependencies needed
