@props(['target' => 'description']) {{-- The ID of the textarea to fill --}}

<div x-data="audioRecorder('{{ $target }}')" class="relative inline-block">
    <button type="button"
        x-show="!isRecording && !isProcessing"
        @click="startRecording"
        class="flex items-center gap-2 text-xs font-bold text-slate-500 bg-white border border-slate-200 px-3 py-1.5 rounded-full hover:border-indigo-500 hover:text-indigo-600 transition shadow-sm">
        <i class="ph-bold ph-microphone"></i>
        <span>Dictate</span>
    </button>

    <button type="button"
        x-show="isRecording"
        @click="stopRecording"
        class="flex items-center gap-2 text-xs font-bold text-white bg-red-500 border border-red-600 px-3 py-1.5 rounded-full animate-pulse shadow-md">
        <span class="w-2 h-2 bg-white rounded-full"></span>
        <span>Stop & Transcribe</span>
    </button>

    <div x-show="isProcessing" class="flex items-center gap-2 text-xs font-bold text-indigo-600 bg-indigo-50 border border-indigo-100 px-3 py-1.5 rounded-full">
        <i class="ph-bold ph-spinner animate-spin"></i>
        <span>AI Processing...</span>
    </div>

    <div x-show="error" x-text="error" class="absolute top-full mt-1 left-0 w-48 text-[10px] text-red-500 font-bold"></div>
</div>

<script>
    document.addEventListener('alpine:init', () => {
        Alpine.data('audioRecorder', (targetId) => ({
            isRecording: false,
            isProcessing: false,
            mediaRecorder: null,
            audioChunks: [],
            error: null,
            targetId: targetId,

            async startRecording() {
                this.error = null;
                this.audioChunks = [];
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    this.mediaRecorder = new MediaRecorder(stream);

                    this.mediaRecorder.ondataavailable = (event) => {
                        this.audioChunks.push(event.data);
                    };

                    this.mediaRecorder.onstop = () => {
                        this.uploadAudio();
                    };

                    this.mediaRecorder.start();
                    this.isRecording = true;
                } catch (err) {
                    console.error(err);
                    this.error = "Microphone access denied.";
                }
            },

            stopRecording() {
                if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
                    this.mediaRecorder.stop();
                    this.isRecording = false;
                    this.isProcessing = true;
                }
            },

            async uploadAudio() {
                const audioBlob = new Blob(this.audioChunks, { type: 'audio/webm' });
                const formData = new FormData();
                formData.append('audio', audioBlob, 'recording.webm');

                // Add CSRF Token
                formData.append('_token', document.querySelector('meta[name="csrf-token"]').getAttribute('content'));

                try {
                    const response = await fetch("{{ route('admin.dictate') }}", {
                        method: 'POST',
                        body: formData
                    });

                    const data = await response.json();

                    if (data.text) {
                        // Append text to the target textarea
                        const textarea = document.getElementById(this.targetId);
                        if(textarea) {
                            const currentVal = textarea.value;
                            textarea.value = currentVal ? currentVal + " " + data.text : data.text;
                            // Trigger input event for auto-resize libraries
                            textarea.dispatchEvent(new Event('input'));
                        }
                    } else {
                        this.error = "Transcription failed.";
                    }
                } catch (err) {
                    this.error = "Server error.";
                } finally {
                    this.isProcessing = false;
                }
            }
        }));
    });
</script>
