<?php
/**
 * Traffic Cameras Module — Downtown Cincinnati, Bridges, Hopple St
 * Live OHGO camera feeds with auto-refresh.
 */
?>

<div class="page-header">
    <h1>Traffic Cameras</h1>
    <div style="display:flex; align-items:center; gap:12px;">
        <span class="badge badge-green" id="cameraStatus">Live</span>
        <button class="btn btn-sm btn-secondary" onclick="refreshCameras()">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-2px;"><path d="M23 4v6h-6"/><path d="M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
            Refresh
        </button>
    </div>
</div>

<!-- Camera Groups -->
<div class="segmented-control" style="margin-bottom:20px;">
    <button class="seg-btn active" data-tab-group="cam" data-tab="cam-all" onclick="switchTab('cam','cam-all'); filterCameras('all')">All Cameras</button>
    <button class="seg-btn" data-tab-group="cam" data-tab="cam-bridge" onclick="switchTab('cam','cam-bridge'); filterCameras('bridge')">Bridges / I-75</button>
    <button class="seg-btn" data-tab-group="cam" data-tab="cam-hopple" onclick="switchTab('cam','cam-hopple'); filterCameras('hopple')">Hopple St Area</button>
    <button class="seg-btn" data-tab-group="cam" data-tab="cam-downtown" onclick="switchTab('cam','cam-downtown'); filterCameras('downtown')">Downtown</button>
</div>

<!-- Last updated -->
<div style="margin-bottom:16px; display:flex; align-items:center; justify-content:space-between;">
    <span style="font-size:13px; color:var(--ios-secondary);">Images refresh every 30 seconds &middot; Last updated: <span id="cameraLastUpdate">loading...</span></span>
    <label style="font-size:13px; color:var(--ios-secondary); display:flex; align-items:center; gap:6px; cursor:pointer;">
        <input type="checkbox" id="autoRefreshToggle" checked style="accent-color:var(--accent);"> Auto-refresh
    </label>
</div>

<!-- Camera Grid -->
<div class="grid grid-3" id="cameraGrid">
    <div class="card" style="grid-column:1/-1; text-align:center; padding:40px;">
        <div class="skeleton skeleton-card" style="height:200px; margin-bottom:12px;"></div>
        <p style="color:var(--ios-secondary);">Loading cameras...</p>
    </div>
</div>

