<script setup>
/**
 * Coach Chat - Instagram DM Style
 * Modern real-time messaging interface for coach-client communication
 */
import CoachLayout from '@/Layouts/CoachLayout.vue';
import ChatWindow from '@/Components/ChatWindow.vue';
import { Head, Link, router, usePage } from '@inertiajs/vue3';
import { ref, computed } from 'vue';

const props = defineProps({
    clients: Array,
    messages: Array,
    selectedUser: Object,
});

const page = usePage();
const coachId = computed(() => page.props.auth.user.id);

const selectedClientId = computed(() => {
    if (!props.selectedUser) return null;
    const client = props.clients.find(c => c.user_id === props.selectedUser.id);
    return client?.id || null;
});

// Check if selected user is admin
const isAdminChat = computed(() => {
    if (!props.selectedUser) return false;
    const contact = props.clients.find(c => c.user_id === props.selectedUser.id || c.id === 'admin');
    return contact?.id === 'admin';
});

const selectedAdminId = computed(() => {
    return isAdminChat.value ? props.selectedUser?.id : null;
});

const searchQuery = ref('');
const mobileShowChat = ref(!!props.selectedUser);

const filteredClients = computed(() => {
    if (!searchQuery.value) return props.clients;
    const q = searchQuery.value.toLowerCase();
    return props.clients.filter(c => c.name.toLowerCase().includes(q));
});

const getInitials = (name) => {
    if (!name) return '?';
    return name.split(' ').map(w => w.charAt(0)).slice(0, 2).join('').toUpperCase();
};

const selectClient = (userId) => {
    mobileShowChat.value = true;
    router.get(route('coach.chat.index', { user: userId }), {}, { preserveState: true });
};

const backToList = () => {
    mobileShowChat.value = false;
};
</script>

