<?php $__template->layout('Layout.mirror'); ?>
<?php $__template->section('title'); ?>المراية — عرض مباشر<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<?php
$statusConfig = [
    'available'   => ['label' => 'متاح',    'color' => '#10B981', 'bg' => '#ECFDF5', 'icon' => 'check-circle'],
    'booked'      => ['label' => 'محجوز',   'color' => '#3B82F6', 'bg' => '#EFF6FF', 'icon' => 'calendar'],
    'in_progress' => ['label' => 'جاري',    'color' => '#F59E0B', 'bg' => '#FFFBEB', 'icon' => 'play-circle'],
    'maintenance' => ['label' => 'صيانة',   'color' => '#EF4444', 'bg' => '#FEF2F2', 'icon' => 'wrench'],
    'closed'      => ['label' => 'مغلق',    'color' => '#6B7280', 'bg' => '#F9FAFB', 'icon' => 'x-circle'],
];

$typeLabels = [
    'court'  => 'ملعب',
    'pool'   => 'حمام سباحة',
    'gym'    => 'صالة رياضية',
    'track'  => 'مضمار',
    'hall'   => 'قاعة',
    'field'  => 'ملعب كبير',
    'other'  => 'أخرى',
];
?>

<!-- Header Bar -->
<div style="position:fixed;top:0;right:0;left:0;z-index:100;background:linear-gradient(135deg, #0D7377, #14919B);padding:15px 30px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 4px 20px rgba(0,0,0,0.15);">
    <div style="display:flex;align-items:center;gap:12px;">
        <i data-lucide="monitor" style="width:28px;height:28px;color:white;"></i>
        <h1 style="margin:0;font-size:22px;color:white;font-weight:700;">المراية — عرض مباشر</h1>
    </div>
    <div style="display:flex;align-items:center;gap:20px;">
        <!-- Filters -->
        <select id="filterType" style="padding:6px 12px;border-radius:6px;border:none;font-size:13px;background:rgba(255,255,255,0.9);" onchange="applyFilters()">
            <option value="">كل الأنواع</option>
            <?php foreach ($facilityTypes as $ft): ?>
            <option value="<?= e($ft['facility_type']) ?>" <?= $currentType === $ft['facility_type'] ? 'selected' : '' ?>><?= e($typeLabels[$ft['facility_type']] ?? $ft['facility_type']) ?></option>
            <?php endforeach; ?>
        </select>
        <!-- Clock -->
        <div id="liveClock" style="font-size:28px;font-weight:700;color:white;font-family:monospace;direction:ltr;"></div>
        <!-- Status Indicator -->
        <div style="display:flex;align-items:center;gap:6px;">
            <span id="syncDot" style="width:10px;height:10px;border-radius:50%;background:#10B981;animation:pulse 2s infinite;"></span>
            <span style="font-size:11px;color:rgba(255,255,255,0.8);">مباشر</span>
        </div>
    </div>
</div>

<!-- Legend -->
<div style="position:fixed;top:65px;right:0;left:0;z-index:99;background:white;padding:10px 30px;border-bottom:1px solid #E5E7EB;display:flex;gap:20px;align-items:center;">
    <?php foreach ($statusConfig as $st => $cfg): ?>
    <span style="display:flex;align-items:center;gap:6px;font-size:13px;">
        <span style="width:16px;height:16px;border-radius:4px;background:<?= $cfg['color'] ?>;display:inline-block;"></span>
        <?= $cfg['label'] ?>
    </span>
    <?php endforeach; ?>
    <span style="margin-right:auto;font-size:12px;color:#9CA3AF;" id="lastUpdate">آخر تحديث: <?= date('H:i:s') ?></span>
</div>

