@extends('layouts.app')

@php $header_title = 'مركز الرسائل المباشرة'; @endphp

@section('content')
<!-- Main Container with Explicit Styles -->
<div class="chat-main-container" style="margin-top: 1.5rem; height: calc(100vh - 200px); display: flex; background-color: #0a0a0a; border-radius: 40px !important; overflow: hidden !important; border: 1px solid rgba(255,255,255,0.05); shadow: 0 50px 100px rgba(0,0,0,0.8); position: relative;">
    
    <!-- Sidebar: Conversations List -->
    <div class="w-96 border-l border-white/5 flex flex-col bg-[#0f0f0f]">
        <div class="p-8 border-b border-white/5">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-black text-white tracking-tight">المحادثات</h3>
                <div class="flex items-center gap-2 px-3 py-1 bg-[#d4af37]/10 rounded-full border border-[#d4af37]/20">
                    <span class="w-1.5 h-1.5 bg-[#d4af37] rounded-full animate-pulse"></span>
                    <span class="text-[10px] text-[#d4af37] font-black uppercase tracking-widest">Live</span>
                </div>
            </div>
            
            <div class="relative group">
                <input type="text" id="conv-search" placeholder="بحث سريع..." class="w-full bg-black/40 border border-white/5 rounded-[20px] px-12 py-4 text-sm text-white focus:border-[#d4af37] transition-all outline-none font-medium">
                <svg class="w-5 h-5 text-gray-600 absolute left-4 top-1/2 -translate-y-1/2 group-focus-within:text-[#d4af37] transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"></path></svg>
            </div>
        </div>
        
        <div class="flex-grow overflow-y-auto custom-scrollbar px-4 py-4" id="conversations-list">
            @forelse($conversations as $conv)
            <div onclick="loadConversation({{ $conv->id }})" id="conv-{{ $conv->id }}" class="conv-item relative p-5 mb-2 rounded-[25px] cursor-pointer hover:bg-white/5 transition-all flex items-center gap-4 group">
                <div class="relative shrink-0">
                    <div class="w-12 h-12 rounded-[18px] bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] border border-white/10 flex items-center justify-center text-[#d4af37] font-black shadow-lg">
                        {{ $conv->customer ? substr($conv->customer->name, 0, 1) : 'G' }}
                    </div>
                    @if($conv->unreadCount() > 0)
                    <div class="absolute -top-1 -right-1 w-5 h-5 bg-[#d4af37] text-black text-[9px] font-black flex items-center justify-center rounded-full border-2 border-[#0f0f0f] shadow-lg">{{ $conv->unreadCount() }}</div>
                    @endif
                </div>
                
                <div class="flex-grow overflow-hidden">
                    <div class="flex justify-between items-center mb-0.5">
                        <h4 class="text-sm font-bold text-white truncate group-hover:text-[#d4af37] transition-colors">
                            {{ $conv->customer ? $conv->customer->name : 'زائر (G-' . substr($conv->session_id, 0, 4) . ')' }}
                        </h4>
                        <span class="text-[9px] text-gray-600 font-bold whitespace-nowrap">{{ $conv->last_message_at ? $conv->last_message_at->diffForHumans(null, true) : '' }}</span>
                    </div>
                    <p class="text-[11px] text-gray-500 truncate group-hover:text-gray-300 transition-colors">
                        {{ $conv->lastMessage ? $conv->lastMessage->message : 'ابدأ المحادثة...' }}
                    </p>
                </div>
                <div class="active-indicator absolute right-1 top-1/2 -translate-y-1/2 w-1 h-6 bg-[#d4af37] rounded-full opacity-0 transition-all scale-y-0"></div>
            </div>
            @empty
            <div class="p-10 text-center text-gray-700 text-xs font-bold">لا توجد محادثات</div>
            @endforelse
        </div>
    </div>

    <!-- Main Chat Area -->
    <div id="chat-container" class="flex-grow flex flex-col bg-[#050505] relative">
        
        <!-- Welcome Screen -->
        <div id="no-chat-selected" class="absolute inset-0 flex flex-col items-center justify-center text-center p-12">
            <div class="w-24 h-24 bg-white/5 rounded-[35px] flex items-center justify-center mb-6">
                <svg class="w-10 h-10 text-[#d4af37] opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path 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" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
            </div>
            <h2 class="text-xl font-black text-white mb-2">مركز الدعم الفني المباشر</h2>
            <p class="text-gray-600 text-xs font-medium">اختر محادثة من القائمة للبدء في الرد على العملاء</p>
        </div>

        <!-- Chat Content -->
        <div id="chat-active" class="hidden h-full flex flex-col">
            <!-- Chat Header -->
            <div class="px-10 py-6 bg-[#0a0a0a]/90 backdrop-blur-md flex justify-between items-center border-b border-white/5">
                <div class="flex items-center gap-5">
                    <div id="active-user-avatar" class="w-12 h-12 rounded-[18px] bg-gradient-to-br from-[#d4af37] to-[#f9d976] flex items-center justify-center text-black font-black shadow-lg"></div>
                    <div>
                        <h4 id="active-user-name" class="text-white font-black"></h4>
                        <div class="flex items-center gap-2 mt-0.5">
                            <span class="w-1.5 h-1.5 bg-green-500 rounded-full"></span>
                            <span class="text-[9px] text-gray-500 font-black uppercase tracking-widest">نشط الآن</span>
                        </div>
                    </div>
                </div>
                <button onclick="closeChat()" class="p-3 bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white rounded-[15px] transition-all border border-red-500/20">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>

            <!-- Messages List -->
            <div id="admin-chat-messages" class="flex-grow overflow-y-auto px-10 py-8 space-y-6 custom-scrollbar bg-transparent flex flex-col">
                <!-- Messages will appear here -->
            </div>

            <!-- Input Box -->
            <div class="p-8 bg-[#0a0a0a]/90 border-t border-white/5">
                <form id="admin-chat-form" class="flex gap-4 items-end max-w-5xl mx-auto">
                    <div class="flex-grow bg-black/40 border border-white/10 rounded-[28px] p-2 flex items-center gap-2 focus-within:border-[#d4af37]/40 transition-all shadow-xl">
                        <label class="cursor-pointer text-gray-500 hover:text-[#d4af37] p-3 rounded-xl transition-all shrink-0">
                            <input type="file" id="admin-chat-attachment" class="hidden" accept="image/*">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path></svg>
                        </label>
                        <textarea id="admin-chat-input" rows="1" placeholder="اكتب رسالتك..." class="bg-transparent border-none focus:ring-0 text-white text-sm w-full py-3 resize-none custom-scrollbar min-h-[45px] max-h-[150px]" oninput="this.style.height = '';this.style.height = this.scrollHeight + 'px'"></textarea>
                        <button type="submit" class="h-12 w-12 bg-[#d4af37] text-black rounded-[20px] hover:scale-105 active:scale-95 transition-all flex items-center justify-center shadow-lg shadow-[#d4af37]/20 shrink-0">
                            <svg class="w-6 h-6 transform rotate-180" fill="currentColor" viewBox="0 0 20 20"><path d="M10.894 2.553a1 1 0 00-1.788 0l-7 14a1 1 0 001.169 1.409l5-1.429A1 1 0 009 15.571V11a1 1 0 112 0v4.571a1 1 0 00.725.962l5 1.428a1 1 0 001.17-1.408l-7-14z"></path></svg>
                        </button>
                    </div>
                </form>
                <div id="file-preview" class="hidden mt-3 mr-12 px-4 py-2 bg-[#d4af37]/10 text-[#d4af37] text-[10px] font-black rounded-full inline-flex items-center gap-2 border border-[#d4af37]/20">
                    <span id="file-name"></span>
                    <button onclick="clearFile()" class="text-red-500">✕</button>
                </div>
            </div>
        </div>
    </div>
