{{-- =============================================
   FLOATING AI CHAT POPUP
   Bisa dipakai di layouts/app.blade.php (authenticated)
   maupun di halaman welcome (guest)

   Di app.blade.php   : @include('layouts.ai-chat')
   Di welcome.blade.php : @include('layouts.ai-chat', ['isGuest' => true])
============================================= --}}

@php
    $isGuest      = $isGuest ?? !auth()->check();
    $authUserName = auth()->check() ? auth()->user()->name : null;
    $authUserRole = auth()->check() ? (auth()->user()->role ?? 'pasien') : null;

    $sapaanRole = match($authUserRole) {
        'dokter'               => 'Dok',
        'admin', 'super_admin' => 'Admin',
        'petugas'              => 'Petugas',
        default                => null,
    };
@endphp

<div
    x-data="{
        open: false,
        guestName: '',
        guestNameConfirmed: {{ $isGuest ? 'false' : 'true' }},
        isGuest: {{ $isGuest ? 'true' : 'false' }},
        authName: {{ $authUserName ? json_encode($authUserName) : 'null' }},
        sapaanRole: {{ $sapaanRole ? json_encode($sapaanRole) : 'null' }},

        get displayName() {
            return this.isGuest ? this.guestName : this.authName;
        },

        get welcomeText() {
            if (this.isGuest) return 'Halo! Saya dr. Andi. Sebelum kita mulai, boleh saya tahu nama Anda?';
            if (this.sapaanRole === 'Dok') return 'Selamat datang kembali, ' + this.sapaanRole + ' ' + this.authName + '. Ada yang bisa saya bantu?';
            return 'Halo, ' + (this.sapaanRole ? this.sapaanRole + ' ' : '') + this.authName + '! Ada yang bisa saya bantu seputar kesehatan?';
        },

        messages: [],
        input: '',
        loading: false,
        csrfToken: document.querySelector('meta[name=csrf-token]')?.content ?? '',

        init() {
            this.messages = [{
                role: 'ai',
                text: this.welcomeText,
                time: new Date().toLocaleTimeString('id-ID', {hour:'2-digit', minute:'2-digit'})
            }];
        },

        confirmGuestName() {
            const name = this.guestName.trim();
            if (!name) return;
            this.guestNameConfirmed = true;
            const now = new Date().toLocaleTimeString('id-ID', {hour:'2-digit', minute:'2-digit'});
            // Update pesan pertama dengan sapaan nama
            this.messages = [{
                role: 'ai',
                text: 'Senang berkenalan dengan Anda, ' + name + '! Ada keluhan atau pertanyaan kesehatan yang ingin Anda sampaikan?',
                time: now
            }];
            this.$nextTick(() => {
                this.scrollToBottom();
                this.$refs.chatInput?.focus();
            });
        },

        toggleChat() {
            this.open = !this.open;
            if (this.open) {
                this.$nextTick(() => {
                    this.scrollToBottom();
                    if (this.guestNameConfirmed) this.$refs.chatInput?.focus();
                    else this.$refs.guestNameInput?.focus();
                });
            }
        },

        scrollToBottom() {
            const el = this.$refs.chatBody;
            if (el) el.scrollTop = el.scrollHeight;
        },

        async sendMessage() {
            const text = this.input.trim();
            if (!text || this.loading) return;

            const now = new Date().toLocaleTimeString('id-ID', {hour:'2-digit', minute:'2-digit'});
            this.messages.push({ role: 'user', text, time: now });
            this.input = '';
            this.loading = true;
            this.$nextTick(() => this.scrollToBottom());

            try {
                const body = { message: text };
                if (this.isGuest) body.guest_name = this.guestName;

                const res = await fetch('/ai/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': this.csrfToken,
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify(body)
                });

                const data = await res.json();
                const reply = data.reply ?? 'Maaf, saya tidak dapat merespons saat ini.';
                const aiTime = new Date().toLocaleTimeString('id-ID', {hour:'2-digit', minute:'2-digit'});
                this.messages.push({ role: 'ai', text: reply, time: aiTime });
            } catch (e) {
                this.messages.push({ role: 'ai', text: 'Koneksi terputus. Silakan coba lagi.', time: new Date().toLocaleTimeString('id-ID', {hour:'2-digit', minute:'2-digit'}) });
            } finally {
                this.loading = false;
                this.$nextTick(() => this.scrollToBottom());
            }
        },

        handleEnter(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        }
    }"
    class="fixed bottom-6 right-6 z-[9999] flex flex-col items-end gap-3"
