@extends('layouts.app')
@section('title', 'Device Map')

@push('head')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<style>
#map { height: calc(100vh - 180px); min-height: 460px; border-radius: 10px; border: 1px solid #1e2433; }
.device-panel { max-height: calc(100vh - 180px); overflow-y: auto; }
.dev-card {
    background: #0d1117; border: 1px solid #1e2433; border-radius: 8px;
    padding: 14px; margin-bottom: 10px; cursor: pointer; transition: border-color .15s;
}
.dev-card:hover { border-color: #3b82f6; }
.dev-card.selected { border-color: #60a5fa; background: #0f1e35; }
.mode-dot {
    width: 12px; height: 12px; border-radius: 50%; display: inline-block; margin-right: 6px;
}
.mode-dot.buka  { background: #4ade80; box-shadow: 0 0 6px #4ade80; }
.mode-dot.tutup { background: #f87171; box-shadow: 0 0 6px #f87171; }
.mode-dot.unknown { background: #64748b; }
.leaflet-popup-content-wrapper {
    background: #141820 !important; color: #e2e8f0 !important;
    border: 1px solid #1e2433; border-radius: 8px !important; box-shadow: 0 4px 20px rgba(0,0,0,.5) !important;
}
.leaflet-popup-tip { background: #141820 !important; }
.leaflet-popup-content { margin: 14px 16px !important; min-width: 220px; }
.popup-title { font-weight: 700; font-size: .95rem; margin-bottom: 6px; }
.popup-row { display: flex; justify-content: space-between; font-size: .8rem; color: #94a3b8; margin-top: 3px; }
.popup-row strong { color: #e2e8f0; }
.popup-actions { display: flex; gap: 6px; margin-top: 10px; }
.popup-btn {
    flex: 1; padding: 5px 8px; border: none; border-radius: 5px;
    font-size: .78rem; font-weight: 600; cursor: pointer; text-align: center;
}
.popup-btn-buka  { background: #166534; color: #4ade80; }
.popup-btn-tutup { background: #7f1d1d; color: #f87171; }
.popup-btn:hover { opacity: .85; }
.map-legend {
    position: absolute; bottom: 32px; left: 60px; z-index: 1000;
    background: rgba(20,24,32,.92); border: 1px solid #1e2433;
    border-radius: 8px; padding: 10px 14px; font-size: .8rem; color: #94a3b8;
}
.map-legend .le { display: flex; align-items: center; gap: 8px; margin: 4px 0; }
</style>
@endpush

@section('content')
<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0 fw-bold"><i class="bi bi-map me-2 text-primary"></i>Device Map</h5>
    <div class="d-flex gap-2 align-items-center">
        <span class="text-secondary" style="font-size:.8rem">
            <i class="bi bi-geo-alt me-1"></i>USJ — Seafield Toll Plaza, LDP Northbound
        </span>
        <button class="btn btn-outline-primary btn-sm" id="refreshBtn">
            <i class="bi bi-arrow-clockwise me-1"></i>Refresh
        </button>
    </div>
</div>

<div class="row g-3">
    {{-- Map --}}
    <div class="col-lg-8 position-relative">
        <div id="map"></div>
        <div class="map-legend">
            <div style="font-size:.7rem;text-transform:uppercase;letter-spacing:.8px;color:#475569;margin-bottom:6px">Legend</div>
            <div class="le"><span class="mode-dot buka"></span> BUKA (Active)</div>
            <div class="le"><span class="mode-dot tutup"></span> TUTUP (Inactive)</div>
            <div class="le"><span class="mode-dot unknown"></span> Unknown / Offline</div>
        </div>
    </div>

    {{-- Device cards sidebar --}}
    <div class="col-lg-4 device-panel">
        <div class="mb-3" style="font-size:.75rem;color:#64748b;text-transform:uppercase;letter-spacing:.7px">
            Devices ({{ $devices->count() }})
        </div>
        @forelse($devices as $device)
        <div class="dev-card" id="card-{{ $device->id }}"
             onclick="focusDevice({{ $device->id }})"
             data-lat="{{ $device->latitude }}" data-lng="{{ $device->longitude }}">
            <div class="d-flex align-items-center justify-content-between mb-2">
                <div class="fw-semibold" style="font-size:.9rem">
                    <span class="mode-dot {{ $device->last_sent_mode ?? 'unknown' }}"></span>
                    {{ $device->name }}
                </div>
                <span class="badge {{ $device->last_status === 'online' ? 'bg-success' : ($device->last_status === 'offline' ? 'bg-danger' : 'bg-secondary') }}" style="font-size:.68rem">
                    {{ $device->last_status ?? 'unknown' }}
                </span>
            </div>

            <div style="font-size:.8rem;color:#7dd3fc;font-family:monospace">
                {{ $device->ip_address }}:{{ $device->port }}
            </div>

            @if($device->chainage || $device->highway)
            <div class="text-secondary mt-1" style="font-size:.75rem">
                <i class="bi bi-sign-turn-right me-1"></i>
                {{ $device->chainage }} — {{ $device->highway }}
            </div>
            @endif

            @if($device->location)
            <div class="text-secondary" style="font-size:.73rem">
                <i class="bi bi-geo-alt me-1"></i>{{ $device->location }}
            </div>
            @endif

            @if($device->latitude && $device->longitude)
            <div style="font-size:.72rem;color:#475569;margin-top:3px">
                {{ number_format($device->latitude, 4) }}°N, {{ number_format($device->longitude, 4) }}°E
            </div>
            @endif

            <div class="d-flex align-items-center justify-content-between mt-2">
                <div>
                    @if($device->last_sent_mode)
                        <span class="badge badge-{{ $device->last_sent_mode }}">{{ strtoupper($device->last_sent_mode) }}</span>
                        <span class="text-secondary ms-1" style="font-size:.7rem">{{ $device->last_sent_at?->format('d/m H:i') }}</span>
                    @else
                        <span class="badge bg-secondary">No data</span>
                    @endif
                </div>
                <div class="d-flex gap-1">
                    <button class="btn btn-success btn-sm py-0 px-2 map-quick" data-id="{{ $device->id }}" data-mode="buka" style="font-size:.72rem">BUKA</button>
                    <button class="btn btn-danger  btn-sm py-0 px-2 map-quick" data-id="{{ $device->id }}" data-mode="tutup" style="font-size:.72rem">TUTUP</button>
                </div>
            </div>
        </div>
        @empty
        <div class="text-center text-secondary py-4">No devices configured.</div>
        @endforelse

        {{-- Highway info box --}}
        <div style="background:#0d1117;border:1px solid #1e2433;border-radius:8px;padding:14px;margin-top:6px">
            <div style="font-size:.75rem;color:#60a5fa;font-weight:600;margin-bottom:8px">
                <i class="bi bi-info-circle me-1"></i>Installation Info
            </div>
            <div style="font-size:.78rem;color:#94a3b8;line-height:1.7">
                <i class="bi bi-geo-alt-fill text-danger me-1"></i>LDP Northbound<br>
                <i class="bi bi-arrow-right me-1"></i>USJ → Seafield Toll Plaza<br>
                <i class="bi bi-sign-stop me-1"></i>KM6.1 NB & KM8.1 NB<br>
                <i class="bi bi-hdd-network me-1"></i>Protocol: Huidu TCP :9527<br>
                <i class="bi bi-sun me-1"></i>Solar-powered LED panels
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
const CSRF = document.querySelector('meta[name=csrf-token]').content;
const devices = @json($mapped);
const centreLat = {{ $centreLat }};
const centreLng = {{ $centreLng }};

// ── Map init ───────────────────────────────────────────────────────────────
const map = L.map('map', {
    center: [centreLat, centreLng],
    zoom: 15,
    zoomControl: true,
});

// Satellite layer (Esri World Imagery — no key needed)
const satellite = L.tileLayer(
    'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
    { attribution: 'Esri, Maxar, GeoEye', maxZoom: 20 }
);

// Street layer
const street = L.tileLayer(
    'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    { attribution: '© OpenStreetMap contributors', maxZoom: 20 }
);

satellite.addTo(map);
L.control.layers({'Satellite': satellite, 'Street Map': street}, {}, {position:'topright'}).addTo(map);

// ── Custom icons ───────────────────────────────────────────────────────────
function makeIcon(mode) {
    const color   = mode === 'buka' ? '#4ade80' : mode === 'tutup' ? '#f87171' : '#94a3b8';
    const glow    = mode === 'buka' ? '0 0 12px #4ade80' : mode === 'tutup' ? '0 0 12px #f87171' : 'none';
    const label   = mode ? mode.toUpperCase() : '?';
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="60" height="70" viewBox="0 0 60 70">
        <defs>
            <filter id="glow">
                <feGaussianBlur stdDeviation="2.5" result="coloredBlur"/>
                <feMerge><feMergeNode in="coloredBlur"/><feMergeNode in="SourceGraphic"/></feMerge>
            </filter>
        </defs>
        <rect x="5" y="5" width="50" height="48" rx="8" fill="#141820" stroke="${color}" stroke-width="2.5" filter="url(#glow)"/>
        <circle cx="30" cy="24" r="12" fill="${color}" opacity=".9"/>
        <text x="30" y="45" text-anchor="middle" font-size="9" font-weight="bold" font-family="Arial" fill="${color}">${label}</text>
        <line x1="30" y1="53" x2="30" y2="65" stroke="${color}" stroke-width="2"/>
        <circle cx="30" cy="67" r="3" fill="${color}"/>
    </svg>`;
    return L.divIcon({
        html: `<div style="filter:drop-shadow(${glow})">${svg}</div>`,
        iconSize:   [60, 70],
        iconAnchor: [30, 67],
        popupAnchor:[0, -70],
        className:  '',
    });
}

// ── Draw device markers ────────────────────────────────────────────────────
const markers = {};
const deviceData = {};

function buildPopup(d) {
    const modeColor = d.last_sent_mode === 'buka' ? '#4ade80' : d.last_sent_mode === 'tutup' ? '#f87171' : '#94a3b8';
    const lastSent  = d.last_sent_at ? new Date(d.last_sent_at).toLocaleString('en-MY', {timeZone:'Asia/Kuala_Lumpur'}) : 'Never';
    return `
        <div class="popup-title"><span style="color:${modeColor}">●</span> ${d.name}</div>
        <div class="popup-row"><span>IP Address</span><strong style="font-family:monospace;color:#7dd3fc">${d.ip_address}:${d.port}</strong></div>
        <div class="popup-row"><span>Chainage</span><strong>${d.chainage || '—'}</strong></div>
        <div class="popup-row"><span>Highway</span><strong>${d.highway || '—'}</strong></div>
        <div class="popup-row"><span>Current Mode</span><strong style="color:${modeColor}">${d.last_sent_mode ? d.last_sent_mode.toUpperCase() : '—'}</strong></div>
        <div class="popup-row"><span>Status</span><strong>${d.last_status || 'unknown'}</strong></div>
        <div class="popup-row"><span>Last Sent</span><strong>${lastSent}</strong></div>
        <div class="popup-actions">
            <button class="popup-btn popup-btn-buka"  onclick="quickSend(${d.id},'buka')">● BUKA</button>
            <button class="popup-btn popup-btn-tutup" onclick="quickSend(${d.id},'tutup')">● TUTUP</button>
        </div>`;
}

devices.forEach(d => {
    if (!d.latitude || !d.longitude) return;
    deviceData[d.id] = d;
    const m = L.marker([d.latitude, d.longitude], { icon: makeIcon(d.last_sent_mode) })
        .addTo(map)
        .bindPopup(buildPopup(d), { maxWidth: 260 });
    markers[d.id] = m;
});

// Draw route line between all mapped devices (ordered by chainage desc)
if (devices.filter(d => d.latitude).length > 1) {
    const pts = [...devices]
        .filter(d => d.latitude)
        .sort((a,b) => (a.chainage || '').localeCompare(b.chainage || ''));
    L.polyline(pts.map(d => [d.latitude, d.longitude]), {
        color: '#60a5fa', weight: 3, opacity: .6, dashArray: '6,6'
    }).addTo(map);
}

// ── Focus device from card click ───────────────────────────────────────────
function focusDevice(id) {
    document.querySelectorAll('.dev-card').forEach(c => c.classList.remove('selected'));
    const card = document.getElementById('card-' + id);
    if (card) card.classList.add('selected');
    const m = markers[id];
    if (m) {
        map.flyTo(m.getLatLng(), 17, { animate: true, duration: 0.8 });
        setTimeout(() => m.openPopup(), 850);
    }
}

// ── Quick send from popup ──────────────────────────────────────────────────
async function quickSend(id, mode) {
    try {
        const r = await fetch(`/lis-portal/send/${id}/quick`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
            body: JSON.stringify({ mode }),
        });
        const data = await r.json();
        if (data.success) {
            deviceData[id].last_sent_mode = mode;
            deviceData[id].last_sent_at   = new Date().toISOString();
            markers[id].setIcon(makeIcon(mode));
            markers[id].setPopupContent(buildPopup(deviceData[id]));
            refreshCards();
        }
        alert(data.success ? `✓ ${mode.toUpperCase()} sent successfully` : `✗ Failed: ${data.message}`);
    } catch(e) { alert('Error: ' + e.message); }
}

// ── Quick send from sidebar cards ─────────────────────────────────────────
document.querySelectorAll('.map-quick').forEach(btn => {
    btn.addEventListener('click', e => {
        e.stopPropagation();
        quickSend(+btn.dataset.id, btn.dataset.mode);
    });
});

// ── Refresh ───────────────────────────────────────────────────────────────
async function refreshCards() {
    try {
        const r    = await fetch('/lis-portal/map/devices');
        const data = await r.json();
        data.forEach(d => {
            deviceData[d.id] = d;
            if (markers[d.id]) {
                markers[d.id].setIcon(makeIcon(d.last_sent_mode));
                markers[d.id].setPopupContent(buildPopup(d));
            }
        });
    } catch(e) {}
}

document.getElementById('refreshBtn').addEventListener('click', () => {
    refreshBtn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>';
    refreshCards().finally(() => {
        refreshBtn.innerHTML = '<i class="bi bi-arrow-clockwise me-1"></i>Refresh';
    });
});
</script>
@endpush
