<?php
require_once 'includes/auth.php';
require_once 'includes/header.php';
?>

<div x-data="chatsTable()" class="space-y-6">
    
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <h3 class="text-3xl font-medium text-gray-100">Live Conversations</h3>
        <div class="flex items-center gap-2 text-sm text-gray-400">
            <span class="w-3 h-3 bg-green-500 rounded-full animate-pulse"></span>
            Realtime Monitoring Active
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-surface p-4 rounded-xl border border-gray-700 flex flex-wrap items-center gap-4">
        <div class="relative flex-1 min-w-[200px]">
            <i class="fas fa-search absolute left-3 top-3 text-gray-500"></i>
            <input x-model="search" @input.debounce.300ms="fetchChats()" type="text" placeholder="Search participants..." class="w-full bg-dark border border-gray-600 rounded-lg pl-10 pr-4 py-2 text-gray-300 focus:outline-none focus:border-primary">
        </div>
        <button @click="fetchChats()" class="p-2 bg-dark rounded hover:bg-gray-600 text-gray-400 transition-colors" title="Refresh">
            <i class="fas fa-sync-alt" :class="{'fa-spin': loading}"></i>
        </button>
    </div>

    <!-- Conversations List -->
    <div class="grid grid-cols-1 gap-4">
        <template x-for="chat in chats" :key="chat.id">
            <div class="bg-surface rounded-xl p-4 border border-gray-700 hover:border-primary/50 transition-all cursor-pointer group"
                @click="window.location.href = 'chat_detail.php?id=' + chat.id">
                
                <div class="flex items-center justify-between mb-3">
                    <div class="text-xs text-gray-500 font-mono" x-text="'ID: ' + chat.id"></div>
                    <div class="flex items-center gap-3">
                        <div class="text-[10px] px-2 py-1 rounded-full border"
                             :class="chat.is_anonymous ? 'bg-primary/10 text-primary border-primary/30' : 'bg-emerald-500/10 text-emerald-400 border-emerald-500/30'">
                            <span class="font-bold uppercase tracking-wide" x-text="chat.is_anonymous ? 'Anon' : 'Real'"></span>
                        </div>
                        <div class="text-xs text-gray-400 flex items-center gap-2">
                            <i class="far fa-clock"></i>
                            <span x-text="formatDate(chat.last_message_at)"></span>
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-between gap-4">
                    
                    <!-- User A -->
                    <div class="flex items-center gap-3 flex-1">
                        <div class="relative">
                            <img :src="chat.sender_avatar_url || 'https://ui-avatars.com/api/?name='+chat.sender_real_name" class="w-10 h-10 rounded-full border border-gray-600">
                            <div x-show="chat.sender_is_bot == 1" class="absolute -bottom-1 -right-1 bg-secondary text-white text-[8px] px-1 rounded-full font-bold">AI</div>
                        </div>
                        <div class="overflow-hidden">
                            <div class="font-medium text-white truncate" x-text="chat.sender_real_name"></div>
                            <div class="text-xs text-gray-500">Participant A</div>
                            <div x-show="chat.is_anonymous && chat.anonymous_participant_id == chat.user_a_id" class="text-[10px] text-primary mt-0.5">
                                Alias: <span x-text="chat.display_alias"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Connection Line -->
                    <div class="flex flex-col items-center px-4">
                        <div class="h-[1px] w-12 bg-gray-600 mb-1"></div>
                        <i class="fas fa-exchange-alt text-gray-500 text-xs"></i>
                        <span x-show="chat.is_anonymous" class="text-[9px] bg-primary/20 text-primary px-1 rounded mt-1">ANON</span>
                        <div x-show="chat.is_anonymous" class="text-[10px] text-gray-400 mt-1 text-center">
                            <span x-text="anonRealName(chat)"></span>
                            <span class="text-gray-500" x-show="chat.display_alias">(<span class="text-primary">Alias:</span> <span x-text="chat.display_alias"></span>)</span>
                        </div>
                    </div>

                    <!-- User B -->
                    <div class="flex items-center gap-3 flex-1 justify-end text-right">
                        <div class="overflow-hidden">
                            <div class="font-medium text-white truncate" x-text="chat.receiver_real_name"></div>
                            <div class="text-xs text-gray-500">Participant B</div>
                            <div x-show="chat.is_anonymous && chat.anonymous_participant_id == chat.user_b_id" class="text-[10px] text-primary mt-0.5">
                                Alias: <span x-text="chat.display_alias"></span>
                            </div>
                        </div>
                        <div class="relative">
                            <img :src="chat.receiver_avatar_url || 'https://ui-avatars.com/api/?name='+chat.receiver_real_name" class="w-10 h-10 rounded-full border border-gray-600">
                            <div x-show="chat.receiver_is_bot == 1" class="absolute -bottom-1 -right-1 bg-secondary text-white text-[8px] px-1 rounded-full font-bold">AI</div>
                        </div>
                    </div>
                </div>

                <!-- Last Message Preview -->
                <div class="mt-4 pt-3 border-t border-gray-700/50">
                    <div class="flex items-start gap-2 text-sm text-gray-300">
                        <i class="fas fa-quote-left text-gray-600 text-xs mt-1"></i>
                        <p class="line-clamp-2">
                            <span x-show="chat.last_msg_is_anon" class="text-primary font-bold mr-1" x-text="chat.last_msg_alias + ':'"></span>
                            <span x-text="chat.last_message_text || 'No messages yet'"></span>
                        </p>
                    </div>
                </div>
                
                <!-- Hover Actions -->
                <div class="mt-3 flex justify-end opacity-0 group-hover:opacity-100 transition-opacity">
                    <button class="text-xs bg-primary/20 text-primary px-3 py-1 rounded hover:bg-primary hover:text-white transition-colors">
                        Monitor Chat <i class="fas fa-arrow-right ml-1"></i>
                    </button>
                </div>

            </div>
        </template>
        
        <!-- Loading -->
        <div x-show="loading" class="text-center py-12">
             <i class="fas fa-circle-notch fa-spin fa-2x text-primary mb-3"></i>
             <p class="text-gray-400">Loading conversations...</p>
        </div>
    </div>
    
    <!-- Pagination -->
    <div class="flex justify-center mt-8">
        <button @click="loadMore()" class="px-6 py-2 bg-dark border border-gray-600 rounded-full text-sm text-gray-300 hover:bg-gray-700 transition-colors">
            Load More
        </button>
    </div>

</div>

<script>
function chatsTable() {
    return {
        chats: [],
        loading: false,
        search: '',
        page: 1,

        anonRealName(chat) {
            if (!chat || !chat.is_anonymous) return '';
            if (chat.anonymous_participant_id == chat.user_a_id) return chat.sender_real_name;
            if (chat.anonymous_participant_id == chat.user_b_id) return chat.receiver_real_name;
            return '';
        },
        
        init() {
            this.fetchChats();
            setInterval(() => this.fetchChats(true), 10000); // Live update
        },
        
        fetchChats(silent = false) {
            if (!silent) this.loading = true;
            
            fetch('/backend-php/public/api/admin/conversations?limit=20')
                .then(res => res.json())
                .then(data => {
                    this.chats = data;
                    if (!silent) this.loading = false;
                });
        },
        
        formatDate(dateStr) {
            if (!dateStr) return 'Just now';
            const date = new Date(dateStr);
            const now = new Date();
            const diff = (now - date) / 1000; // seconds
            
            if (diff < 60) return 'Just now';
            if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
            if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
            return date.toLocaleDateString();
        }
    }
}
</script>

<?php require_once 'includes/footer.php'; ?>
