@extends('layouts.app')
@section('title', 'RTSP Cameras')

@push('scripts')
<script>
function copyText(text, btn) {
    navigator.clipboard.writeText(text).then(() => {
        const orig = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check-lg"></i>';
        setTimeout(() => btn.innerHTML = orig, 2000);
    });
}

function openEdit(camera) {
    const f = document.getElementById('editForm');
    f.action = `/lis-portal/cameras/${camera.id}`;
    f.querySelector('[name=name]').value          = camera.name         ?? '';
    f.querySelector('[name=location]').value      = camera.location     ?? '';
    f.querySelector('[name=rtsp_url]').value      = camera.rtsp_url     ?? '';
    f.querySelector('[name=snapshot_url]').value  = camera.snapshot_url ?? '';
    f.querySelector('[name=username]').value      = camera.username     ?? '';
    f.querySelector('[name=password]').value      = '';
    f.querySelector('[name=chainage]').value      = camera.chainage     ?? '';
    f.querySelector('[name=highway]').value       = camera.highway      ?? '';
    f.querySelector('[name=latitude]').value      = camera.latitude     ?? '';
    f.querySelector('[name=longitude]').value     = camera.longitude    ?? '';
    f.querySelector('[name=notes]').value         = camera.notes        ?? '';
    f.querySelector('[name=is_active]').checked   = !!camera.is_active;
    document.getElementById('editModalLabel').textContent = 'Edit — ' + camera.name;
    new bootstrap.Modal(document.getElementById('editModal')).show();
}

function openSnapshot(cameraId, name) {
    const url = `/lis-portal/cameras/${cameraId}/snapshot`;
    document.getElementById('snapshotImg').src         = url + '?t=' + Date.now();
    document.getElementById('snapshotModalLabel').textContent = name + ' — Snapshot';
    const m = new bootstrap.Modal(document.getElementById('snapshotModal'));
    m.show();
    // Auto-refresh every 5 s while modal is open
    const timer = setInterval(() => {
        const img = document.getElementById('snapshotImg');
        if (img) img.src = url + '?t=' + Date.now();
        else clearInterval(timer);
    }, 5000);
    document.getElementById('snapshotModal').addEventListener('hidden.bs.modal', () => clearInterval(timer), {once:true});
}
</script>
@endpush

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <h5 class="mb-0 fw-bold"><i class="bi bi-camera-video me-2 text-primary"></i>RTSP Cameras</h5>
    <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="bi bi-plus me-1"></i>Add Camera
    </button>
</div>

@if($cameras->isEmpty())
<div class="card">
    <div class="card-body text-center py-5 text-secondary">
        <i class="bi bi-camera-video-off display-6 d-block mb-3 opacity-25"></i>
        No cameras configured yet.
        <div class="mt-2">
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="bi bi-plus me-1"></i>Add your first camera
            </button>
        </div>
    </div>
