@extends('layouts.app')
@section('title', 'Add New Prompt')

@section('content')
    <div class="container content">
        <!-- Page Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h3 class="mb-0">Add New Prompt</h3>
            <a href="{{ route('prompts.index') }}" class="btn btn-secondary">Back</a>
        </div>

        <div class="card card-shadow p-3">
            <form action="{{ route('prompts.store') }}" method="POST">
                @csrf

                <div class="mb-3">
                    <label class="form-label">Title</label>
                    <input type="text" name="title" class="form-control" value="{{ old('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 value="alloy">Alloy (Male) - Warm & confident</option>
                            <option value="ash">Ash (Male) - Calm & grounded</option>
                            <option value="ballad">Ballad (Male) - Expressive & emotional</option>
                            <option value="coral">Coral (Female) - Bright & energetic</option>
                            <option value="echo">Echo (Male) - Clear & neutral</option>
                            <option value="sage">Sage (Female) - Gentle & wise</option>
                            <option value="shimmer">Shimmer (Female) - Soft & friendly</option>
                            <option value="verse" selected>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"
                        placeholder="Enter your greeting text...">{{ old('initial_greeting') }}</textarea>
                </div>

                <div class="mb-3 col-6">
                    <label class="form-label"> Lead Placeholders </label>
                    <div class="input-group mb-3">
                        <span class="input-group-text"><i class="ti-user"></i></span>
                        <span id="setBoxValue" style="display:none;"></span>
                        <select id="multiple_labels" class="form-select" autocomplete="off">
                            <option value="">Select to Insert</option>
                            @foreach ($label_list as $list)
                                <option value="[[{{ $list->title }}]]">{{ $list->title }}</option>
                            @endforeach;
                        </select>
                    </div>
                </div>

                <!-- Description -->
                <div class="mb-3">
                    <label class="form-label">Description</label>
                    <textarea id="editor1" rows="12" name="description" class="form-control" placeholder="Describe your prompt...">{{ old('description') }}</textarea>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-success">Add Prompt</button>
                    <a href="{{ route('prompts.index') }}" class="btn btn-secondary">Back</a>
                </div>
            </form>
        </div>
    </div>

    {{-- SweetAlert2 --}}

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

            // Enable play button only if greeting text exists
            greetingInput.addEventListener("input", function() {
                playBtn.disabled = !this.value.trim();
            });

            // Preview voice using OpenAI TTS API via Laravel backend
            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": "{{ 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";
                            playBtn.disabled = false;
                        };
                    } else {
                        Swal.fire({
                            icon: "error",
                            title: "Voice Preview Failed",
                            text: data.message || "Unable to generate voice preview.",
                            confirmButtonColor: "#d33"
                        });
                        playBtn.textContent = "▶ Preview";
                        playBtn.disabled = false;
                    }

                } catch (err) {
                    Swal.fire({
                        icon: "error",
                        title: "Request Error",
                        text: "Something went wrong while fetching voice preview.",
                        confirmButtonColor: "#d33"
                    });
                    playBtn.textContent = "▶ Preview";
                    playBtn.disabled = false;
                }
            });
        });
    </script>
    <script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM="
        crossorigin="anonymous"></script>
    <script src="https://cdn.ckeditor.com/4.22.1/standard/ckeditor.js"></script>
    <script language="javascript">
        $(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: "{{ route('start-dialing.upload', ['_token' => csrf_token()]) }}",
                filebrowserUploadMethod: 'form',
                allowedContent: true

            });

            $("#multiple_labels").on('change', function() {
                console.log($(this).val());
                var hidden_box = $('#setBoxValue').html();
                if (hidden_box == 'subject_box') {

                    var cursorPos = $('#subject_box').prop('selectionStart');
                    var v = $('#subject_box').val();
                    var textBefore = v.substring(0, cursorPos);
                    var textAfter = v.substring(cursorPos, v.length);
                    $('#subject_box').val(textBefore + $(this).val() + textAfter);
                } else {
                    for (var i in CKEDITOR.instances) {
                        CKEDITOR.instances[i].insertHtml($(this).val());
                    }
                }
            });

            CKEDITOR.instances['editor1'].on('contentDom', function() {
                this.document.on('click', function(event) {
                    $('#setBoxValue').html('');
                });
            });
        });

        $('#subject_box').on('click', function() {
            $('#setBoxValue').html('subject_box');
        });
    </script>
@endsection