>
    {{-- ── POPUP CHAT WINDOW ── --}}
    <div
        x-show="open"
        x-cloak
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0 scale-90 translate-y-4"
        x-transition:enter-end="opacity-100 scale-100 translate-y-0"
        x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="opacity-100 scale-100 translate-y-0"
        x-transition:leave-end="opacity-0 scale-90 translate-y-4"
        class="ai-chat-window"
        style="transform-origin: bottom right;"
    >
        {{-- Header --}}
        <div class="ai-chat-header">
            <div class="flex items-center gap-3">
                <div class="relative">
                    <div class="w-9 h-9 rounded-full bg-white/20 flex items-center justify-center ring-2 ring-white/30">
                        <i class="fas fa-user-md text-white text-sm"></i>
                    </div>
                    <span class="absolute bottom-0 right-0 w-2.5 h-2.5 bg-green-400 rounded-full ring-2 ring-teal-600"></span>
                </div>
                <div>
                    <p class="text-white font-semibold text-sm leading-none">dr. Andi</p>
                    <p class="text-teal-200 text-xs mt-0.5">Dokter Umum · Klinik Kesehatan Digital</p>
                </div>
            </div>
            <div class="flex items-center gap-2">
                <button
                    @click="messages = [{ role: 'ai', text: welcomeText, time: new Date().toLocaleTimeString('id-ID', {hour:'2-digit', minute:'2-digit'}) }]; if(isGuest) { guestNameConfirmed = false; guestName = ''; }"
                    title="Bersihkan chat"
                    class="w-7 h-7 rounded-lg bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors"
                >
                    <i class="fas fa-trash-alt text-white/70 text-xs"></i>
                </button>
                <button @click="open = false" class="w-7 h-7 rounded-lg bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors">
                    <i class="fas fa-times text-white text-xs"></i>
                </button>
            </div>
        </div>

        {{-- Body --}}
        <div x-ref="chatBody" class="ai-chat-body">

            {{-- Quick chips (hanya muncul saat sudah confirmed & pesan masih 1) --}}
            <template x-if="guestNameConfirmed && messages.length === 1">
                <div class="flex flex-wrap gap-1.5 mb-3">
                    <button @click="input = 'Saya demam sudah 2 hari, apa yang harus dilakukan?'; sendMessage()" class="ai-chip">Demam 2 hari</button>
                    <button @click="input = 'Obat apa untuk sakit kepala?'; sendMessage()" class="ai-chip">Sakit kepala</button>
                    <button @click="input = 'Kapan saya harus ke IGD?'; sendMessage()" class="ai-chip">Kapan ke IGD?</button>
                </div>
            </template>

            {{-- Messages --}}
            <template x-for="(msg, i) in messages" :key="i">
                <div :class="msg.role === 'user' ? 'flex justify-end' : 'flex justify-start'" class="mb-3">
                    <template x-if="msg.role === 'ai'">
                        <div class="w-7 h-7 rounded-full bg-teal-100 dark:bg-teal-900/50 flex items-center justify-center shrink-0 mr-2 mt-0.5">
                            <i class="fas fa-user-md text-teal-600 dark:text-teal-400" style="font-size: 0.65rem;"></i>
                        </div>
                    </template>
                    <div class="max-w-[78%]">
                        <div :class="msg.role === 'user' ? 'ai-bubble-user' : 'ai-bubble-ai'" x-text="msg.text"></div>
                        <p :class="msg.role === 'user' ? 'text-right' : 'text-left'" class="text-[10px] text-slate-400 dark:text-slate-500 mt-0.5 px-1" x-text="msg.time"></p>
                    </div>
                </div>
            </template>

            {{-- Loading --}}
            <div x-show="loading" class="flex justify-start mb-3">
                <div class="w-7 h-7 rounded-full bg-teal-100 dark:bg-teal-900/50 flex items-center justify-center shrink-0 mr-2 mt-0.5">
                    <i class="fas fa-user-md text-teal-600 dark:text-teal-400" style="font-size: 0.65rem;"></i>
                </div>
                <div class="ai-bubble-ai">
                    <div class="flex items-center gap-1 py-0.5">
                        <span class="ai-dot" style="animation-delay: 0ms;"></span>
                        <span class="ai-dot" style="animation-delay: 160ms;"></span>
                        <span class="ai-dot" style="animation-delay: 320ms;"></span>
                    </div>
                </div>
            </div>
        </div>

        {{-- Input Area --}}
        <div class="ai-chat-footer">

            {{-- Guest: form nama dulu --}}
            <template x-if="isGuest && !guestNameConfirmed">
                <div class="flex gap-2">
                    <input
                        x-ref="guestNameInput"
                        x-model="guestName"
                        @keydown.enter="confirmGuestName()"
                        type="text"
                        placeholder="Nama Anda..."
                        class="flex-1 px-3 py-2 text-sm rounded-xl border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-800 text-slate-800 dark:text-slate-100 outline-none focus:border-teal-400"
                    >
                    <button
                        @click="confirmGuestName()"
                        :disabled="!guestName.trim()"
                        class="px-4 py-2 bg-teal-500 hover:bg-teal-600 disabled:opacity-40 text-white text-sm font-medium rounded-xl transition-colors"
                    >
                        Mulai
                    </button>
                </div>
            </template>

            {{-- Chat input normal --}}
            <template x-if="!isGuest || guestNameConfirmed">
                <div>
                    <div class="ai-input-wrapper">
                        <textarea
                            x-ref="chatInput"
                            x-model="input"
                            @keydown="handleEnter($event)"
                            :disabled="loading"
                            placeholder="Ketik keluhan atau pertanyaan..."
                            rows="1"
                            class="ai-textarea"
                        ></textarea>
                        <button @click="sendMessage" :disabled="loading || !input.trim()" class="ai-send-btn">
                            <i x-show="!loading" class="fas fa-paper-plane text-xs"></i>
                            <i x-show="loading" class="fas fa-spinner fa-spin text-xs"></i>
                        </button>
                    </div>
                    <p class="text-center text-[10px] text-slate-400 dark:text-slate-500 mt-2">
                        Konsultasi awal · Bukan pengganti pemeriksaan langsung
                    </p>
                </div>
            </template>
        </div>
    </div>

    {{-- ── FAB Button ── --}}
    <button @click="toggleChat()" class="ai-fab" :title="open ? 'Tutup' : 'Konsultasi dengan dr. Andi'">
        <span x-show="!open" class="ai-fab-icon">
            <i class="fas fa-comment-medical text-xl"></i>
            <span class="ai-fab-pulse"></span>
        </span>
        <span x-show="open" class="ai-fab-icon">
            <i class="fas fa-times text-xl"></i>
        </span>
    </button>