</div>
@else
<div class="row g-3">
@foreach($cameras as $cam)
<div class="col-md-6 col-xl-4">
<div class="card h-100">
    {{-- Snapshot preview --}}
    @if($cam->snapshot_url)
    <div style="background:#080b10;border-radius:10px 10px 0 0;overflow:hidden;aspect-ratio:16/9;position:relative">
        <img src="{{ route('lis.cameras.snapshot', $cam) }}"
             alt="Snapshot" loading="lazy"
             style="width:100%;height:100%;object-fit:cover"
             onerror="this.parentElement.innerHTML='<div style=\'height:100%;display:flex;align-items:center;justify-content:center;color:#475569\'>&#x25B6;&#xFE0F; No snapshot</div>'">
        <span class="badge bg-danger" style="position:absolute;top:8px;right:8px;font-size:.68rem">
            <i class="bi bi-circle-fill me-1" style="font-size:.45rem"></i>LIVE
        </span>
    </div>
    @else
    <div style="background:#080b10;border-radius:10px 10px 0 0;height:120px;display:flex;align-items:center;justify-content:center;color:#334155;border-bottom:1px solid #1e2433">
        <i class="bi bi-camera-video" style="font-size:2.5rem"></i>
    </div>
    @endif

    <div class="card-body">
        <div class="d-flex align-items-start justify-content-between mb-2">
            <div>
                <div class="fw-semibold">{{ $cam->name }}</div>
                @if($cam->location)
                <div class="text-secondary" style="font-size:.78rem">
                    <i class="bi bi-geo-alt me-1"></i>{{ $cam->location }}
                </div>
                @endif
                @if($cam->chainage)
                <div class="text-secondary" style="font-size:.75rem">
                    <i class="bi bi-sign-turn-right me-1"></i>{{ $cam->chainage }}
                    @if($cam->highway)— {{ $cam->highway }}@endif
                </div>
                @endif
            </div>
            <span class="badge {{ $cam->is_active ? 'bg-success' : 'bg-secondary' }}" style="font-size:.68rem">
                {{ $cam->is_active ? 'Active' : 'Inactive' }}
            </span>
        </div>

        {{-- RTSP URL --}}
        <div class="p-2 mb-3" style="background:#080b10;border-radius:6px;border:1px solid #1e2433">
            <div class="text-secondary mb-1" style="font-size:.68rem;text-transform:uppercase;letter-spacing:.6px">RTSP URL</div>
            <div style="font-family:monospace;font-size:.73rem;color:#7dd3fc;word-break:break-all">
                {{ $cam->rtspDisplay() }}
            </div>
        </div>

        {{-- Actions --}}
        <div class="d-flex flex-wrap gap-1">
            <button class="btn btn-outline-secondary btn-sm"
                    onclick="copyText('{{ addslashes($cam->rtsp_url) }}', this)"
                    title="Copy RTSP URL">
                <i class="bi bi-clipboard"></i>
            </button>
            <a href="vlc://{{ addslashes($cam->rtsp_url) }}" class="btn btn-outline-warning btn-sm"
               title="Open in VLC">
                <i class="bi bi-play-circle me-1"></i>VLC
            </a>
            @if($cam->snapshot_url)
            <button class="btn btn-outline-info btn-sm"
                    onclick="openSnapshot({{ $cam->id }}, '{{ addslashes($cam->name) }}')"
                    title="View snapshot">
                <i class="bi bi-image me-1"></i>Snapshot
            </button>
            @endif
            @if($cam->snapshot_url)
            <a href="{{ $cam->snapshot_url }}" target="_blank" class="btn btn-outline-primary btn-sm"
               title="Open HTTP stream in new tab">
                <i class="bi bi-box-arrow-up-right"></i>
            </a>
            @endif
            <button class="btn btn-outline-secondary btn-sm ms-auto"
                    onclick="openEdit(@json($cam))" title="Edit">
                <i class="bi bi-pencil"></i>
            </button>
            <form method="POST" action="{{ route('lis.cameras.destroy', $cam) }}" class="d-inline"
                  onsubmit="return confirm('Delete {{ addslashes($cam->name) }}?')">
                @csrf @method('DELETE')
                <button class="btn btn-outline-danger btn-sm" title="Delete">
                    <i class="bi bi-trash"></i>
                </button>
            </form>
        </div>
    </div>
</div>
</div>
@endforeach
</div>
@endif

{{-- Add Camera Modal --}}
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content" style="background:#141820;border:1px solid #1e2433">
            <div class="modal-header border-secondary border-opacity-25">
                <h5 class="modal-title">Add Camera</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="{{ route('lis.cameras.store') }}">
                @csrf
                <div class="modal-body">
                    @include('cameras._form')
                </div>
                <div class="modal-footer border-secondary border-opacity-25">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary btn-sm">Add Camera</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Edit Camera Modal --}}
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content" style="background:#141820;border:1px solid #1e2433">
            <div class="modal-header border-secondary border-opacity-25">
                <h5 class="modal-title" id="editModalLabel">Edit Camera</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="" id="editForm">
                @csrf @method('PUT')
                <div class="modal-body">
                    @include('cameras._form')
                </div>
                <div class="modal-footer border-secondary border-opacity-25">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary btn-sm">Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- Snapshot Modal --}}
<div class="modal fade" id="snapshotModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content" style="background:#080b10;border:1px solid #1e2433">
            <div class="modal-header border-secondary border-opacity-25">
                <h5 class="modal-title" id="snapshotModalLabel">Snapshot</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0 text-center" style="background:#000">
                <img id="snapshotImg" src="" alt="Snapshot"
                     style="max-width:100%;max-height:70vh;object-fit:contain"
                     onerror="this.alt='Failed to load snapshot'">
            </div>
            <div class="modal-footer border-secondary border-opacity-25 justify-content-start">
                <small class="text-secondary">Auto-refreshes every 5 seconds</small>
            </div>
        </div>
    </div>
</div>
@endsection
