<?php $__env->startSection('title', 'Edit Prompt'); ?>
<?php $__env->startSection('content'); ?>
    <style>
        .accordion-item {
            border: 1px solid #dee2e6 !important;
            border-radius: 0.5rem !important;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
            margin-bottom: 0.75rem;
        }

        .accordion-button {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .func-title-label {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            display: inline-block;
            max-width: 200px;
            vertical-align: bottom;
        }

        .accordion-button:not(.collapsed) {
            background-color: #e9ecef;
            box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.1);
        }

        .accordion-body {
            background-color: #fff;
            border-top: 1px solid #dee2e6;
            border-radius: 0 0 0.5rem 0.5rem;
        }
    </style>

    <div class="container-fluid content">
        <div class="row g-3">
            <!-- Prompt Details Card - 8 cols -->
            <div class="col-12 col-lg-8">
                <div class="card card-shadow p-3 mb-4">
                    <h4 class="mb-3">Edit Prompt Details</h4>

                    <?php if($prompt): ?>
                        <form action="<?php echo e(route('prompts.update', $prompt->id)); ?>" method="POST">
                            <?php echo csrf_field(); ?>
                            <?php echo method_field('POST'); ?>

                            <div class="mb-3">
                                <label class="form-label">Title</label>
                                <input type="text" name="title" class="form-control"
                                    value="<?php echo e(old('title', $prompt->title)); ?>" required>
                            </div>

                            <!-- Voice Selection + Preview -->
                            <div class="mb-3">
                                <label class="form-label">Select Voice</label>
                                <div class="d-flex align-items-center gap-2">
                                    <select name="voice_name" id="voiceSelect" class="form-select w-auto">
                                        <option <?php if($prompt->voice_name == 'alloy'): echo 'selected'; endif; ?> value="alloy">Alloy (Male) - Warm &
                                            confident</option>
                                        <option <?php if($prompt->voice_name == 'ash'): echo 'selected'; endif; ?> value="ash">Ash (Male) - Calm & grounded
                                        </option>
                                        <option <?php if($prompt->voice_name == 'ballad'): echo 'selected'; endif; ?> value="ballad">Ballad (Male) -
                                            Expressive & emotional</option>
                                        <option <?php if($prompt->voice_name == 'coral'): echo 'selected'; endif; ?> value="coral">Coral (Female) - Bright &
                                            energetic</option>
                                        <option <?php if($prompt->voice_name == 'echo'): echo 'selected'; endif; ?> value="echo">Echo (Male) - Clear &
                                            neutral</option>
                                        <option <?php if($prompt->voice_name == 'sage'): echo 'selected'; endif; ?> value="sage">Sage (Female) - Gentle &
                                            wise</option>
                                        <option <?php if($prompt->voice_name == 'shimmer'): echo 'selected'; endif; ?> value="shimmer">Shimmer (Female) -
                                            Soft & friendly</option>
                                        <option <?php if($prompt->voice_name == 'verse'): echo 'selected'; endif; ?> value="verse">Verse (Male) - Balanced &
                                            intelligent</option>
                                    </select>
                                    <button type="button" class="btn btn-outline-primary" id="playVoiceBtn" disabled>▶
                                        Preview</button>
                                </div>
                                <small class="text-muted">Choose a voice to preview how your Initial Greeting
                                    sounds.</small>
                            </div>

                            <!-- Initial Greeting -->
                            <div class="mb-3">
                                <label class="form-label">Initial Greeting</label>
                                <textarea name="initial_greeting" id="initialGreeting" class="form-control" rows="3"><?php echo e(old('initial_greeting', $prompt->initial_greeting)); ?></textarea>
                            </div>

                            <!-- Lead Placeholders for Description -->
                            <div class="mb-3">
                                <label class="form-label">Lead Placeholders</label>
                                <div class="input-group mb-2">
                                    <span class="input-group-text"><i class="ti-user"></i></span>
                                    <select id="multiple_labels" class="form-select" autocomplete="off">
                                        <option value="">Select to Insert</option>
                                        <?php $__currentLoopData = $label_list; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $list): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="[[<?php echo e($list->title); ?>]]"><?php echo e($list->title); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                                <small class="text-muted">Click to insert placeholder in Description or SMS Message.</small>
                                <span id="setBoxValue" style="display:none;"></span>
                            </div>

                            <!-- Description -->
                            <div class="mb-3">
                                <label class="form-label">Description</label>
                                <textarea id="editor1" name="description" class="form-control" rows="12"><?php echo e(old('description', $prompt->description)); ?></textarea>
                            </div>

                            <div class="d-flex gap-2 mb-3">
                                <button type="submit" class="btn btn-success">Save Prompt</button>
                                <a href="<?php echo e(route('prompts.index')); ?>" class="btn btn-secondary">Back</a>
                                <button type="button" class="btn btn-primary ms-auto" id="openTestModalBtn">
                                    <i class="ti-headphone-alt"></i> Test Prompt
                                </button>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Functions Card - 4 cols -->
            <div class="col-12 col-lg-4">
                <div class="card card-shadow p-3">
                    <h4 class="mb-3">Functions</h4>
                    <p>Add or update functions for this prompt. Each function must have a type and a name.</p>

                    <?php if($prompt): ?>
                        <form action="<?php echo e(route('prompts.saveFunctions', $prompt->id)); ?>" method="POST">
                            <?php echo csrf_field(); ?>
                            <div class="border p-3 mb-3" id="functions-container"></div>
                            <button type="button" class="btn btn-primary mb-3" id="add-function-btn">Add Function</button>
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-success">Save Functions</button>
                                <a href="<?php echo e(route('prompts.index')); ?>" class="btn btn-secondary">Back</a>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <style>
        /* Chat UI Styles */
        #chatHistory {
            height: 400px;
            overflow-y: auto;
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 8px;
        }
        .chat-message {
            margin-bottom: 15px;
            display: flex;
            flex-direction: column;
        }
        .chat-bubble {
            max-width: 80%;
            padding: 10px 15px;
            border-radius: 15px;
            font-size: 14px;
            line-height: 1.4;
            position: relative;
        }
        .user-msg {
            align-items: flex-end;
        }
        .user-msg .chat-bubble {
            background-color: #0d6efd;
            color: white;
            border-bottom-right-radius: 2px;
        }
        .ai-msg {
            align-items: flex-start;
        }
        .ai-msg .chat-bubble {
            background-color: #e9ecef;
            color: #333;
            border-bottom-left-radius: 2px;
        }
        .chat-role {
            font-size: 11px;
            color: #888;
            margin-bottom: 4px;
            margin-left: 5px;
            margin-right: 5px;
        }
    </style>

    <!-- Voice Test Modal (Chat Mode) -->
    <div class="modal fade" id="voiceTestModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Voice Chat Test</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-4">
                    
                    <!-- Chat Scroll Area -->
                    <div id="chatHistory">
                        <div class="text-center text-muted mt-5 pt-5" id="chatPlaceholder">
                            <i class="ti-comments fs-1 mb-3"></i>
                            <p>Conversation will appear here...</p>
                        </div>
                    </div>

                <!-- Controls Area -->
                </div> <!-- End modal-body -->

                <div class="modal-footer bg-light border-top d-flex align-items-center justify-content-between">
                    <!-- Left: Reset -->
                    <div style="width: 80px;"> <!-- Fixed width wrapper for alignment -->
                        <button class="btn btn-outline-secondary btn-sm w-100" onclick="uiReset()" id="resetBtn">
                             <i class="fas fa-trash"></i> Reset
                        </button>
                    </div>
                    
                    <!-- Center: Visualizer & Status -->
                    <div class="text-center flex-grow-1 px-3">
                        <span id="statusIndicator" class="badge bg-secondary mb-2 d-block mx-auto" style="width: fit-content;">Ready</span>
                        <div id="visualizer" style="height: 6px; width: 100%; max-width: 200px; background: #e9ecef; margin: 0 auto; border-radius: 3px; overflow: hidden;">
                             <div id="visBar" style="height: 100%; width: 0%; background: #28a745; transition: width 0.1s ease-out;"></div>
                        </div>
                    </div>

                    <!-- Right: Call Actions -->
                    <div style="width: 80px;" class="text-end"> <!-- Fixed width wrapper for alignment -->
                        <!-- Start Call Button -->
                        <button id="startCallBtn" class="btn btn-success rounded-circle shadow" style="width: 54px; height: 54px;" onclick="startCallLoop()">
                            <i class="fas fa-phone fs-4"></i>
                        </button>

                        <!-- End Call Button (Hidden by default) -->
                        <button id="endCallBtn" class="btn btn-danger rounded-circle shadow d-none" style="width: 54px; height: 54px;" onclick="endCallLoop()">
                            <i class="fas fa-phone-slash fs-4"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        @keyframes pulse-ring {
            0% { transform: scale(1); opacity: 0.8; }
            100% { transform: scale(1.5); opacity: 0; }
        }
        .mic-listening {
            animation: pulse-ring 2s infinite;
            border-color: #dc3545 !important; 
        }
        .mic-active {
            background-color: #dc3545 !important;
        }
        .mic-speaking {
            box-shadow: 0 0 15px #0d6efd;
            background-color: #0d6efd !important;
        }
    </style>

    <!-- JS: Function Builder & Placeholder insert -->
    <script>
        let funcCount = 0;

        function slugify(text) {
            const result = text
                .toString()
                .toLowerCase()
                .replace(/\s+/g, '_') // convert spaces to underscores
                .replace(/[^a-z_]/g, '') // allow only lowercase letters and underscores
                .replace(/_+/g, '_'); // collapse multiple underscores
            return result;
        }

        function addFunction(existing = null) {
            funcCount++;
            const funcDiv = document.createElement('div');
            funcDiv.classList.add('function-block');
            const funcId = existing && existing.id ? existing.id : '';

            funcDiv.innerHTML = `
            <div class="accordion" id="accordionFunc${funcCount}">
            <div class="accordion-item border rounded">
                <h2 class="accordion-header mt-0" id="heading${funcCount}">
                <button class="accordion-button collapsed fw-bold" type="button" data-bs-toggle="collapse"
                    data-bs-target="#collapse${funcCount}" aria-expanded="false" aria-controls="collapse${funcCount}">
                    Function ${funcCount} — <span class="ms-1 func-title-label">${existing?.name || ''}</span>
                </button>
                </h2>
                <div id="collapse${funcCount}" class="accordion-collapse collapse" aria-labelledby="heading${funcCount}"
                data-bs-parent="#accordionFunc${funcCount}">
                <div class="accordion-body">
                    <input type="hidden" name="functions[${funcCount}][id]" value="${funcId}">
                    <div class="d-flex justify-content-end mb-2">
                    <button type="button" class="btn btn-danger btn-sm remove-func-btn">Remove</button>
                    </div>

                    <div class="mb-2">
                    <label class="form-label">Type</label>
                    <select name="functions[${funcCount}][type]" class="form-select func-type" required>
                        <option value="">Select Type</option>
                        <option value="sms">SMS</option>
                        <option value="call">Call Redirect</option>
                        <option value="email">Email</option>
                        <option value="curl">cURL Request</option>
                        <option value="api">API / Webhook</option>
                    </select>
                    </div>

                    <div class="mb-2">
                    <label class="form-label">Name</label>
                    <input type="text" name="functions[${funcCount}][name]" class="form-control func-name"
                        placeholder="function_name" required>
                    </div>

                    <!-- Function Description (shown only for existing functions) -->
                    <div class="mb-2 function-description-container" style="display:none;">
                    <label class="form-label">Function Description</label>
                    <textarea name="functions[${funcCount}][function_description]" class="form-control function-description" rows="3"
                        placeholder="Optional description for this function"></textarea>
                    <small class="text-muted">This description is editable and helps document the function's purpose.</small>
                    </div>

                    <div class="mb-2 func-sms" style="display:none;">
                    <label class="form-label">Select SMS Template</label>
                    <select name="functions[${funcCount}][message]" class="form-select sms-template-select" required>
                        <option value="">Select Template</option>
                        <?php $__currentLoopData = $template_list; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tpl): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($tpl->templete_id); ?>"><?php echo e($tpl->templete_name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    </div>

                    <div class="mb-2 func-call" style="display:none;">
                    <label class="form-label">Phone Number (Call Redirect)</label>
                    <input type="text" name="functions[${funcCount}][phone]" class="form-control"
                        placeholder="+1XXXXXXXXXX">
                    </div>

                    <div class="mb-2 func-email" style="display:none;">
                    <label class="form-label">Select Email Template</label>
                    <select name="functions[${funcCount}][message]" class="form-select email-template-select" required>
                        <option value="">Select Template</option>
                        <?php $__currentLoopData = $email_templates; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $tpl): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($tpl->id); ?>"><?php echo e($tpl->template_name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                    </div>

                    <div class="mb-2 func-curl" style="display:none;">
                    <!-- Lead Placeholders for cURL -->
                    <label class="form-label mt-3">Lead Placeholders</label>
                    <div class="input-group mb-2">
                        <span class="input-group-text"><i class="ti-user"></i></span>
                        <select class="form-select curl-placeholder-select" autocomplete="off">
                            <option value="">Select to Insert</option>
                            <?php $__currentLoopData = $label_list; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $list): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="[[<?php echo e($list->title); ?>]]"><?php echo e($list->title); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                    <small class="text-muted">Click to insert placeholder in cURL Request body.</small>
                    
                    <label class="form-label mt-3">cURL Request</label>
                    <textarea name="functions[${funcCount}][curl_request]" class="form-control curl-request-textarea" rows="15"
                        placeholder="Paste full cURL request"></textarea>
                    <label class="form-label mt-2">Expected Response</label>
                    <textarea name="functions[${funcCount}][curl_response]" class="form-control" rows="15"
                        placeholder="Paste example response"></textarea>
                    </div>

                    <div class="mb-2 func-api" style="display:none;">
                    <label class="form-label">HTTP Method</label>
                    <select name="functions[${funcCount}][api_method]" class="form-select api-method" required>
                        <option value="GET">GET</option>
                        <option value="POST">POST</option>
                        <option value="PUT">PUT</option>
                        <option value="PATCH">PATCH</option>
                        <option value="DELETE">DELETE</option>
                    </select>

                    <label class="form-label mt-2">API URL</label>
                    <input type="url" name="functions[${funcCount}][api_url]" class="form-control api-url"
                        placeholder="https://api.example.com/data" required>

                    <div class="api-body-section">
                        <label class="form-label mt-2">Request Body (JSON)</label>
                        <textarea name="functions[${funcCount}][api_body]" class="form-control api-body" rows="15"
                        placeholder='{"key": "value"}'></textarea>
                    </div>

                    <label class="form-label mt-2">Expected Response (JSON)</label>
                    <textarea name="functions[${funcCount}][api_response]" class="form-control" rows="15"
                        placeholder='{"status": "success", "id": 123}'></textarea>
                    </div>
                </div>
                </div>
            </div>
            </div>`;


            document.getElementById('functions-container').appendChild(funcDiv);

            const typeSelect = funcDiv.querySelector('.func-type');
            const descBox = funcDiv.querySelector('.func-api-desc');
            const apiMethodSelect = funcDiv.querySelector('.api-method');
            const apiBodySection = funcDiv.querySelector('.api-body-section');
            const apiBody = funcDiv.querySelector('.api-body');

            const sections = {
                sms: funcDiv.querySelector('.func-sms'),
                call: funcDiv.querySelector('.func-call'),
                email: funcDiv.querySelector('.func-email'),
                curl: funcDiv.querySelector('.func-curl'),
                api: funcDiv.querySelector('.func-api')
            };

            // Handle type change
            typeSelect.addEventListener('change', function() {
                Object.values(sections).forEach(div => {
                    div.style.display = 'none';
                    div.querySelectorAll('input, select, textarea').forEach(el => {
                        el.required = false;
                        el.disabled = true;
                    });
                });
                if (sections[this.value]) {
                    sections[this.value].style.display = 'block';
                    sections[this.value].querySelectorAll('input, select, textarea').forEach(el => {
                        // Skip placeholder helper dropdowns and function description - they're not required fields
                        if (!el.classList.contains('curl-placeholder-select') && 
                            !el.classList.contains('function-description')) {
                            el.required = true;
                            el.disabled = false;
                        } else {
                            el.disabled = false;
                        }
                    });
                }
            });

            // Hide API body if GET
            apiMethodSelect.addEventListener('change', function() {
                if (this.value === 'GET') {
                    apiBodySection.style.display = 'none';
                    apiBody.disabled = true;
                    apiBody.required = false;
                } else {
                    apiBodySection.style.display = 'block';
                    apiBody.disabled = false;
                    apiBody.required = true;
                }
            });

            funcDiv.querySelector('.func-name').addEventListener('input', function() {
                this.value = slugify(this.value);
                const titleLabel = funcDiv.querySelector('.func-title-label');
                const accordionBtn = funcDiv.querySelector('.accordion-button');
                titleLabel.textContent = this.value || '';
                // Add title attribute to show full name on hover
                if (this.value) {
                    titleLabel.setAttribute('title', this.value);
                    accordionBtn.setAttribute('title', `Function ${funcCount} — ${this.value}`);
                } else {
                    titleLabel.removeAttribute('title');
                    accordionBtn.removeAttribute('title');
                }
            });


            funcDiv.querySelector('.remove-func-btn').addEventListener('click', function() {
                funcDiv.remove();
            });

            // Handle CURL placeholder insertion
            const curlPlaceholderSelect = funcDiv.querySelector('.curl-placeholder-select');
            const curlTextarea = funcDiv.querySelector('.curl-request-textarea');
            
            if (curlPlaceholderSelect && curlTextarea) {
                curlPlaceholderSelect.addEventListener('change', function() {
                    const placeholder = this.value;
                    if (placeholder) {
                        // Get current cursor position
                        const startPos = curlTextarea.selectionStart;
                        const endPos = curlTextarea.selectionEnd;
                        const currentValue = curlTextarea.value;
                        
                        // Insert placeholder at cursor position
                        curlTextarea.value = currentValue.substring(0, startPos) + 
                                           placeholder + 
                                           currentValue.substring(endPos);
                        
                        // Set cursor position after inserted text
                        const newCursorPos = startPos + placeholder.length;
                        curlTextarea.setSelectionRange(newCursorPos, newCursorPos);
                        curlTextarea.focus();
                        
                        // Reset dropdown
                        this.value = '';
                    }
                });
            }

            // Prefill existing data
            if (existing) {
                typeSelect.value = existing.type;
                typeSelect.dispatchEvent(new Event('change'));
                funcDiv.querySelector('.func-name').value = existing.name || '';
                
                // Set title attributes for existing functions
                if (existing.name) {
                    const titleLabel = funcDiv.querySelector('.func-title-label');
                    const accordionBtn = funcDiv.querySelector('.accordion-button');
                    titleLabel.setAttribute('title', existing.name);
                    accordionBtn.setAttribute('title', `Function ${funcCount} — ${existing.name}`);
                }

                // UNIVERSAL: Always show function description for existing functions (all types)
                const descContainer = funcDiv.querySelector('.function-description-container');
                const descTextarea = funcDiv.querySelector('.function-description');
                if (descContainer && descTextarea) {
                    descTextarea.value = existing.function_description || '';
                    descContainer.style.display = 'block';
                }

                // Type-specific field population
                if (existing.type === 'sms') funcDiv.querySelector('.sms-template-select').value = existing.message || '';
                if (existing.type === 'email') funcDiv.querySelector('.email-template-select').value = existing.message || '';
                if (existing.type === 'call') funcDiv.querySelector('.func-call input').value = existing.phone || '';
                if (existing.type === 'curl') {
                    funcDiv.querySelector('textarea[name*="[curl_request]"]').value = existing.curl_request || '';
                    funcDiv.querySelector('textarea[name*="[curl_response]"]').value = existing.curl_response || '';
                }
                if (existing.type === 'api') {
                    funcDiv.querySelector('.api-method').value = existing.api_method || 'POST';
                    funcDiv.querySelector('.api-url').value = existing.api_url || '';
                    funcDiv.querySelector('.api-body').value = existing.api_body || '';
                    funcDiv.querySelector('textarea[name*="[api_response]"]').value = existing.api_response || '';
                    apiMethodSelect.dispatchEvent(new Event('change'));
                }
            }
        }

        document.getElementById('add-function-btn').addEventListener('click', function() {
            addFunction();
        });

        <?php if(isset($functions)): ?>
            <?php $__currentLoopData = $functions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $func): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                addFunction(<?php echo json_encode($func, 15, 512) ?>);
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        <?php endif; ?>
    </script>

    <!-- CKEditor + Placeholder -->
    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <script src="https://cdn.ckeditor.com/4.22.1/standard/ckeditor.js"></script>
    <script>
        $(function() {
            CKEDITOR.config.autoParagraph = false;
            CKEDITOR.config.versionCheck = false;
            CKEDITOR.config.enterMode = CKEDITOR.ENTER_BR;
            CKEDITOR.config.shiftEnterMode = CKEDITOR.ENTER_P;
            CKEDITOR.replace('editor1', {
                enterMode: CKEDITOR.ENTER_BR,
                filebrowserUploadUrl: "<?php echo e(route('start-dialing.upload', ['_token' => csrf_token()])); ?>",
                filebrowserUploadMethod: 'form',
                allowedContent: true
            });

            $("#multiple_labels").on('change', function() {
                var val = $(this).val();
                if (val) {
                    for (var i in CKEDITOR.instances) {
                        CKEDITOR.instances[i].insertHtml(val);
                    }
                    $(this).val('');
                }
            });
        });
    </script>

    <!-- Voice Preview -->
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const playBtn = document.getElementById("playVoiceBtn");
            const greetingInput = document.getElementById("initialGreeting");
            const voiceSelect = document.getElementById("voiceSelect");

            // Function to update preview button state
            function updatePreviewBtn() {
                playBtn.disabled = !greetingInput.value.trim();
            }

            // Initial check on page load
            updatePreviewBtn();

            // Enable/disable button on input
            greetingInput.addEventListener("input", updatePreviewBtn);

            playBtn.addEventListener("click", async function() {
                const text = greetingInput.value.trim();
                const voiceName = voiceSelect.value;
                if (!text) return;

                playBtn.disabled = true;
                playBtn.textContent = "🔊 Playing...";

                try {
                    const res = await fetch("/prompts/voice-preview", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            "X-CSRF-TOKEN": "<?php echo e(csrf_token()); ?>"
                        },
                        body: JSON.stringify({
                            text,
                            voiceName
                        })
                    });

                    const data = await res.json();

                    if (data.success && data.audio) {
                        const audio = new Audio("data:audio/mp3;base64," + data.audio);
                        audio.play();
                        audio.onended = () => {
                            playBtn.textContent = "▶ Preview";
                            updatePreviewBtn();
                        };
                    } else {
                        Swal.fire({
                            icon: "error",
                            title: "Voice Preview Failed",
                            text: data.message || "Unable to generate voice preview.",
                            confirmButtonColor: "#d33"
                        });
                        playBtn.textContent = "▶ Preview";
                        updatePreviewBtn();
                    }

                } catch (err) {
                    Swal.fire({
                        icon: "error",
                        title: "Request Error",
                        text: "Something went wrong while fetching voice preview.",
                        confirmButtonColor: "#d33"
                    });
                    playBtn.textContent = "▶ Preview";
                    updatePreviewBtn();
                }
            });
        });
    </script>

