<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MONITOREO CADENA DE FRÍO - PREFECTURA NAVAL ARGENTINA</title>
    <link rel="stylesheet" href="styles/main.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
</head>

<body>
    <div class="dashboard-container">
        <!-- HEADER SECTION -->
        <header class="header">
            <div class="header-title">
                <h1><span>🧪</span> BARCO DE PRUEBAS <small
                        style="font-size: 0.6rem; color: var(--gold-glow); vertical-align: middle;">MODO
                        SIMULACIÓN</small></h1>
                <select id="shipSelector" class="ship-selector" style="display:none;" onchange="changeShip(this.value)">
                    <option value="BUQUE-SIMULACION">BUQUE-SIMULACION</option>
                </select>
            </div>

            <div id="argentinaClock" class="live-clock">--:--:--</div>

            <div class="header-status">
                <div id="statusIndicator" class="status-pill status-offline">
                    <span class="pulse-dot"></span>
                    <span id="statusText">SIN SEÑAL</span>
                </div>
                <div class="header-links">
                    <a href="ver_datos.php"
                        style="color: var(--cyan-glow); text-decoration: none; font-weight: 600; font-size: 0.9rem;">ENTRAR
                        HISTORIAL</a>
                </div>
            </div>
        </header>

        <!-- SHIP SENSOR MAP SECTION -->
        <section class="ship-visualizer">
            <div class="visualizer-header">
                <h2 style="font-size: 0.8rem; color: var(--text-secondary); margin: 0;">MAPA DE SENSORES</h2>
                <button id="lockToggle" class="lock-btn" onclick="toggleLock()">🔓 DESBLOQUEADO</button>
            </div>
            <div class="map-container" id="mapContainer">
                <img src="ship_map.png" alt="Mapa de Sensores" class="ship-model" id="shipImg">
                <div id="markersLayer"></div>
                <div class="scan-line"></div>
            </div>
        </section>

        <!-- METRICS GRID SECTION (DYNAMIC) -->
        <section class="metrics-grid" id="metricsGrid">
            <!-- Dynamic Cards -->
            <div class="add-card" onclick="addSensor()">
                <span>+</span>
                <label>AGREGAR SENSOR</label>
            </div>
        </section>

        <!-- CHART ANALYTICS SECTION -->
        <section class="chart-section">
            <h2 style="font-size: 1rem; color: var(--text-secondary); margin-bottom: 15px;">TENDENCIAS DE TEMPERATURA
                (24H)</h2>
            <div style="height: 250px;">
                <canvas id="coldChainChart"></canvas>
            </div>
        </section>

        <!-- FOOTER MESSAGES -->
        <section class="messages-panel">
            <div class="messages-list" id="mensajesPruebaLista"></div>
        </section>
    </div>

    <script>
        let currentBuque = 'BUQUE-SIMULACION';
        let mainChart = null;
        let isLocked = true; // Lock by default in sim
        let activeMarker = null;
        let activeSensors = [];
        let lastData = null; // Cache for immediate rendering

        // --- SIMULATION ENGINE ---
        async function runSimulation() {
            const sensorsCount = 10;
            const temps = [];
            for (let i = 0; i < sensorsCount; i++) {
                const base = 20;
                const variance = Math.random() * 10 - 5;
                temps.push((base + variance).toFixed(1));
            }

            // Format: buque_id,t1,t2...t10,key
            // Removing extra spaces and ensuring exactly what api/buque.php expects
            const csvData = `BUQUE-SIMULACION,${temps.join(',')},BUQUE2024_SECRET_KEY_XYZ789`;

            try {
                const response = await fetch('api/buque.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'text/plain' },
                    body: csvData
                });
                const result = await response.json();
                if (result.success) {
                    console.log('✅ Simulación: Datos enviados OK (ID: ' + result.data.id + ')');
                } else {
                    console.error('❌ Simulación: Error de API:', result.message);
                }
            } catch (e) {
                console.error('❌ Simulación: Error de red:', e);
            }
        }

        // Start simulation
        setInterval(runSimulation, 5000);
        runSimulation();

        function startClock() {
            setInterval(() => {
                const clock = document.getElementById('argentinaClock');
                const now = new Date();
                const options = { timeZone: 'America/Argentina/Buenos_Aires', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
                clock.textContent = new Intl.DateTimeFormat('es-AR', options).format(now);
            }, 1000);
        }

        // --- DYNAMIC SENSOR MANAGEMENT ---

        function loadConfig() {
            const saved = localStorage.getItem(`config_${currentBuque}`);
            if (saved) {
                activeSensors = JSON.parse(saved);
            } else {
                activeSensors = [
                    { id: 1, label: 'PROA - 1', x: '70%', yTop: '23%', ySide: '76%' },
                    { id: 2, label: 'POPA - 2', x: '30%', yTop: '23%', ySide: '76%' },
                    { id: 3, label: 'BABOR - 3', x: '50%', yTop: '15%', ySide: '76%' },
                    { id: 4, label: 'ESTRIBOR - 4', x: '50%', yTop: '31%', ySide: '76%' },
                    { id: 5, label: 'BODEGA A - 5', x: '45%', yTop: '23%', ySide: '76%' },
                    { id: 6, label: 'BODEGA B - 6', x: '55%', yTop: '23%', ySide: '76%' }
                ];
            }
            renderUI();
        }

        function saveConfig() {
            localStorage.setItem(`config_${currentBuque}`, JSON.stringify(activeSensors));
        }

        function renderUI() {
            const grid = document.getElementById('metricsGrid');
            const map = document.getElementById('markersLayer');

            const addCard = grid.querySelector('.add-card');
            grid.innerHTML = '';
            map.innerHTML = '';

            activeSensors.forEach(s => {
                const card = document.createElement('div');
                card.className = 'metric-card';
                card.id = `card${s.id}`;
                card.innerHTML = `
                    <button class="delete-btn" onclick="removeSensor(${s.id})">🗑️</button>
                    <div class="card-meta">
                        <span class="ip-meta" id="ip${s.id}">IP: --</span>
                        <span class="time-meta" id="time${s.id}">--:--:--</span>
                    </div>
                    <input class="editable-label" value="${s.label}" oninput="updateLabel(${s.id}, this.value)" spellcheck="false">
                    <div class="metric-value">
                        <span id="temp${s.id}">--</span>
                        <span class="metric-unit">°C</span>
                    </div>
                `;
                grid.appendChild(card);

                createMarker(s, 'top', map);
                createMarker(s, 'side', map);
            });

            grid.appendChild(addCard);
            if (mainChart) updateChartDatasets();

            // Re-apply last known values immediately
            if (lastData) applyData(lastData);
        }

        function createMarker(s, type, container) {
            const marker = document.createElement('div');
            marker.className = `sensor-marker m${s.id} marker-${type}`;
            marker.id = `marker-${type}-${s.id}`;
            marker.style.left = s.x;
            marker.style.top = type === 'top' ? s.yTop : s.ySide;

            const onStart = (e) => {
                startDrag(e, s.id, type);
            };

            marker.addEventListener('mousedown', onStart);
            marker.addEventListener('touchstart', onStart, { passive: false });
            marker.innerHTML = `
                <span class="marker-label" id="mLabel-${type}-${s.id}">${s.label}</span>
                <span class="marker-temp" id="mTemp-${type}-${s.id}">--°C</span>
            `;
            container.appendChild(marker);
        }

        function applyData(data) {
            if (!data.ultima) return;
            activeSensors.forEach(s => {
                const val = data.ultima[`temp${s.id}`];
                const tEl = document.getElementById(`temp${s.id}`);
                if (tEl) tEl.textContent = val != null ? val.toFixed(1) : '--';

                const ipEl = document.getElementById(`ip${s.id}`);
                const timeEl = document.getElementById(`time${s.id}`);
                if (ipEl) ipEl.textContent = `ORIGEN: ${data.ultima.ip || '---'}`;
                if (timeEl) {
                    const d = new Date(data.ultima.fecha);
                    timeEl.textContent = d.toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
                }

                ['top', 'side'].forEach(type => {
                    const mEl = document.getElementById(`mTemp-${type}-${s.id}`);
                    if (mEl) mEl.textContent = val != null ? `${val.toFixed(1)}°C` : '--°C';
                });

                const card = document.getElementById(`card${s.id}`);
                if (card && val != null) {
                    if (val > 10) card.style.borderLeft = '4px solid var(--red-alert)';
                    else card.style.borderLeft = '4px solid var(--cyan-glow)';
                }
            });
        }

        function addSensor() {
            if (activeSensors.length >= 10) return;
            const usedIds = activeSensors.map(s => s.id);
            let nextId = 1;
            while (usedIds.includes(nextId)) nextId++;

            activeSensors.push({
                id: nextId,
                label: `SENSOR #${nextId}`,
                x: '50%',
                yTop: '23%',
                ySide: '76%'
            });
            saveConfig();
            renderUI();
        }

        function removeSensor(id) {
            if (!confirm("¿Eliminar este sensor?")) return;
            activeSensors = activeSensors.filter(s => s.id !== id);
            saveConfig();
            renderUI();
        }

        function updateLabel(id, newLabel) {
            const sensor = activeSensors.find(s => s.id === id);
            if (sensor) {
                sensor.label = newLabel;
                const topLabel = document.getElementById(`mLabel-top-${id}`);
                const sideLabel = document.getElementById(`mLabel-side-${id}`);
                if (topLabel) topLabel.textContent = newLabel;
                if (sideLabel) sideLabel.textContent = newLabel;
                saveConfig();
            }
        }

        // --- DUAL-AXIS DRAG AND DROP ---

        function startDrag(e, id, type) {
            if (isLocked) return;
            activeMarker = { id: id, type: type, element: document.getElementById(`marker-${type}-${id}`) };
            e.preventDefault();
        }

        function handleMove(e) {
            if (!activeMarker) return;
            const clientX = (e.touches && e.touches.length > 0) ? e.touches[0].clientX : e.clientX;
            const clientY = (e.touches && e.touches.length > 0) ? e.touches[0].clientY : e.clientY;

            if (e.type === 'touchmove') e.preventDefault();

            const container = document.getElementById('mapContainer');
            const rect = container.getBoundingClientRect();

            let x = ((clientX - rect.left) / rect.width) * 100;
            let y = ((clientY - rect.top) / rect.height) * 100;

            x = Math.max(0, Math.min(100, x));
            y = Math.max(0, Math.min(100, y));

            const sensor = activeSensors.find(s => s.id === activeMarker.id);
            if (!sensor) return;

            sensor.x = `${x.toFixed(2)}%`;
            if (activeMarker.type === 'top') {
                sensor.yTop = `${y.toFixed(2)}%`;
            } else {
                sensor.ySide = `${y.toFixed(2)}%`;
            }

            const topEl = document.getElementById(`marker-top-${sensor.id}`);
            const sideEl = document.getElementById(`marker-side-${sensor.id}`);

            if (topEl) {
                topEl.style.left = sensor.x;
                topEl.style.top = sensor.yTop;
            }
            if (sideEl) {
                sideEl.style.left = sensor.x;
                sideEl.style.top = sensor.ySide;
            }
        }

        document.addEventListener('mousemove', handleMove);
        document.addEventListener('touchmove', handleMove, { passive: false });

        const endDrag = () => {
            if (activeMarker) {
                saveConfig();
                activeMarker = null;
            }
        };

        document.addEventListener('mouseup', endDrag);
        document.addEventListener('touchend', endDrag);

        function toggleLock() {
            isLocked = !isLocked;
            const btn = document.getElementById('lockToggle');
            btn.textContent = isLocked ? '🔒 BLOQUEADO' : '🔓 DESBLOQUEADO';
            btn.style.background = isLocked ? 'var(--red-alert)' : 'var(--cyan-glow)';
            document.getElementById('mapContainer').style.cursor = isLocked ? 'default' : 'crosshair';
        }

        // --- CHARTING & UPDATES ---

        function updateChartDatasets() {
            const sensorColors = ['#ff4d4d', '#00f2ff', '#f0b429', '#00ffaa', '#9b59b6', '#ffffff', '#ff00ff', '#00ff00', '#ff8800', '#888888'];
            mainChart.data.datasets = activeSensors.map(s => ({
                label: s.label,
                data: [],
                borderColor: sensorColors[(s.id - 1) % 10],
                tension: 0.4,
                borderWidth: 2,
                pointRadius: 0
            }));
            mainChart.update();
        }

        function initChart() {
            const ctx = document.getElementById('coldChainChart').getContext('2d');
            mainChart = new Chart(ctx, {
                type: 'line',
                data: { labels: [], datasets: [] },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: { legend: { labels: { color: '#8892b0', boxWidth: 10 } } },
                    scales: {
                        x: { ticks: { color: '#8892b0', font: { size: 10 } }, grid: { display: false } },
                        y: { ticks: { color: '#8892b0' }, grid: { color: 'rgba(255,255,255,0.05)' } }
                    }
                }
            });
            updateChartDatasets();
        }

        async function updateDashboard() {
            try {
                const response = await fetch(`api/dashboard_data.php?buque_id=${currentBuque}&_=${Date.now()}`);
                const result = await response.json();

                if (result.success) {
                    lastData = result.data; // Cache it
                    updateUIStatus(true);

                    const sel = document.getElementById('shipSelector');
                    if (lastData.lista_buques && sel.options.length <= 1) {
                        sel.innerHTML = lastData.lista_buques.map(b => `<option value="${b}" ${b === currentBuque ? 'selected' : ''}>${b}</option>`).join('');
                    }

                    applyData(lastData);

                    if (lastData.historial && lastData.historial.length > 0) {
                        mainChart.data.labels = lastData.historial.map(h => new Date(h.fecha).toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit' }));
                        activeSensors.forEach((s, idx) => {
                            if (mainChart.data.datasets[idx]) {
                                mainChart.data.datasets[idx].data = lastData.historial.map(h => h[`temp${s.id}`]);
                            }
                        });
                        mainChart.update('none');
                    }
                }
            } catch (error) {
                console.error(error);
                updateUIStatus(false);
            }
        }

        function changeShip(id) {
            currentBuque = id;
            loadConfig();
            updateDashboard();
        }

        function updateUIStatus(online) {
            const indicator = document.getElementById('statusIndicator');
            const text = document.getElementById('statusText');
            if (indicator) {
                indicator.className = online ? 'status-pill status-online' : 'status-pill status-offline';
                text.textContent = online ? 'LINK ACTIVO' : 'SIN DATOS';
            }
        }

        startClock();
        initChart();
        loadConfig();
        updateDashboard();
        setInterval(updateDashboard, 5000);
    </script>
</body>

</html>