</div>

<style>
[x-cloak] { display: none !important; }

.ai-chat-window {
    width: 360px;
    max-width: calc(100vw - 2rem);
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 1.25rem;
    box-shadow: 0 20px 60px rgba(0,0,0,0.15), 0 4px 16px rgba(20,184,166,0.1);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    max-height: min(520px, calc(100vh - 6rem));
}
.dark .ai-chat-window { background: #1e293b; border-color: #334155; box-shadow: 0 20px 60px rgba(0,0,0,0.5); }

.ai-chat-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 0.875rem 1rem;
    background: linear-gradient(135deg, #14b8a6, #0d9488);
    flex-shrink: 0;
}

.ai-chat-body { flex: 1; overflow-y: auto; padding: 1rem; background: #f8fafc; scroll-behavior: smooth; }
.dark .ai-chat-body { background: #0f172a; }
.ai-chat-body::-webkit-scrollbar { width: 4px; }
.ai-chat-body::-webkit-scrollbar-thumb { background: #14b8a6; border-radius: 2px; }

.ai-bubble-user {
    background: linear-gradient(135deg, #14b8a6, #0d9488);
    color: #fff; padding: 0.5rem 0.875rem;
    border-radius: 1rem 1rem 0.25rem 1rem;
    font-size: 0.8125rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word;
}
.ai-bubble-ai {
    background: #fff; color: #1e293b; border: 1px solid #e2e8f0;
    padding: 0.5rem 0.875rem;
    border-radius: 1rem 1rem 1rem 0.25rem;
    font-size: 0.8125rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word;
    box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.dark .ai-bubble-ai { background: #1e293b; border-color: #334155; color: #e2e8f0; box-shadow: none; }

.ai-dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: #14b8a6; animation: ai-bounce 0.8s infinite ease-in-out both; }
@keyframes ai-bounce { 0%,80%,100%{transform:scale(0.6);opacity:0.5} 40%{transform:scale(1);opacity:1} }

.ai-chip {
    padding: 0.25rem 0.625rem; border: 1px solid #14b8a6; border-radius: 999px;
    font-size: 0.7rem; font-weight: 500; color: #0d9488; background: #f0fdf9;
    cursor: pointer; transition: all 0.15s; white-space: nowrap;
}
.ai-chip:hover { background: #14b8a6; color: white; }
.dark .ai-chip { background: rgba(20,184,166,0.1); color: #2dd4bf; border-color: #2dd4bf; }
.dark .ai-chip:hover { background: #14b8a6; color: white; }

.ai-chat-footer { padding: 0.75rem; border-top: 1px solid #e2e8f0; background: #fff; flex-shrink: 0; }
.dark .ai-chat-footer { background: #1e293b; border-color: #334155; }

.ai-input-wrapper {
    display: flex; align-items: flex-end; gap: 0.5rem;
    background: #f1f5f9; border: 1px solid #e2e8f0;
    border-radius: 0.875rem; padding: 0.5rem 0.5rem 0.5rem 0.75rem;
    transition: border-color 0.2s, box-shadow 0.2s;
}
.dark .ai-input-wrapper { background: #0f172a; border-color: #334155; }
.ai-input-wrapper:focus-within { border-color: #14b8a6; box-shadow: 0 0 0 3px rgba(20,184,166,0.15); }

.ai-textarea { flex: 1; resize: none; border: none; outline: none; background: transparent; font-size: 0.8125rem; color: #1e293b; line-height: 1.5; max-height: 80px; font-family: inherit; padding: 0; }
.dark .ai-textarea { color: #f1f5f9; }
.ai-textarea::placeholder { color: #94a3b8; }

.ai-send-btn {
    width: 2rem; height: 2rem; border-radius: 0.625rem;
    background: linear-gradient(135deg, #14b8a6, #0d9488);
    color: white; display: flex; align-items: center; justify-content: center;
    border: none; cursor: pointer; transition: all 0.2s; flex-shrink: 0;
}
.ai-send-btn:hover:not(:disabled) { transform: scale(1.08); box-shadow: 0 4px 12px rgba(20,184,166,0.4); }
.ai-send-btn:disabled { opacity: 0.4; cursor: not-allowed; }

.ai-fab {
    width: 3.25rem; height: 3.25rem; border-radius: 999px;
    background: linear-gradient(135deg, #14b8a6, #0d9488);
    color: white; border: none; cursor: pointer;
    display: flex; align-items: center; justify-content: center;
    box-shadow: 0 8px 24px rgba(20,184,166,0.45);
    transition: transform 0.2s, box-shadow 0.2s; position: relative;
}
.ai-fab:hover { transform: scale(1.08) translateY(-2px); box-shadow: 0 12px 32px rgba(20,184,166,0.55); }
.ai-fab:active { transform: scale(0.96); }
.ai-fab-icon { display: flex; align-items: center; justify-content: center; position: relative; }
.ai-fab-pulse { position: absolute; inset: -8px; border-radius: 999px; border: 2px solid rgba(20,184,166,0.4); animation: ai-pulse-ring 2s ease-out infinite; }
@keyframes ai-pulse-ring { 0%{transform:scale(0.85);opacity:1} 70%{transform:scale(1.2);opacity:0} 100%{opacity:0} }

@media (max-width: 480px) {
    .ai-chat-window { width: calc(100vw - 2rem); max-height: calc(100vh - 5rem); }
}
</style>