<!-- Facility Grid -->
<div id="facilityGrid" style="padding:120px 30px 30px;display:grid;grid-template-columns:repeat(auto-fill, minmax(280px, 1fr));gap:20px;min-height:100vh;">
    <?php foreach ($states as $s):
        $cfg = $statusConfig[$s['current_status']] ?? $statusConfig['closed'];
    ?>
    <div class="mirror-card" data-facility-id="<?= $s['facility_id'] ?>" style="
        border-radius:16px;
        border:3px solid <?= $cfg['color'] ?>40;
        background:<?= $cfg['bg'] ?>;
        padding:20px;
        transition:all 0.3s;
        position:relative;
        overflow:hidden;
    ">
        <!-- Status indicator stripe -->
        <div style="position:absolute;top:0;right:0;left:0;height:5px;background:<?= $cfg['color'] ?>;"></div>

        <!-- Header -->
        <div style="display:flex;align-items:start;justify-content:space-between;margin-bottom:12px;">
            <div>
                <h3 style="margin:0 0 4px;font-size:18px;font-weight:700;color:#1A1A2E;"><?= e($s['name_ar']) ?></h3>
                <span style="font-size:12px;color:#6B7280;"><?= e($typeLabels[$s['type']] ?? $s['type']) ?></span>
            </div>
            <div style="width:44px;height:44px;border-radius:12px;background:<?= $cfg['color'] ?>20;display:flex;align-items:center;justify-content:center;">
                <i data-lucide="<?= $cfg['icon'] ?>" style="width:22px;height:22px;color:<?= $cfg['color'] ?>;"></i>
            </div>
        </div>

        <!-- Status Badge -->
        <div style="margin-bottom:12px;">
            <span style="padding:5px 14px;border-radius:20px;font-size:14px;font-weight:700;background:<?= $cfg['color'] ?>20;color:<?= $cfg['color'] ?>;">
                <?= $cfg['label'] ?>
            </span>
        </div>

        <!-- Current/Next Info -->
        <?php if ($s['current_booking']): ?>
        <div style="padding:10px;background:white;border-radius:8px;margin-bottom:8px;font-size:13px;">
            <div style="color:#6B7280;font-size:11px;margin-bottom:2px;">الآن:</div>
            <div style="color:#1A1A2E;font-weight:600;"><?= e($s['current_booking']['purpose'] ?: 'حجز') ?></div>
            <div style="color:#6B7280;direction:ltr;text-align:right;font-size:12px;"><?= e($s['current_booking']['start_time']) ?> — <?= e($s['current_booking']['end_time']) ?></div>
        </div>
        <?php endif; ?>

        <?php if ($s['next_booking']): ?>
        <div style="padding:8px 10px;background:white;border-radius:8px;font-size:12px;display:flex;justify-content:space-between;align-items:center;">
            <span style="color:#6B7280;">التالي: <?= e($s['next_booking']['purpose'] ?: 'حجز') ?></span>
            <?php if ($s['time_until_next']): ?>
            <span style="font-weight:600;color:#D97706;">بعد <?= e($s['time_until_next']) ?></span>
            <?php endif; ?>
        </div>
        <?php elseif ($s['current_status'] === 'available'): ?>
        <div style="padding:8px 10px;background:white;border-radius:8px;font-size:13px;text-align:center;color:#059669;font-weight:600;">
            لا يوجد حجوزات قادمة
        </div>
        <?php endif; ?>

        <!-- Footer -->
        <div style="margin-top:12px;display:flex;justify-content:space-between;font-size:11px;color:#9CA3AF;">
            <span>حجوزات اليوم: <?= $s['today_count'] ?></span>
            <?php if ($s['capacity']): ?>
            <span>سعة: <?= $s['capacity'] ?></span>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<?php if (empty($states)): ?>
<div style="padding:120px 30px;text-align:center;">
    <i data-lucide="monitor-off" style="width:64px;height:64px;color:#D1D5DB;margin-bottom:20px;"></i>
    <h2 style="color:#6B7280;">لا توجد مرافق نشطة</h2>
</div>
<?php endif; ?>

<style>
@keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.4; }
}
body { overflow-x: hidden; }
.mirror-card:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(0,0,0,0.1); }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();
    updateClock();
    setInterval(updateClock, 1000);
    setInterval(refreshMirror, 30000);
});

function updateClock() {
    var now = new Date();
    var h = String(now.getHours()).padStart(2, '0');
    var m = String(now.getMinutes()).padStart(2, '0');
    var s = String(now.getSeconds()).padStart(2, '0');
    document.getElementById('liveClock').textContent = h + ':' + m + ':' + s;
}

function refreshMirror() {
    var type = document.getElementById('filterType').value;
    var url = '/api/mirror/state?type=' + encodeURIComponent(type);

    fetch(url)
        .then(r => r.json())
        .then(data => {
            document.getElementById('lastUpdate').textContent = 'آخر تحديث: ' + data.time;
            updateCards(data.states);
        })
        .catch(() => {
            document.getElementById('syncDot').style.background = '#EF4444';
        });
}

function updateCards(states) {
    var statusConfig = {
        available:   {label:'متاح',  color:'#10B981', bg:'#ECFDF5'},
        booked:      {label:'محجوز', color:'#3B82F6', bg:'#EFF6FF'},
        in_progress: {label:'جاري',  color:'#F59E0B', bg:'#FFFBEB'},
        maintenance: {label:'صيانة', color:'#EF4444', bg:'#FEF2F2'},
        closed:      {label:'مغلق',  color:'#6B7280', bg:'#F9FAFB'},
    };

    states.forEach(function(s) {
        var card = document.querySelector('[data-facility-id="' + s.facility_id + '"]');
        if (!card) return;
        var cfg = statusConfig[s.current_status] || statusConfig.closed;
        card.style.borderColor = cfg.color + '40';
        card.style.background = cfg.bg;
        var stripe = card.querySelector('div');
        if (stripe) stripe.style.background = cfg.color;
    });

    document.getElementById('syncDot').style.background = '#10B981';
}

function applyFilters() {
    var type = document.getElementById('filterType').value;
    window.location.href = '/mirror' + (type ? '?type=' + encodeURIComponent(type) : '');
}
</script>

<?php $__template->endSection(); ?>
