@extends('layouts.developer')

@section('title', 'Chat with ' . ($session->tenant->name ?? 'Tenant'))

@section('content')
<div class="container mx-auto px-4 py-6">
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center gap-4">
            <a href="{{ route('developer.chat.index') }}" class="p-2 bg-white border border-gray-200 rounded-lg text-gray-500 hover:text-purple-600 transition shadow-sm">
                <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" d="M15 19l-7-7 7-7"></path>
                </svg>
            </a>
            <div>
                <h1 class="text-xl font-bold text-gray-900">Chat with {{ $session->tenant->name ?? 'Unknown Tenant' }}</h1>
                <p class="text-xs text-gray-500">Session ID: #{{ $session->id }} • Started {{ $session->created_at->diffForHumans() }}</p>
            </div>
        </div>
        <div class="flex items-center gap-2">
            @if($session->status === 'active')
                <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-xs font-bold uppercase tracking-wider">Active</span>
                <form method="POST" action="{{ route('developer.chat.close', $session->id) }}" onsubmit="return confirm('Close this session?')">
                    @csrf
                    <button type="submit" class="px-4 py-2 bg-red-50 text-red-600 border border-red-100 rounded-lg hover:bg-red-100 transition text-sm font-medium">
                        Close Session
                    </button>
                </form>
            @else
                <span class="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-xs font-bold uppercase tracking-wider">Closed</span>
            @endif
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 h-[calc(100vh-250px)]">
        <!-- Sidebar: Session Info -->
        <div class="lg:col-span-1 space-y-6 overflow-y-auto pr-2">
            <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6">
                <h3 class="font-bold text-gray-900 mb-4 flex items-center gap-2">
                    🏢 Tenant Information
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-[10px] font-bold text-gray-400 uppercase">Name</label>
                        <p class="text-sm font-medium text-gray-900">{{ $session->tenant->name ?? 'N/A' }}</p>
                    </div>
                    <div>
                        <label class="text-[10px] font-bold text-gray-400 uppercase">Domain</label>
                        <p class="text-sm text-purple-600 font-mono">{{ $session->tenant->domain ?? 'N/A' }}</p>
                    </div>
                    <div>
                        <label class="text-[10px] font-bold text-gray-400 uppercase">Plan</label>
                        <p class="text-sm text-gray-700">{{ $session->tenant->plan_name ?? 'Basic Plan' }}</p>
                    </div>
                </div>
                <div class="mt-6 pt-6 border-t border-gray-50">
                    <a href="{{ route('developer.tenants.activity', $session->tenant_id) }}" class="text-xs text-purple-600 hover:underline font-medium">
                        View Tenant Activity →
                    </a>
                </div>
            </div>

            <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-6">
                <h3 class="font-bold text-gray-900 mb-4 flex items-center gap-2">
                    ⚙️ Chat Controls
                </h3>
                <div class="space-y-2">
                    <button onclick="window.location.reload()" class="w-full py-2 bg-gray-50 text-gray-700 rounded-lg hover:bg-gray-100 transition text-xs font-medium">
                        🔄 Refresh Messages
                    </button>
                </div>
            </div>
        </div>

        <!-- Main Chat Area -->
        <div class="lg:col-span-2 flex flex-col bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
            <!-- Messages container -->
            <div id="messagesContainer" class="flex-1 overflow-y-auto p-6 space-y-6 bg-gray-50/50">
                @forelse($session->messages as $message)
                    <div class="flex {{ $message->sender_type === 'admin' ? 'justify-end' : 'justify-start' }}">
                        <div class="max-w-[80%]">
                            <div class="flex items-center gap-2 mb-1 {{ $message->sender_type === 'admin' ? 'flex-row-reverse' : '' }}">
                                <span class="text-[10px] font-bold text-gray-400 uppercase">
                                    {{ $message->sender_type === 'admin' ? 'Developer' : 'Tenant' }}
                                </span>
                                <span class="text-[10px] text-gray-400">
                                    {{ $message->created_at->format('H:i') }}
                                </span>
                            </div>
                            <div class="px-4 py-3 rounded-2xl text-sm shadow-sm {{ $message->sender_type === 'admin' ? 'bg-purple-600 text-white rounded-tr-none' : 'bg-white text-gray-800 border border-gray-100 rounded-tl-none' }}">
                                {{ $message->message }}
                            </div>
                            @if($message->sender_type === 'admin')
                                <div class="text-[10px] mt-1 text-right {{ $message->is_read ? 'text-purple-500' : 'text-gray-400' }}">
                                    {{ $message->is_read ? 'Read ✓✓' : 'Sent ✓' }}
                                </div>
                            @endif
                        </div>
                    </div>
                @empty
                    <div class="h-full flex flex-col items-center justify-center text-center opacity-50">
                        <span class="text-4xl mb-2">📭</span>
                        <p class="text-sm">No messages yet in this session.</p>
                    </div>
                @endforelse
            </div>

            <!-- Input area -->
            @if($session->status === 'active')
            <div class="p-4 bg-white border-t border-gray-100">
                <form id="chatForm" class="flex gap-2">
                    @csrf
                    <input type="text" id="messageInput" placeholder="Type your response here..." 
                           class="flex-1 bg-gray-50 border-gray-200 rounded-xl px-4 py-2 focus:ring-purple-500 focus:border-purple-500 text-sm">
                    <button type="submit" class="px-6 py-2 bg-purple-600 text-white rounded-xl hover:bg-purple-700 transition font-bold text-sm flex items-center gap-2">
                        Send <span>🚀</span>
                    </button>
                </form>
            </div>
            @endif
        </div>
    </div>
</div>

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const messagesContainer = document.getElementById('messagesContainer');
        const chatForm = document.getElementById('chatForm');
        const messageInput = document.getElementById('messageInput');

        // Scroll to bottom
        messagesContainer.scrollTop = messagesContainer.scrollHeight;

        if (chatForm) {
            chatForm.addEventListener('submit', async function(e) {
                e.preventDefault();
                const message = messageInput.value.trim();
                if (!message) return;

                try {
                    const response = await fetch('{{ route("developer.chat.send", $session->id) }}', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}'
                        },
                        body: JSON.stringify({ message })
                    });

                    const data = await response.json();
                    if (data.success) {
                        messageInput.value = '';
                        window.location.reload(); // Simple refresh for now
                    }
                } catch (error) {
                    console.error('Error sending message:', error);
                    alert('Failed to send message. Please try again.');
                }
            });
        }
    });
</script>
@endpush
@endsection