<template>
    <Head title="Mensajes" />

    <CoachLayout>
        <template #header>
            <div class="hidden lg:flex items-center gap-3">
                <div class="p-2 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl">
                    <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /></svg>
                </div>
                <div>
                    <h2 class="text-[15px] font-bold text-gray-900 dark:text-white">Mensajes</h2>
                    <p class="text-xs text-gray-500 dark:text-gray-400">Chatea con tus clientes</p>
                </div>
            </div>
        </template>

        <!-- Full-screen native chat on mobile, contained on desktop -->
        <div class="-mx-4 -mt-4 -mb-24 sm:-mx-6 sm:-mt-6 lg:mx-0 lg:mt-0 lg:mb-0 h-[calc(100dvh-56px-64px)] lg:h-[calc(100vh-140px)]">
            <div class="h-full lg:mx-auto lg:max-w-7xl lg:px-4 lg:py-2">
                <div class="flex h-full bg-white dark:bg-gray-900 lg:rounded-2xl lg:shadow-xl lg:border lg:border-gray-200/60 lg:dark:border-gray-800 overflow-hidden">

                    <!-- Sidebar - Contact List -->
                    <div
                        :class="[
                            'w-full lg:w-[340px] xl:w-[380px] flex-shrink-0 lg:border-r border-gray-100 dark:border-gray-800 flex flex-col bg-white dark:bg-gray-900',
                            mobileShowChat ? 'hidden lg:flex' : 'flex'
                        ]"
                    >
                        <!-- Mobile header for contacts list -->
                        <div class="lg:hidden flex items-center gap-3 px-4 py-3 border-b border-gray-100 dark:border-gray-800">
                            <div class="p-2 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl">
                                <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /></svg>
                            </div>
                            <div>
                                <h2 class="text-[15px] font-bold text-gray-900 dark:text-white">Mensajes</h2>
                                <p class="text-xs text-gray-500 dark:text-gray-400">Chatea con tus clientes</p>
                            </div>
                        </div>

                        <!-- Search -->
                        <div class="px-4 pt-3 pb-2">
                            <div class="relative">
                                <svg class="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
                                <input
                                    v-model="searchQuery"
                                    type="text"
                                    placeholder="Buscar clientes..."
                                    class="w-full pl-10 pr-4 py-2.5 bg-gray-100 dark:bg-gray-800 border-0 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:bg-white dark:focus:bg-gray-700 dark:text-white placeholder-gray-400 transition-all"
                                >
                            </div>
                        </div>

                        <!-- Contacts -->
                        <div class="flex-1 overflow-y-auto">
                            <div
                                v-for="client in filteredClients"
                                :key="client.id"
                                @click="selectClient(client.user_id)"
                                :class="[
                                    'flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors mx-2 rounded-xl mb-0.5',
                                    selectedUser?.id == client.user_id
                                        ? 'bg-blue-50 dark:bg-blue-950/30'
                                        : 'hover:bg-gray-50 dark:hover:bg-gray-800/50'
                                ]"
                            >
                                <div class="relative flex-shrink-0">
                                    <div class="w-12 h-12 rounded-full overflow-hidden">
                                        <img v-if="client.avatar_url" :src="client.avatar_url" :alt="client.name" class="w-full h-full object-cover" @error="$event.target.style.display='none'" loading="lazy">
                                        <div v-else class="w-full h-full bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center text-white font-semibold text-sm">
                                            {{ getInitials(client.name) }}
                                        </div>
                                    </div>
                                    <span class="absolute bottom-0 right-0 w-3 h-3 bg-emerald-400 border-2 border-white dark:border-gray-900 rounded-full"></span>
                                </div>
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center justify-between">
                                        <h4 class="text-sm font-semibold text-gray-900 dark:text-white truncate">{{ client.name }}</h4>
                                    </div>
                                    <p class="text-xs text-gray-500 dark:text-gray-400 truncate">Toca para chatear</p>
                                </div>
                                <div v-if="client.has_unread" class="flex-shrink-0">
                                    <span class="w-5 h-5 bg-blue-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center">!</span>
                                </div>
                            </div>

                            <div v-if="!filteredClients.length" class="p-8 text-center">
                                <div class="w-16 h-16 mx-auto mb-3 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center">
                                    <svg class="w-7 h-7 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
                                </div>
                                <p class="text-sm text-gray-500 dark:text-gray-400">
                                    {{ searchQuery ? 'No se encontraron clientes' : 'Tus clientes con acceso al portal aparecerán aquí' }}
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Chat Area -->
                    <div
                        :class="[
                            'flex-1 flex flex-col min-w-0',
                            !mobileShowChat ? 'hidden lg:flex' : 'flex'
                        ]"
                    >
                        <ChatWindow
                            v-if="selectedUser"
                            :receiver-id="selectedUser.id"
                            :receiver-name="selectedUser.name"
                            :receiver-avatar="selectedUser.avatar_url"
                            :messages="messages"
                            :sender-id="$page.props.auth.user.id"
                            :sender-name="$page.props.auth.user.name"
                            :sender-avatar="$page.props.auth.user.avatar_url"
                            :store-route="route('coach.chat.store')"
                            :coach-id="isAdminChat ? coachId : coachId"
                            :client-id="!isAdminChat ? selectedClientId : null"
                            :admin-id="isAdminChat ? selectedAdminId : null"
                            :show-header="true"
                            :show-back-button="true"
                            @back="backToList"
                            class="flex-1"
                        />

                        <!-- Empty State -->
                        <div v-else class="flex-1 flex flex-col items-center justify-center bg-gray-50/50 dark:bg-gray-900">
                            <div class="w-24 h-24 mb-5 bg-gradient-to-br from-blue-100 to-indigo-100 dark:from-blue-900/30 dark:to-indigo-900/30 rounded-full flex items-center justify-center">
                                <svg class="w-10 h-10 text-blue-500 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" /></svg>
                            </div>
                            <h3 class="text-xl font-bold text-gray-900 dark:text-white mb-1">Tus mensajes</h3>
                            <p class="text-sm text-gray-500 dark:text-gray-400 text-center max-w-xs">Selecciona un cliente de la lista para comenzar a chatear.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </CoachLayout>
</template>
