@extends('layouts.app')

@section('title', 'Monitoreo en Tiempo Real - Ojo de Águila')
@section('header_title', 'Monitoreo en Vivo')

@section('content')
<div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 24px;">
    <div style="display: flex; align-items: center; gap: 8px;">
        <span style="width: 10px; height: 10px; border-radius: 50%; background-color: var(--danger-color); display: inline-block; animation: pulse 1.5s infinite;"></span>
        <span style="font-size: 14px; font-weight: 700; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.5px;">Panel en Vivo</span>
    </div>
    <span style="font-size: 12px; color: var(--text-light); font-weight: 500;" id="last-poll-time">Actualizando cada 5 segundos...</span>
</div>

<div class="dashboard-grid">
    <!-- Left Column: Estadísticas y Capacidad -->
    <div style="display: flex; flex-direction: column; gap: 24px;">
        <!-- Tarjetas principales -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px;">
            <!-- Personas Adentro -->
            <div class="card" style="margin-bottom: 0;">
                <div class="card-body" style="display: flex; align-items: center; justify-content: space-between; padding: 24px;">
                    <div style="display: flex; flex-direction: column;">
                        <span style="font-size: 13px; font-weight: 600; color: var(--text-secondary);">Personas en Recinto</span>
                        <span style="font-size: 40px; font-weight: 800; color: var(--text-primary); margin-top: 8px; line-height: 1;" id="count-people">8</span>
                        <span style="font-size: 11px; color: var(--success-color); font-weight: 600; margin-top: 8px;">👥 Peatonal</span>
                    </div>
                    <div class="stat-icon" style="background-color: var(--accent-light); color: var(--accent-color); width: 56px; height: 56px; border-radius: var(--radius-md); font-size: 24px;">👥</div>
                </div>
            </div>

            <!-- Vehículos Adentro -->
            <div class="card" style="margin-bottom: 0;">
                <div class="card-body" style="display: flex; align-items: center; justify-content: space-between; padding: 24px;">
                    <div style="display: flex; flex-direction: column;">
                        <span style="font-size: 13px; font-weight: 600; color: var(--text-secondary);">Vehículos Activos</span>
                        <span style="font-size: 40px; font-weight: 800; color: var(--text-primary); margin-top: 8px; line-height: 1;" id="count-vehicles">5</span>
                        <span style="font-size: 11px; color: var(--accent-color); font-weight: 600; margin-top: 8px;">🚗 En tránsito</span>
                    </div>
                    <div class="stat-icon" style="background-color: var(--success-light); color: var(--success-color); width: 56px; height: 56px; border-radius: var(--radius-md); font-size: 24px;">🚗</div>
                </div>
            </div>
        </div>

        <!-- Ocupación de Estacionamientos -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">🅿️ Ocupación de Estacionamientos</h3>
                <span style="font-size: 13px; font-weight: 700; color: var(--text-secondary);" id="parking-ratio">5 / 10 Ocupados</span>
            </div>
            <div class="card-body" style="padding: 24px;">
                <!-- Barra de Progreso -->
                <div style="width: 100%; height: 12px; background-color: #E2E8F0; border-radius: 6px; overflow: hidden; margin-bottom: 12px;">
                    <div style="width: 50%; height: 100%; background-color: var(--accent-color); border-radius: 6px; transition: width 0.8s ease;" id="parking-bar"></div>
                </div>
                <div style="display: flex; justify-content: space-between; font-size: 12px; color: var(--text-secondary); font-weight: 500;">
                    <span>Disponibles: <strong id="parking-available" style="color: var(--success-color);">5</strong></span>
                    <span>Capacidad Total: 10</span>
                </div>
            </div>
        </div>

        <!-- Incidentes Críticos Activos -->
        <div class="card" style="border-color: rgba(239, 68, 68, 0.2); background-color: rgba(239, 68, 68, 0.02);">
            <div class="card-body" style="display: flex; align-items: center; justify-content: space-between; padding: 24px;">
                <div style="display: flex; flex-direction: column;">
                    <span style="font-size: 14px; font-weight: 700; color: var(--danger-color);">🚨 Incidentes hoy</span>
                    <span style="font-size: 12px; color: var(--text-secondary); margin-top: 4px;">Reportados por guardias en turno</span>
                </div>
                <span style="font-size: 28px; font-weight: 800; color: var(--danger-color);" id="count-incidents">1</span>
            </div>
        </div>
    </div>

    <!-- Right Column: Feed de Actividad en Vivo -->
    <div class="card" style="margin-bottom: 0;">
        <div class="card-header">
            <h3 class="card-title">🔔 Feed de actividad reciente</h3>
            <span class="badge badge-info" style="font-size: 10px; letter-spacing: 0.5px;">EN VIVO</span>
        </div>
        <div class="card-body" style="padding: 12px 24px; overflow-y: auto; max-height: 480px;" id="activity-feed-container">
            <!-- Los elementos se renderizan aquí dinámicamente mediante el script AJAX -->
            <div style="text-align: center; color: var(--text-light); padding: 40px;" id="feed-loading">
                Cargando feed de actividad...
            </div>
        </div>
    </div>
