{% extends 'django_spire/speech/speech_recognition.html' %}

{% block speech_recognition_content %}
    <div
        class="row"
        x-data="{
            chat_id: '{{ chat.id|default:'0' }}',
            chat_name: '{{ chat.name_shortened|default:'New Chat'|escapejs }}',
            message_body: '',
            request_message_view: new ViewGlue('{% url "django_spire:ai:chat:message:request:new" %}'),

            init() {
                if (this.chat_id && this.chat_id !== '0' && this.chat_id !== '') {
                    this.load_messages()
                }

                setTimeout(() => {
                    if (this.$refs.target_div) {
                        this.smooth_scroll_to_bottom()
                    }
                }, 1500)

                this.speech_recognition.onresult = () => {
                    this.message_body = this.speech_transcript
                    this.send_chat({message_body: this.message_body, synthesis_speech_for_response: true})
                }
            },

            load_messages() {
                let load_messages_view = new ViewGlue(`/django_spire/ai/chat/message/load/chat/${this.chat_id}/`)
                load_messages_view.render_insert_adjacent(this.$refs.target_div, {})
            },

            smooth_scroll_to_bottom() {
                let target = this.$refs.target_div
                let start = target.scrollTop
                let end = target.scrollHeight - target.clientHeight
                let duration = 400
                let start_time = performance.now()

                function animate(current_time) {
                    let elapsed = current_time - start_time
                    let progress = Math.min(elapsed / duration, 1)
                    let ease = progress * (2 - progress)

                    target.scrollTop = start + (end - start) * ease

                    if (progress < 1) {
                        requestAnimationFrame(animate)
                    }
                }

                requestAnimationFrame(animate)
            },

            async send_chat({message_body = '', synthesis_speech_for_response = false}) {
                if (message_body !== '') {
                    let was_new_chat = (this.chat_id === '0' || this.chat_id === 0 || this.chat_id === '')

                    let response_html = await this.request_message_view.render_insert_adjacent(
                        this.$refs.target_div,
                        {
                            chat_id: this.chat_id,
                            message_body: message_body,
                            synthesis_speech: synthesis_speech_for_response
                        }
                    )

                    if (was_new_chat) {
                        this.chat_name = message_body.length > 24 ? message_body.substring(0, 21) + '...' : message_body

                        let message_element = this.$refs.target_div.querySelector('[data-message-chat-id]')

                        if (message_element) {
                            this.chat_id = message_element.dataset.messageChatId
                            $dispatch('new-chat-created', {chat_id: parseInt(this.chat_id)})
                        }
                    }

                    this.message_body = ''
                    $dispatch('chat-loaded')
                }
            },

            speak_text(text) {
                if ('speechSynthesis' in window) {
                    let utterance = new SpeechSynthesisUtterance(text)
                    window.speechSynthesis.speak(utterance)
                }
            }
        }"
        @send-message.window="send_chat({message_body: $event.detail.message_body})" @speak.window="speak_text($event.detail.text)"
    >
        <div class="col-12 d-flex flex-column" style="{{ dialog_height|default:'height: calc(100dvh - 52px - var(--app-top-navigation-height));' }}">
            <div class="flex-grow-1 overflow-y-auto overflow-x-hidden">
                <div class="mx-auto py-3" style="max-width: 56rem;" x-ref="target_div"></div>
            </div>

            <div class="flex-shrink-0 bg-app-layer-one">
                <div class="mx-auto px-3 py-3" style="max-width: 56rem;">
                    <div class="d-flex align-items-center gap-2">
                        <button
                            @click="speech_listening ? stop_listening() : start_listening()"
                            class="d-flex align-items-center justify-content-center rounded-circle flex-shrink-0 border-0 bg-app-primary"
                            style="width: 34px; height: 34px;"
                            :class="speech_listening ? 'text-app-primary' : 'text-muted'"
                        >
                            <i class="bi text-white" :class="speech_listening ? 'bi-mic-fill' : 'bi-mic'"></i>
                        </button>

                        <div class="d-flex align-items-center flex-grow-1 rounded-pill ps-3 pe-1 py-1 border bg-app-layer-two" style="height: 44px;">
                            <input
                                @keyup.enter="send_chat({message_body: message_body})"
                                autocomplete="off"
                                class="border-0 bg-transparent shadow-none px-0 flex-grow-1 ds-fs-9"
                                name="request_message"
                                placeholder="Ask a question..."
                                style="outline: none;"
                                type="text"
                                x-init="$el.focus()"
                                x-model="message_body"
                            >

                            <button
                                @click="send_chat({message_body: message_body})"
                                class="d-flex align-items-center justify-content-center rounded-circle flex-shrink-0 border-0 bg-app-primary text-white"
                                style="width: 34px; height: 34px;"
                            >
                                <i class="bi bi-send-fill"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