<?php $__env->stopSection(); ?>
    <!-- Voice Test Logic (Optimized with Browser STT + TTS Speed Trick) -->
    <script>
        // =====================================================
        // STATE MANAGEMENT
        // =====================================================
        let isCallActive = false;
        let isListening = false;
        let isProcessing = false;
        let currentAudio = null;
        let recognition = null;
        let conversationHistory = [];
        let retryCount = 0;
        
        const MAX_RETRIES = 3;

        // =====================================================
        // API KEY
        // =====================================================
        function getApiKey() {
            const keyInput = document.getElementById('openai_api_key');
            if (keyInput && keyInput.value) return keyInput.value;
            
            <?php if(env('OPENAI_API_KEY')): ?>
            return "<?php echo e(env('OPENAI_API_KEY')); ?>";
            <?php else: ?>
            const key = prompt("Enter your OpenAI API Key:");
            return key || "";
            <?php endif; ?>
        }

        // =====================================================
        // UI CONTROL FUNCTIONS
        // =====================================================

        // Detect mobile browser
        function isMobile() {
            return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        }

        async function startCallLoop() {
            if (isCallActive) return;
            
            // Check browser support
            if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
                alert("Speech recognition not supported. Please use Chrome, Edge, or Safari.");
                return;
            }
            
            // Check HTTPS requirement (mobile requires secure context)
            if (isMobile() && location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
                alert("Voice features require HTTPS on mobile. Please use a secure connection.");
                return;
            }
            
            // Request microphone permission FIRST (mobile fix)
            try {
                serverLog("[VoiceCall] Requesting microphone permission...");
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                stream.getTracks().forEach(t => t.stop()); // Release immediately
                serverLog("[VoiceCall] Microphone permission granted.");
            } catch (e) {
                serverLog("[VoiceCall] Microphone permission denied: " + e.message);
                alert("Microphone access denied. Please allow microphone permission and try again.");
                return;
            }
            
            isCallActive = true;
            isProcessing = false;
            retryCount = 0;
            conversationHistory = [];
            
            serverLog("[VoiceCall] Call Started (Browser STT Mode, Mobile: " + isMobile() + ")");
            startListening();
        }

        function endCallLoop() {
            isCallActive = false;
            isListening = false;
            isProcessing = false;
            
            serverLog("[VoiceCall] Call Ended by User");
            
            // Stop speech recognition
            if (recognition) {
                try { recognition.abort(); } catch(e) {}
                recognition = null;
            }
            
            // Stop volume visualizer
            stopVolumeVisualizer();
            
            // Stop any playing audio
            if (currentAudio) {
                currentAudio.pause();
                currentAudio = null;
            }
            
            uiSetCallState('idle');
        }

        function uiReset() {
            conversationHistory = [];
            const historyDiv = document.getElementById('chatHistory');
            if(historyDiv) {
                historyDiv.innerHTML = '<div id="chatPlaceholder" class="text-center text-muted mt-5"><i class="far fa-comments fa-3x mb-3"></i><p>Conversation will appear here...</p></div>';
            }
            serverLog("[VoiceCall] UI Reset");
        }

        function uiSetCallState(state) {
            const startBtn = document.getElementById('startCallBtn');
            const endBtn = document.getElementById('endCallBtn');
            const statusIndicator = document.getElementById('statusIndicator');
            const visBar = document.getElementById('visBar');

            if (!startBtn || !endBtn) return; 

            if(state === 'idle') {
                startBtn.classList.remove('d-none');
                endBtn.classList.add('d-none');
                statusIndicator.className = "badge bg-secondary mb-2 d-block mx-auto";
                statusIndicator.style.width = "fit-content";
                statusIndicator.innerText = "Ready";
                if(visBar) visBar.style.width = "0%";
            } else if (state === 'listening') {
                startBtn.classList.add('d-none');
                endBtn.classList.remove('d-none');
                statusIndicator.className = "badge bg-success mb-2 d-block mx-auto";
                statusIndicator.style.width = "fit-content";
                statusIndicator.innerText = "Listening...";
            } else if (state === 'processing') {
                statusIndicator.className = "badge bg-warning text-dark mb-2 d-block mx-auto";
                statusIndicator.style.width = "fit-content";
                statusIndicator.innerText = "Thinking...";
            } else if (state === 'speaking') {
                statusIndicator.className = "badge bg-info text-dark mb-2 d-block mx-auto";
                statusIndicator.style.width = "fit-content";
                statusIndicator.innerText = "Speaking...";
            }
        }

        // =====================================================
        // BROWSER SPEECH RECOGNITION (No API call needed!)
        // =====================================================

        function createRecognition() {
            if (recognition) {
                try { recognition.abort(); } catch(e) {}
                recognition = null;
            }

            const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
            recognition = new SpeechRecognition();
            recognition.continuous = false;
            recognition.interimResults = false;
            recognition.lang = 'en-IN'; // Indian English
            recognition.maxAlternatives = 1;

            recognition.onstart = () => {
                isListening = true;
                uiSetCallState('listening');
                serverLog("[VoiceCall] Browser STT listening...");
            };

            recognition.onresult = (event) => {
                const transcript = event.results[0][0].transcript;
                serverLog("[VoiceCall] User said: " + transcript);

                if (transcript.trim() && isCallActive && !isProcessing) {
                    isProcessing = true;
                    isListening = false;
                    processUserInput(transcript);
                }
            };

            recognition.onerror = (event) => {
                serverLog("[VoiceCall] STT Error: " + event.error);
                isListening = false;

                if (event.error === 'no-speech') {
                    // No speech detected, restart listening
                    if (isCallActive && !isProcessing) {
                        setTimeout(() => startListening(), 500);
                    }
                } else if (event.error === 'aborted') {
                    // Intentionally aborted, ignore
                } else if (event.error === 'network') {
                    serverLog("[VoiceCall] Network error in speech recognition");
                    if (isCallActive && !isProcessing) {
                        setTimeout(() => startListening(), 1000);
                    }
                } else {
                    // Other errors - try to recover
                    if (isCallActive && !isProcessing) {
                        retryCount++;
                        if (retryCount < MAX_RETRIES) {
                            setTimeout(() => startListening(), 1000);
                        }
                    }
                }
            };

            recognition.onend = () => {
                isListening = false;
                
                // Auto-restart if call is still active and not processing
                if (isCallActive && !isProcessing) {
                    setTimeout(() => {
                        if (isCallActive && !isProcessing) {
                            startListening();
                        }
                    }, 300);
                }
            };

            return recognition;
        }

        function startListening() {
            if (!isCallActive || isProcessing || isListening) {
                return;
            }

            try {
                createRecognition();
                recognition.start();
                retryCount = 0;
                
                // Start volume visualizer in parallel
                startVolumeVisualizer();
                
            } catch (e) {
                serverLog("[VoiceCall] Error starting recognition: " + e.message);
                setTimeout(() => {
                    if (isCallActive && !isProcessing) {
                        startListening();
                    }
                }, 500);
            }
        }
        
        // Volume visualizer variables
        let visualizerStream = null;
        let visualizerContext = null;
        let visualizerInterval = null;
        
        async function startVolumeVisualizer() {
            try {
                visualizerStream = await navigator.mediaDevices.getUserMedia({ 
                    audio: { echoCancellation: true, noiseSuppression: true } 
                });
                
                visualizerContext = new (window.AudioContext || window.webkitAudioContext)();
                const source = visualizerContext.createMediaStreamSource(visualizerStream);
                const analyser = visualizerContext.createAnalyser();
                analyser.fftSize = 256;
                source.connect(analyser);
                
                const bufferLength = analyser.frequencyBinCount;
                const dataArray = new Uint8Array(bufferLength);
                const visBar = document.getElementById('visBar');
                
                visualizerInterval = setInterval(() => {
                    if (!isCallActive || !isListening) {
                        stopVolumeVisualizer();
                        return;
                    }
                    
                    analyser.getByteFrequencyData(dataArray);
                    let sum = 0;
                    for (let i = 0; i < bufferLength; i++) sum += dataArray[i];
                    const avgVol = sum / bufferLength;
                    
                    if (visBar) visBar.style.width = Math.min(100, avgVol * 2) + "%";
                }, 50);
                
            } catch (e) {
                serverLog("[VoiceCall] Visualizer error: " + e.message);
            }
        }
        
        function stopVolumeVisualizer() {
            if (visualizerInterval) {
                clearInterval(visualizerInterval);
                visualizerInterval = null;
            }
            if (visualizerStream) {
                visualizerStream.getTracks().forEach(t => t.stop());
                visualizerStream = null;
            }
            if (visualizerContext) {
                try { visualizerContext.close(); } catch(e) {}
                visualizerContext = null;
            }
            const visBar = document.getElementById('visBar');
            if (visBar) visBar.style.width = "0%";
        }

        function stopListening() {
            if (recognition) {
                try { recognition.abort(); } catch(e) {}
                recognition = null;
            }
            isListening = false;
        }

        // =====================================================
        // AI PROCESSING (LLM + TTS only - STT is browser-native)
        // =====================================================

        async function processUserInput(userText) {
            uiSetCallState('processing');
            stopListening();
            
            const apiKey = getApiKey();
            if (!apiKey) {
                alert("OpenAI API Key is required.");
                isProcessing = false;
                endCallLoop();
                return;
            }
            
            try {
                // Add user message to history & display
                conversationHistory.push({ role: 'user', content: userText });
                appendMessage('user', userText);
                
                // ===========================================
                // STEP 1: Chat Completion (GPT API)
                // ===========================================
                serverLog("[VoiceCall] Getting AI response...");
                
                const systemPrompt = CKEDITOR.instances.editor1.getData().replace(/<[^>]*>/g, '');
                
                const messages = [
                    { role: 'system', content: systemPrompt },
                    ...conversationHistory
                ];

                const chatResponse = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: 'gpt-4o-mini',
                        messages: messages,
                        max_tokens: 150,
                        temperature: 0.7
                    })
                });

                if (!chatResponse.ok) {
                    const errData = await chatResponse.json();
                    throw new Error("Chat Error: " + (errData.error?.message || 'Failed'));
                }

                const chatData = await chatResponse.json();
                const aiText = chatData.choices?.[0]?.message?.content || "I didn't understand.";
                
                serverLog("[VoiceCall] AI said: " + aiText);
                
                // Add AI message to history & display
                conversationHistory.push({ role: 'assistant', content: aiText });
                appendMessage('assistant', aiText);
                
                // ===========================================
                // STEP 2: TTS with Speed Trick
                // ===========================================
                serverLog("[VoiceCall] Generating speech (speed trick)...");
                uiSetCallState('speaking');
                
                const voiceName = document.getElementById("voiceSelect").value || 'alloy';
                
                // Generate at normal speed (faster API response)
                const ttsResponse = await fetch('https://api.openai.com/v1/audio/speech', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: 'tts-1',
                        voice: voiceName,
                        input: aiText,
                        speed: 1.0  // Normal generation (faster)
                    })
                });

                if (!ttsResponse.ok) {
                    const errData = await ttsResponse.json();
                    throw new Error("TTS Error: " + (errData.error?.message || 'Failed'));
                }

                // Play audio with slower playback rate for natural speech
                const audioBlob = await ttsResponse.blob();
                const audioUrl = URL.createObjectURL(audioBlob);
                
                await playAudioWithSpeedTrick(audioUrl);
                
                URL.revokeObjectURL(audioUrl);
                
                // Resume listening
                isProcessing = false;
                if (isCallActive) {
                    serverLog("[VoiceCall] AI finished. Your turn.");
                    setTimeout(() => startListening(), 500);
                }

            } catch (e) {
                serverLog("[VoiceCall] Error: " + e.message);
                console.error(e);
                isProcessing = false;
                
                retryCount++;
                if (retryCount < MAX_RETRIES && isCallActive) {
                    serverLog("[VoiceCall] Retrying...");
                    setTimeout(() => startListening(), 1000);
                } else {
                    alert("Error: " + e.message);
                    endCallLoop();
                }
            }
        }

        // Legacy function for MediaRecorder-based audio (for compatibility)
        async function processAudio(blob) {
            // Fallback: Use Whisper API if browser STT fails
            const apiKey = getApiKey();
            if (!apiKey) return;
            
            try {
                const sttFormData = new FormData();
                sttFormData.append('file', blob, 'audio.webm');
                sttFormData.append('model', 'whisper-1');
                
                const sttResponse = await fetch('https://api.openai.com/v1/audio/transcriptions', {
                    method: 'POST',
                    headers: { 'Authorization': `Bearer ${apiKey}` },
                    body: sttFormData
                });

                if (!sttResponse.ok) throw new Error("STT Failed");

                const sttData = await sttResponse.json();
                const userText = sttData.text || '';
                
                if (userText.trim()) {
                    processUserInput(userText);
                } else {
                    isProcessing = false;
                    if (isCallActive) startListening();
                }
            } catch(e) {
                serverLog("[VoiceCall] Whisper fallback error: " + e.message);
                isProcessing = false;
                if (isCallActive) startListening();
            }
        }

        // =====================================================
        // AUDIO PLAYBACK (with Speed Trick)
        // =====================================================

        function playAudioWithSpeedTrick(url) {
            return new Promise((resolve) => {
                if (currentAudio) {
                    currentAudio.pause();
                    currentAudio = null;
                }

                currentAudio = new Audio(url);
                
                // SPEED TRICK: Slow down playback for natural speech
                // Audio was generated at 1.0x (faster API), played at 0.85x (natural)
                currentAudio.playbackRate = 0.85;
                
                currentAudio.onended = () => {
                    currentAudio = null;
                    serverLog("[VoiceCall] AI Finished Speaking.");
                    resolve();
                };
                
                currentAudio.onerror = (e) => {
                    console.error("Audio playback error:", e);
                    currentAudio = null;
                    resolve();
                };
                
                currentAudio.play().catch((e) => {
                    console.error("Playback failed:", e);
                    currentAudio = null;
                    resolve();
                });
            });
        }

        // Simple playback (no speed trick)
        function playAudioFromUrl(url) {
            return new Promise((resolve) => {
                if (currentAudio) {
                    currentAudio.pause();
                    currentAudio = null;
                }

                currentAudio = new Audio(url);
                
                currentAudio.onended = () => {
                    currentAudio = null;
                    resolve();
                };
                
                currentAudio.onerror = () => {
                    currentAudio = null;
                    resolve();
                };
                
                currentAudio.play().catch(() => {
                    currentAudio = null;
                    resolve();
                });
            });
        }

        // =====================================================
        // UI HELPERS
        // =====================================================

        function appendMessage(role, text) {
            const historyDiv = document.getElementById('chatHistory');
            const ph = document.getElementById('chatPlaceholder');
            if(ph) ph.remove();
            
            const div = document.createElement('div');
            div.className = "chat-message " + (role === 'user' ? 'user-msg' : 'ai-msg');
            
            const roleLabel = document.createElement('div');
            roleLabel.className = 'chat-role';
            roleLabel.innerText = role === 'user' ? 'You' : 'Agent';
            
            const bubble = document.createElement('div');
            bubble.className = "chat-bubble shadow-sm";
            bubble.innerHTML = text; 

            div.appendChild(roleLabel);
            div.appendChild(bubble);

            historyDiv.appendChild(div);
            historyDiv.scrollTop = historyDiv.scrollHeight;
        }

        function serverLog(message, data = null) {
            console.log(message, data);
            fetch("<?php echo e(route('prompts.logClientEvent')); ?>", {
                method: 'POST',
                headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": "<?php echo e(csrf_token()); ?>" },
                body: JSON.stringify({ message, data })
            }).catch(() => {});
        }

        // =====================================================
        // EVENT LISTENERS (DOM Ready)
        // =====================================================

        document.addEventListener("DOMContentLoaded", function() {
            const openModalBtn = document.getElementById("openTestModalBtn");
            const modalEl = document.getElementById("voiceTestModal");
            
            if(modalEl) {
                const modal = new bootstrap.Modal(modalEl);
                if(openModalBtn) {
                    openModalBtn.addEventListener("click", function() {
                        uiReset();
                        uiSetCallState('idle');
                        modal.show();
                    });
                }
                modalEl.addEventListener('hidden.bs.modal', function () {
                    if(isCallActive) endCallLoop();
                });
            }
        });
    </script>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /var/www/html/leadmine/leadmine_pro/resources/views/prompts/edit.blade.php ENDPATH**/ ?>