<!-- Fullscreen Modal -->
<div class="modal-overlay" id="cameraModal">
    <div class="modal" style="max-width:900px; padding:0; overflow:hidden; background:#000;">
        <div style="display:flex; align-items:center; justify-content:space-between; padding:12px 16px; background:var(--primary);">
            <span id="modalCameraName" style="color:#fff; font-weight:700; font-size:15px;"></span>
            <button class="modal-close" onclick="closeModal('cameraModal')" style="background:rgba(255,255,255,0.15); color:#fff;">&times;</button>
        </div>
        <div style="position:relative;">
            <img id="modalCameraImage" src="" alt="" style="width:100%; display:block;">
            <div id="modalCameraTime" style="position:absolute; bottom:8px; right:8px; background:rgba(0,0,0,0.7); color:#fff; padding:4px 10px; border-radius:6px; font-size:12px; font-weight:600;"></div>
        </div>
        <div style="padding:12px 16px; background:var(--primary); display:flex; gap:12px; align-items:center;">
            <span id="modalCameraDesc" style="color:rgba(255,255,255,0.7); font-size:13px; flex:1;"></span>
            <button class="btn btn-sm" style="background:var(--accent); color:#fff;" onclick="openInMaps()">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:-2px;"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>
                Map
            </button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    'use strict';

    const grid = document.getElementById('cameraGrid');
    const statusBadge = document.getElementById('cameraStatus');
    const lastUpdateEl = document.getElementById('cameraLastUpdate');
    const autoRefreshToggle = document.getElementById('autoRefreshToggle');
    let allCameras = [];
    let currentFilter = 'all';
    let refreshTimer = null;
    let selectedCamera = null;

    const groups = {
        bridge: ['I-75 at 3rd St', 'I-75 at 6th St', 'I-71/I-75 Merge', 'I-75 at Linn St', 'I-75 at Ezzard Charles Dr', 'I-75 at Western Hills Viaduct', 'I-75 at I-74', 'I-75 South of I-74'],
        hopple: ['I-75 at Hopple St', 'I-75 North of Hopple St', 'I-75 South of Hopple St', 'I-75 at Western Hills Viaduct', 'I-75 at I-74'],
        downtown: ['3rd St at Vine St', '2nd St at Elm St', '3rd St at Sycamore St', 'Eggleston Ave at Pete Rose Way', 'I-71 at US-50 (Lytle Tunnel)', 'I-71 at I-471', 'I-71 at Casino/Gilbert Ave']
    };

    async function loadCameras() {
        try {
            const data = await window.portalAPI('cameras.php');
            if (!data || data.error) {
                statusBadge.className = 'badge badge-red';
                statusBadge.textContent = 'Offline';
                return;
            }

            allCameras = data.cameras || [];
            statusBadge.className = 'badge badge-green';
            statusBadge.textContent = 'Live';
            lastUpdateEl.textContent = new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', second: '2-digit' });

            renderCameras();
        } catch (err) {
            statusBadge.className = 'badge badge-red';
            statusBadge.textContent = 'Error';
        }
    }

    function renderCameras() {
        let filtered = allCameras;
        if (currentFilter !== 'all') {
            const groupNames = groups[currentFilter] || [];
            filtered = allCameras.filter(c => groupNames.includes(c.name));
        }

        if (filtered.length === 0) {
            grid.innerHTML = `
                <div class="card" style="grid-column:1/-1; text-align:center; padding:40px;">
                    <p style="color:var(--ios-secondary);">No cameras available for this view.</p>
                </div>`;
            return;
        }

        grid.innerHTML = filtered.map(cam => `
            <div class="card camera-card" style="padding:0; overflow:hidden; cursor:pointer;" onclick="openCamera('${cam.id}')">
                <div style="position:relative; background:#0B2240; min-height:180px;">
                    <img src="${cam.image_url}" alt="${cam.name}" loading="lazy"
                         style="width:100%; height:180px; object-fit:cover; display:block;"
                         onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                    <div style="display:none; width:100%; height:180px; align-items:center; justify-content:center; color:rgba(255,255,255,0.4); font-size:13px;">
                        Camera unavailable
                    </div>
                    <div style="position:absolute; top:8px; left:8px;">
                        <span style="background:rgba(0,0,0,0.6); color:#fff; padding:2px 8px; border-radius:4px; font-size:10px; font-weight:600;">LIVE</span>
                    </div>
                </div>
                <div style="padding:12px 14px;">
                    <div style="font-weight:700; font-size:14px; color:var(--primary); margin-bottom:2px;">${cam.name}</div>
                    <div style="font-size:12px; color:var(--ios-secondary); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${cam.description}</div>
                </div>
            </div>
        `).join('');
    }

    window.filterCameras = function(filter) {
        currentFilter = filter;
        renderCameras();
    };

    window.openCamera = function(id) {
        selectedCamera = allCameras.find(c => c.id === id);
        if (!selectedCamera) return;

        document.getElementById('modalCameraName').textContent = selectedCamera.name;
        document.getElementById('modalCameraDesc').textContent = selectedCamera.description;
        document.getElementById('modalCameraTime').textContent = new Date().toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });

        const img = document.getElementById('modalCameraImage');
        img.src = selectedCamera.image_url + '?t=' + Date.now();
        img.alt = selectedCamera.name;

        openModal('cameraModal');
    };

    window.openInMaps = function() {
        if (!selectedCamera) return;
        window.open(`https://www.google.com/maps?q=${selectedCamera.latitude},${selectedCamera.longitude}`, '_blank');
    };

    window.refreshCameras = function() {
        loadCameras();
        // Also bust image cache by reloading with timestamp
        document.querySelectorAll('.camera-card img').forEach(img => {
            const src = img.src.split('?')[0];
            img.src = src + '?t=' + Date.now();
        });
    };

    // Auto-refresh every 30 seconds
    function startAutoRefresh() {
        if (refreshTimer) clearInterval(refreshTimer);
        refreshTimer = setInterval(() => {
            if (autoRefreshToggle.checked) {
                refreshCameras();
            }
        }, 30000);
    }

    autoRefreshToggle.addEventListener('change', () => {
        if (autoRefreshToggle.checked) startAutoRefresh();
        else if (refreshTimer) clearInterval(refreshTimer);
    });

    loadCameras();
    startAutoRefresh();
});
</script>