</div>

<style>
    @keyframes pulse {
        0% { transform: scale(0.9); opacity: 0.4; }
        50% { transform: scale(1.1); opacity: 1; }
        100% { transform: scale(0.9); opacity: 0.4; }
    }
    .feed-item {
        animation: fadeIn 0.5s ease-out;
        transition: background-color 0.5s ease;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(-10px); }
        to { opacity: 1; transform: translateY(0); }
    }
</style>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        var lastFeedCount = 0;

        function fetchRealtimeData() {
            fetch('/api/monitoring/data')
                .then(res => res.json())
                .then(response => {
                    if (response.success) {
                        const data = response.data;

                        // 1. Actualizar contadores principales
                        document.getElementById('count-people').innerText = data.people_inside;
                        document.getElementById('count-vehicles').innerText = data.vehicles_inside;
                        document.getElementById('count-incidents').innerText = data.active_incidents;

                        // 2. Actualizar barra de estacionamientos
                        const occupied = data.parking.occupied;
                        const total = data.parking.total;
                        const pct = (occupied / total) * 100;
                        document.getElementById('parking-bar').style.width = pct + '%';
                        document.getElementById('parking-ratio').innerText = occupied + ' / ' + total + ' Ocupados';
                        document.getElementById('parking-available').innerText = (total - occupied);

                        // 3. Actualizar hora de la consulta
                        const now = new Date();
                        document.getElementById('last-poll-time').innerText = 'Actualizado: ' + now.toLocaleTimeString('es-CL');

                        // 4. Renderizar feed
                        const container = document.getElementById('activity-feed-container');
                        const loading = document.getElementById('feed-loading');
                        if (loading) loading.style.display = 'none';

                        let html = '';
                        data.feed.forEach(function(item) {
                            const isExit = item.exit_time !== null;
                            const badgeColor = item.type === 'person' ? 'badge-info' : (item.type === 'vehicle' ? 'badge-success' : 'badge-warning');
                            const icon = item.type === 'person' ? '👥' : (item.type === 'vehicle' ? '🚗' : '📦');

                            html += `
                                <div class="feed-item" style="display: flex; align-items: flex-start; justify-content: space-between; padding: 14px 0; border-bottom: 1px solid var(--border-color); &:last-child { border-bottom: none; }">
                                    <div style="display: flex; align-items: flex-start; gap: 12px;">
                                        <div style="font-size: 20px; background-color: #F1F5F9; width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0;">
                                            ${icon}
                                        </div>
                                        <div style="display: flex; flex-direction: column;">
                                            <span style="font-size: 13px; font-weight: 700; color: var(--text-primary);">${item.name}</span>
                                            <span style="font-size: 11px; color: var(--text-secondary); margin-top: 2px;">${item.subtext}</span>
                                            <span style="font-size: 11px; font-weight: 600; color: var(--text-light); margin-top: 4px;">📍 Destino: ${item.zone}</span>
                                        </div>
                                    </div>
                                    <div style="text-align: right; display: flex; flex-direction: column; align-items: flex-end; gap: 6px;">
                                        <span style="font-size: 11px; font-weight: 700; color: var(--text-primary);">
                                            ${isExit ? '📤 Salió: ' + item.exit_time : '📥 Entró: ' + item.time}
                                        </span>
                                        <span class="badge ${badgeColor}" style="font-size: 9px; padding: 1px 6px;">
                                            ${item.type_label}
                                        </span>
                                    </div>
                                </div>
                            `;
                        });

                        container.innerHTML = html;

                        // Efecto de parpadeo si hay más registros de los que había antes
                        if (lastFeedCount > 0 && data.feed.length > lastFeedCount) {
                            const firstItem = container.querySelector('.feed-item');
                            if (firstItem) {
                                firstItem.style.backgroundColor = 'var(--accent-light)';
                                setTimeout(() => firstItem.style.backgroundColor = 'transparent', 2000);
                            }
                        }
                        lastFeedCount = data.feed.length;
                    }
                })
                .catch(err => console.error('Error fetching realtime data:', err));
        }

        // Consultar inmediatamente y luego cada 5 segundos
        fetchRealtimeData();
        setInterval(fetchRealtimeData, 5000);
    });
</script>
@endsection