</div>

@push('styles')
<style>
    .custom-scrollbar::-webkit-scrollbar { width: 3px; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(212, 175, 55, 0.2); border-radius: 10px; }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #d4af37; }
    
    .conv-item.active { background: rgba(212, 175, 55, 0.08); border: 1px solid rgba(212, 175, 55, 0.1); }
    .conv-item.active .active-indicator { opacity: 1; scale: 1; }
    
    .bubble-admin { 
        background-color: #d4af37; 
        color: #000; 
        border-radius: 25px; 
        border-bottom-right-radius: 5px; 
        box-shadow: 0 8px 25px rgba(212, 175, 55, 0.15);
    }
    .bubble-customer { 
        background-color: #1a1a1a; 
        color: #eee; 
        border-radius: 25px; 
        border-bottom-left-radius: 5px; 
        border: 1px solid rgba(255,255,255,0.05);
    }
    
    .message-anim {
        animation: messageFadeIn 0.3s ease-out forwards;
    }
    @keyframes messageFadeIn {
        from { opacity: 0; transform: translateY(15px); }
        to { opacity: 1; transform: translateY(0); }
    }
</style>
@endpush

@push('scripts')
<script>
    let currentConversationId = null;
    let pollingInterval = null;
    let lastMsgCount = 0;

    async function loadConversation(id) {
        if (currentConversationId === id) return;
        currentConversationId = id;
        lastMsgCount = 0;
        
        document.getElementById('no-chat-selected').classList.add('hidden');
        document.getElementById('chat-active').classList.remove('hidden');
        
        document.querySelectorAll('.conv-item').forEach(el => el.classList.remove('active'));
        document.getElementById(`conv-${id}`).classList.add('active');
        
        const response = await fetch(`/admin/chat/${id}`);
        const data = await response.json();
        
        const name = data.conversation.customer ? data.conversation.customer.name : 'زائر (G-' + data.conversation.session_id.substring(0,4) + ')';
        document.getElementById('active-user-name').innerText = name;
        document.getElementById('active-user-avatar').innerText = name[0].toUpperCase();
        
        renderMessages(data.messages);
        lastMsgCount = data.messages.length;
        
        if (pollingInterval) clearInterval(pollingInterval);
        pollingInterval = setInterval(() => fetchNewMessages(id), 5000);
    }

    function renderMessages(messages) {
        const container = document.getElementById('admin-chat-messages');
        container.innerHTML = '';
        
        messages.forEach(msg => {
            const isAdmin = msg.sender_type === 'admin';
            const div = document.createElement('div');
            // In RTL: justify-start = Right (Admin), justify-end = Left (Customer)
            div.className = `flex ${isAdmin ? 'justify-start' : 'justify-end'} w-full message-anim`;
            
            let content = `
                <div class="flex flex-col ${isAdmin ? 'items-start' : 'items-end'} max-w-[70%]">
                    <div class="p-5 ${isAdmin ? 'bubble-admin' : 'bubble-customer'} transition-all">
            `;
            
            if (msg.attachment) {
                content += `<img src="${msg.attachment}" class="rounded-xl mb-3 max-w-full shadow-md cursor-pointer" onclick="window.open('${msg.attachment}')">`;
            }
            
            if (msg.message) {
                content += `<p class="leading-relaxed text-[13px] font-bold whitespace-pre-wrap">${msg.message}</p>`;
            }
            
            content += `
                    </div>
                    <span class="text-[9px] text-gray-600 font-black mt-2 uppercase tracking-widest px-2">${msg.created_at} ${isAdmin ? '• مرسل' : ''}</span>
                </div>
            `;
            
            div.innerHTML = content;
            container.appendChild(div);
        });
        
        container.scrollTop = container.scrollHeight;
    }

    async function fetchNewMessages(id) {
        if (id !== currentConversationId) return;
        try {
            const response = await fetch(`/admin/chat/${id}`);
            const data = await response.json();
            if (data.messages.length !== lastMsgCount) {
                renderMessages(data.messages);
                lastMsgCount = data.messages.length;
            }
        } catch (e) { console.error(e); }
    }

    document.getElementById('admin-chat-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        if (!currentConversationId) return;

        const input = document.getElementById('admin-chat-input');
        const fileInput = document.getElementById('admin-chat-attachment');
        const message = input.value.trim();
        const file = fileInput.files[0];

        if (!message && !file) return;

        const formData = new FormData();
        if (message) formData.append('message', message);
        if (file) formData.append('attachment', file);
        formData.append('_token', '{{ csrf_token() }}');

        input.value = '';
        input.style.height = '';
        clearFile();

        const response = await fetch(`/admin/chat/${currentConversationId}/reply`, {
            method: 'POST',
            body: formData
        });
        
        fetchNewMessages(currentConversationId);
    });

    document.getElementById('admin-chat-attachment').addEventListener('change', function() {
        const preview = document.getElementById('file-preview');
        const name = document.getElementById('file-name');
        if (this.files[0]) {
            name.innerText = this.files[0].name;
            preview.classList.remove('hidden');
        }
    });

    function clearFile() {
        document.getElementById('admin-chat-attachment').value = '';
        document.getElementById('file-preview').classList.add('hidden');
    }

    function closeChat() {
        currentConversationId = null;
        if (pollingInterval) clearInterval(pollingInterval);
        document.getElementById('chat-active').classList.add('hidden');
        document.getElementById('no-chat-selected').classList.remove('hidden');
        document.querySelectorAll('.conv-item').forEach(el => el.classList.remove('active'));
    }

    document.getElementById('conv-search').addEventListener('input', function(e) {
        const q = e.target.value.toLowerCase();
        document.querySelectorAll('.conv-item').forEach(el => {
            const name = el.querySelector('h4').innerText.toLowerCase();
            el.style.display = name.includes(q) ? 'flex' : 'none';
        });
    });
</script>
@endpush
@endsection
