{% 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">
            <div class="row border-bottom px-0">
                <div class="col text-center pb-2" x-text="chat_name">
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-12 overflow-auto p-4" style="{{ dialog_height|default:'height: calc(100vh - 90px - var(--app-top-navigation-height));' }}" x-ref="target_div"></div>
            </div>

            <div class="row">
                <div class="col-auto text-center ps-2 pe-1">
                    <button @click="start_listening()" class="btn btn-app-primary-outlined" x-show="!speech_listening">
                        <i class="bi bi-mic"></i>
                    </button>
                    <button @click="stop_listening()" class="btn btn-app-danger" x-show="speech_listening">
                        <i class="bi bi-mic-fill"></i>
                    </button>
                </div>

                <div class="col text-center px-1">
                    <input @keyup.enter="send_chat({message_body: message_body})" autocomplete="off" class="form-control" name="request_message" type="text" x-init="$el.focus()" x-model="message_body">
                </div>

                <div class="col-auto text-center ps-1 pe-2">
                    <button @click="send_chat({message_body: message_body})" class="btn btn-app-primary">
                        <i class="bi bi-send"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
