@extends('layouts.app')

@section('title', $page->title)
@section('meta_description', $page->meta_description)
@section('meta_keywords', $page->meta_keywords)

@section('content')

    <!-- Main Content -->
<div class="mx-auto">
        
        <!-- Breadcrumb -->
        <nav class="flex mb-6 text-sm text-gray-400" aria-label="Breadcrumb">
            <ol class="inline-flex items-center space-x-1 md:space-x-3">
                <li class="inline-flex items-center">
                    <a href="{{ route('home') }}" class="inline-flex items-center hover:text-white">
                        <svg class="w-4 h-4 mr-2" fill="currentColor" viewBox="0 0 20 20"><path d="M10.707 2.293a1 1 0 00-1.414 0l-7 7a1 1 0 001.414 1.414L4 10.414V17a1 1 0 001 1h2a1 1 0 001-1v-2a1 1 0 011-1h2a1 1 0 011 1v2a1 1 0 001 1h2a1 1 0 001-1v-6.586l.293.293a1 1 0 001.414-1.414l-7-7z"></path></svg>
                        Home
                    </a>
                </li>
                <li>
                    <div class="flex items-center">
                        <svg class="w-6 h-6 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg>
                        <a href="{{ route('home') }}" class="ml-1 text-gray-400 hover:text-white md:ml-2">Live Stream</a>
                    </div>
                </li>
                <li aria-current="page">
                    <div class="flex items-center">
                        <svg class="w-6 h-6 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg>
                        <span class="ml-1 text-gray-100 md:ml-2 font-medium truncate max-w-[200px] sm:max-w-xs">{{ $homeTeam }} vs {{ $awayTeam }}</span>
                    </div>
                </li>
            </ol>
        </nav>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- Main Column: Player -->
            <div class="lg:col-span-2">
                
                <!-- Match Title -->
                <div class="flex items-center justify-between mb-4">
                    <h1 class="text-xl md:text-2xl font-bold text-white">
                        <span class="text-blue-500">{{ $homeTeam }}</span> vs <span class="text-blue-500">{{ $awayTeam }}</span>
                    </h1>
                    @if ($isLive)
                        <span class="bg-red-600 text-white text-xs font-bold px-2 py-1 rounded animate-pulse">LIVE</span>
                    @else
                        <span class="bg-gray-700 text-gray-300 text-xs font-bold px-2 py-1 rounded">{{ $time }}</span>
                    @endif
                </div>

                <!-- Video Player Container -->
                <div class="relative w-full bg-black rounded-xl overflow-hidden shadow-2xl aspect-video group">
                    
                    <!-- Pre-match Overlay -->
                    <div id="match-overlay" class="absolute inset-0 z-20 bg-gray-900 bg-opacity-95 md:bg-opacity-90 flex flex-col items-center justify-center text-center p-4 md:p-6 transition-opacity duration-500 overflow-y-auto">
                        
                        <div class="flex items-center gap-4 md:gap-12 mb-3 md:mb-8 w-full justify-center mt-auto md:mt-0">
                            <div class="flex flex-col items-center w-1/3">
                                <img src="{{ $homeBadge }}" class="w-10 h-10 md:w-24 md:h-24 object-contain mb-2 md:mb-3" onerror="this.src='https://placehold.co/100x100/374151/E5E7EB?text=H'">
                                <span class="text-[10px] md:text-lg font-bold text-white leading-tight break-words max-w-full">{{ $homeTeam }}</span>
                            </div>
                            <div class="text-base md:text-3xl font-bold text-gray-500 italic">VS</div>
                            <div class="flex flex-col items-center w-1/3">
                                <img src="{{ $awayBadge }}" class="w-10 h-10 md:w-24 md:h-24 object-contain mb-2 md:mb-3" onerror="this.src='https://placehold.co/100x100/374151/E5E7EB?text=A'">
                                <span class="text-[10px] md:text-lg font-bold text-white leading-tight break-words max-w-full">{{ $awayTeam }}</span>
                            </div>
                        </div>

                        <div class="mb-4 md:mb-10 scale-90 md:scale-100 flex flex-col items-center">
                            <div id="countdown" class="text-2xl md:text-6xl font-mono font-bold text-blue-500 mb-1 md:mb-2 tracking-widest">00:00:00</div>
                            <p class="text-gray-400 text-[10px] md:text-sm uppercase tracking-wider">Time until kickoff</p>
                        </div>

                        <button id="start-watching-btn" class="mb-auto md:mb-0 bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 md:py-3 md:px-10 rounded-full text-sm md:text-base transition-all transform hover:scale-105 active:scale-95 flex items-center gap-2 shadow-lg shadow-blue-500/30 ring-2 ring-blue-500 ring-offset-2 ring-offset-gray-900">
                            <svg class="w-5 h-5 md:w-6 md:h-6" fill="currentColor" viewBox="0 0 20 20"><path d="M6.3 2.841A1.5 1.5 0 004 4.11V15.89a1.5 1.5 0 002.3 1.269l9.344-5.89a1.5 1.5 0 000-2.538L6.3 2.84z"></path></svg>
                            Start Watching
                        </button>
                    </div>

                    <!-- Iframe -->
                    <iframe id="stream-player" src="" class="absolute inset-0 w-full h-full z-10" frameborder="0" allowfullscreen scrolling="no" allow="autoplay; encrypted-media"></iframe>
                    
                    <!-- Loading Spinner (Hidden by default) -->
                    <div id="player-loader" class="absolute inset-0 z-15 bg-black flex items-center justify-center hidden">
                        <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
                    </div>
                </div>

                <!-- Server Selection -->
                <div id="server-selection" class="mt-8 hidden">
                    <h3 class="text-gray-400 text-sm font-semibold mb-4 uppercase tracking-wider">Select Server</h3>
                    <div class="flex flex-wrap gap-4">
                        @foreach ($servers as $index => $server)
                            <button 
                                onclick="changeServer(this)" 
                                data-type="{{ $server['type'] }}"
                                data-src="{{ $server['type'] === 'iframe' ? ($server['src'] ?? '') : '' }}"
                                data-source="{{ $server['source'] ?? '' }}"
                                data-id="{{ $server['id'] ?? '' }}"
                                class="server-btn px-6 py-3 rounded-lg text-sm font-medium transition-colors {{ $index === 0 ? 'bg-blue-600 text-white shadow-lg shadow-blue-500/20' : 'bg-gray-800 text-gray-300 hover:bg-gray-700 hover:text-white' }}">
                                {{ $server['name'] }}
                            </button>
                        @endforeach
                    </div>
                    <p class="text-xs text-gray-500 mt-4 flex items-center gap-2">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                        If the stream is lagging or not working, try switching to another server.
                    </p>
                </div>

                <!-- About Match -->
                <div class="mt-8 bg-gray-800 p-8 rounded-xl shadow-lg">
                    <h2 class="text-xl font-bold text-white mb-4">About the Match</h2>
                    <p class="text-gray-400 leading-relaxed">
                        Watch the live stream of <strong>{{ $homeTeam }}</strong> vs <strong>{{ $awayTeam }}</strong>. 
                        This match is part of the ongoing season. Don't miss any of the action as these two teams clash on the field. 
                        We provide high-quality streams from multiple sources to ensure you have the best viewing experience.
                    </p>
                    <div class="mt-4 flex gap-4 text-sm text-gray-500">
                        <span>📅 {{ date('d M Y') }}</span>
                        <span>⏰ {{ $time }}</span>
                    </div>
                </div>

                
                <!-- Related / Random Posts -->
                <div class="mt-6 border-t border-gray-700 pt-6">
                     <h3 class="font-bold text-white mb-4">You might also like</h3>
                     <div class="space-y-4">
                        @foreach($randomPosts as $post)
                        <a href="{{ url('/post/' . $post->slug) }}" class="flex gap-3 group cursor-pointer bg-gray-800 p-2 rounded hover:bg-gray-750 transition-colors">
                            <div class="w-16 h-16 flex-shrink-0 overflow-hidden rounded bg-gray-700">
                                <img src="{{ $post->image ?? 'https://placehold.co/100x100/1f2937/60a5fa?text=Post' }}" class="w-full h-full object-cover group-hover:scale-110 transition-transform">
                            </div>
                            <div>
                                <h4 class="text-xs font-semibold text-gray-200 leading-snug group-hover:text-blue-400 line-clamp-2">{{ $post->title }}</h4>
                                <span class="text-[10px] text-gray-500 mt-1 block">{{ $post->created_at->format('M d, Y') }}</span>
                            </div>
                        </a>
                        @endforeach
                     </div>
                </div>

            </div>

            <!-- Right Column: Chat / Sidebar -->
            <div class="lg:col-span-1 space-y-6">
                <!-- Chat Widget -->
                <div class="bg-gray-800 rounded-xl overflow-hidden flex flex-col h-[500px]">
                    <div class="bg-gray-750 p-4 border-b border-gray-700 flex justify-between items-center">
                        <h3 class="font-bold text-white">Live Chat</h3>
                        <span class="text-xs text-green-400 flex items-center gap-1">
                            <span class="w-2 h-2 bg-green-400 rounded-full"></span> <span id="online-count">Loading...</span> Online
                        </span>
                    </div>
                    <div id="chat-messages" class="flex-grow p-4 overflow-y-auto space-y-3 scrollbar-thin scrollbar-thumb-gray-600">
                        <!-- Messages will be loaded here -->
                        <div class="text-center text-gray-500 text-sm mt-10">Connecting to chat...</div>
                    </div>
                    <div class="p-3 bg-gray-750 border-t border-gray-700">
                        <div class="flex justify-between items-center mb-2 text-xs text-gray-400">
                            <span>Posting as: <strong id="current-username" class="text-white cursor-pointer hover:text-blue-400" title="Click to change">Guest</strong></span>
                            <button id="change-name-btn" class="text-blue-500 hover:text-blue-400">Change</button>
                        </div>
                        <input id="chat-input" type="text" placeholder="Type a message..." class="w-full bg-gray-900 text-white rounded px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                    </div>
                </div>


            </div>

        </div>

    </div>


    <script>
        // Countdown Logic
        const matchTimeStr = "{{ $time }}"; // e.g. "21:00"
        const isLive = @json($isLive);
        
        // Simple parser
        const now = new Date();
        const target = new Date();
        
        // Try to parse HH:MM
        const timeParts = matchTimeStr.match(/(\d{1,2}):(\d{2})/);
        if (timeParts) {
            target.setHours(parseInt(timeParts[1]), parseInt(timeParts[2]), 0);
            
            // Should properly handle tomorrow/yesterday/timezone, but simplify for now
            // If target is earlier than now and not live, maybe it's tomorrow?
            // Actually Streami time comes with date usually, but here passed just HH:MM
            // Since controller passed 'date' in ms, maybe better inject that
        } else {
            target.setTime(now.getTime() - 1000);
        }

        const countdownEl = document.getElementById('countdown');
        const overlay = document.getElementById('match-overlay');
        const startBtn = document.getElementById('start-watching-btn');
        const serverSelection = document.getElementById('server-selection');
        const player = document.getElementById('stream-player');
        const loader = document.getElementById('player-loader');

        function updateCountdown() {
            const current = new Date();
            const diff = target - current;

            if (isLive || diff <= 0) {
                countdownEl.innerHTML = "LIVE NOW";
                countdownEl.classList.add('text-red-500', 'animate-pulse');
                countdownEl.classList.remove('text-blue-500');
                return;
            }

            const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((diff % (1000 * 60)) / 1000);

            countdownEl.innerHTML = 
                (hours < 10 ? "0" + hours : hours) + ":" +
                (minutes < 10 ? "0" + minutes : minutes) + ":" +
                (seconds < 10 ? "0" + seconds : seconds);
        }

        setInterval(updateCountdown, 1000);
        updateCountdown();

        // Start Watching
        startBtn.addEventListener('click', () => {
            overlay.classList.add('opacity-0', 'pointer-events-none');
            serverSelection.classList.remove('hidden');
            
            // Trigger load of first server if needed
            const firstServerBtn = document.querySelector('.server-btn');
            if (firstServerBtn) {
                changeServer(firstServerBtn);
            }
        });

        // Mobile Menu Toggle
        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
        const mobileMenu = document.getElementById('mobile-menu');

        if (mobileMenuBtn && mobileMenu) {
            mobileMenuBtn.addEventListener('click', () => {
                mobileMenu.classList.toggle('hidden');
            });
        }

        // Server Switching Logic
        async function changeServer(btn) {
            // UI Update
            document.querySelectorAll('.server-btn').forEach(b => {
                b.classList.remove('bg-blue-600', 'text-white', 'shadow-lg', 'shadow-blue-500/20');
                b.classList.add('bg-gray-800', 'text-gray-300');
            });
            btn.classList.remove('bg-gray-800', 'text-gray-300');
            btn.classList.add('bg-blue-600', 'text-white', 'shadow-lg', 'shadow-blue-500/20');

            const type = btn.getAttribute('data-type');
            
            if (type === 'iframe') {
                player.src = btn.getAttribute('data-src');
            } else if (type === 'streami') {
                const source = btn.getAttribute('data-source');
                const id = btn.getAttribute('data-id');
                
                // Show loader
                loader.classList.remove('hidden');
                
                try {
                    // Fetch stream URL via our Laravel proxy
                    const response = await fetch(`{{ route('api.stream') }}?source=${source}&id=${id}`);
                    const data = await response.json();
                    
                    if (data && data.length > 0 && data[0].embedUrl) {
                        player.src = data[0].embedUrl;
                    } else {
                        alert('Stream not available at the moment.');
                    }
                } catch (e) {
                    console.error(e);
                    alert('Error loading stream.');
                } finally {
                    loader.classList.add('hidden');
                }
            }
        }
    </script>
    <script>
        // Countdown Logic
        // ... (existing script)
    </script>
    
    @include('components.content-locker')
@endsection

