<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>حمام السباحة: <?= e($pool->name_ar) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/pool/<?= (int) $pool->id ?>/book?date=<?= e($date) ?>" class="btn btn-primary"><i data-lucide="plus" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> حجز جديد</a>
<a href="/pool/config/<?= (int) $pool->id ?>/edit" class="btn btn-outline"><i data-lucide="settings" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> الإعدادات</a>
<a href="/pool" class="btn btn-outline"><i data-lucide="arrow-right" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> العودة</a>
<?php $__template->endSection(); ?>

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

<?php
$lanes = $gridState['lanes'] ?? [];
$timeSlots = $gridState['time_slots'] ?? [];
$cells = $gridState['cells'] ?? [];
$statusColors = [
    'available'    => '#10B981',
    'booked'       => '#3B82F6',
    'in_progress'  => '#F59E0B',
    'maintenance'  => '#EF4444',
];
?>

<!-- Date Selector + Stats -->
<div style="display:flex;gap:15px;margin-bottom:20px;align-items:stretch;">
    <!-- Date Navigation -->
    <div class="card" style="padding:15px;display:flex;align-items:center;gap:10px;flex:0 0 auto;">
        <?php
        $prevDate = date('Y-m-d', strtotime($date . ' -1 day'));
        $nextDate = date('Y-m-d', strtotime($date . ' +1 day'));
        ?>
        <a href="/pool/<?= (int) $pool->id ?>/grid?date=<?= $prevDate ?>" class="btn btn-sm btn-outline">&rarr;</a>
        <form method="GET" action="/pool/<?= (int) $pool->id ?>/grid" style="display:flex;gap:8px;">
            <input type="date" name="date" value="<?= e($date) ?>" class="form-input" style="direction:ltr;font-size:13px;" onchange="this.form.submit()">
        </form>
        <a href="/pool/<?= (int) $pool->id ?>/grid?date=<?= $nextDate ?>" class="btn btn-sm btn-outline">&larr;</a>
        <a href="/pool/<?= (int) $pool->id ?>/grid" class="btn btn-sm btn-outline">اليوم</a>
    </div>

    <!-- Stats -->
    <div class="card" style="padding:15px;flex:1;display:flex;gap:25px;align-items:center;">
        <div style="text-align:center;">
            <div style="font-size:20px;font-weight:700;color:#0D7377;"><?= $utilization['occupancy_pct'] ?? 0 ?>%</div>
            <div style="font-size:11px;color:#6B7280;">الإشغال</div>
        </div>
        <div style="text-align:center;">
            <div style="font-size:20px;font-weight:700;color:#2563EB;"><?= $utilization['total_bookings'] ?? 0 ?></div>
            <div style="font-size:11px;color:#6B7280;">حجز</div>
        </div>
        <div style="text-align:center;">
            <div style="font-size:20px;font-weight:700;color:#D97706;"><?= $utilization['total_swimmers'] ?? 0 ?></div>
            <div style="font-size:11px;color:#6B7280;">سبّاح</div>
        </div>
        <div style="text-align:center;">
            <div style="font-size:20px;font-weight:700;color:#059669;"><?= number_format($utilization['total_revenue'] ?? 0, 0) ?></div>
            <div style="font-size:11px;color:#6B7280;">إيرادات (ج.م)</div>
        </div>
    </div>

    <!-- Legend -->
    <div class="card" style="padding:15px;display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
        <?php foreach ($statusColors as $st => $color): ?>
        <span style="display:flex;align-items:center;gap:4px;font-size:11px;">
            <span style="width:14px;height:14px;border-radius:3px;background:<?= $color ?>;display:inline-block;"></span>
            <?= ['available'=>'متاح','booked'=>'محجوز','in_progress'=>'جاري','maintenance'=>'صيانة'][$st] ?>
        </span>
        <?php endforeach; ?>
    </div>
</div>

<!-- Pool Grid -->
<div class="card" style="padding:0;overflow:auto;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;gap:8px;">
        <i data-lucide="grid-3x3" style="width:18px;height:18px;color:#0D7377;"></i>
        <h3 style="margin:0;color:#0D7377;font-size:15px;">شبكة الحارات × الأوقات</h3>
        <span style="font-size:12px;color:#9CA3AF;margin-right:auto;"><?= e($pool->length_meters) ?>م × <?= e($pool->width_meters) ?>م — <?= count($lanes) ?> حارة</span>
    </div>

    <div style="overflow-x:auto;padding:10px;">
        <table style="width:100%;border-collapse:collapse;min-width:<?= count($timeSlots) * 70 + 100 ?>px;" id="poolGrid">
            <thead>
                <tr>
                    <th style="padding:8px;font-size:12px;color:#6B7280;text-align:right;position:sticky;right:0;background:#fff;z-index:2;border-bottom:2px solid #E5E7EB;min-width:90px;">
                        الحارة
                    </th>
                    <?php foreach ($timeSlots as $slot): ?>
                    <th style="padding:6px 4px;font-size:11px;color:#6B7280;text-align:center;border-bottom:2px solid #E5E7EB;min-width:65px;direction:ltr;">
                        <?= e($slot['start']) ?>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lanes as $lane):
                    $laneNum = (int) $lane['lane_number'];
                ?>
                <tr>
                    <td style="padding:8px;font-size:12px;font-weight:600;color:#1A1A2E;position:sticky;right:0;background:#fff;z-index:1;border-bottom:1px solid #F3F4F6;">
                        <?= e($lane['label_ar'] ?? ('حارة ' . $laneNum)) ?>
                        <div style="font-size:10px;color:#9CA3AF;font-weight:normal;"><?= e($lane['width_meters']) ?>م</div>
                    </td>
                    <?php foreach ($timeSlots as $slot):
                        $slotStart = $slot['start'];
                        $cell = $cells[$laneNum][$slotStart] ?? ['status' => 'available', 'booking' => null];
                        $color = $statusColors[$cell['status']] ?? '#D1D5DB';
                        $booking = $cell['booking'];
                    ?>
                    <td style="padding:3px;border-bottom:1px solid #F3F4F6;"
                        data-lane="<?= $laneNum ?>" data-slot="<?= e($slotStart) ?>" data-status="<?= e($cell['status']) ?>">
                        <div class="grid-cell" style="
                            height:40px;
                            border-radius:6px;
                            background:<?= $color ?>15;
                            border:2px solid <?= $color ?>40;
                            cursor:<?= $cell['status'] === 'available' ? 'pointer' : 'default' ?>;
                            display:flex;
                            align-items:center;
                            justify-content:center;
                            font-size:10px;
                            color:<?= $color ?>;
                            font-weight:600;
                            position:relative;
                            transition:all 0.15s;
                        "
                        <?php if ($booking): ?>
                        title="<?= e(($bookingTypes[$booking['type']] ?? '') . ' — ' . ($booking['booker'] ?? '') . ' (' . $booking['swimmers'] . ' سبّاح)') ?>"
                        <?php else: ?>
                        title="متاح — اضغط للحجز"
                        onclick="quickBook(<?= $laneNum ?>, '<?= e($slotStart) ?>', '<?= e($slot['end']) ?>')"
                        <?php endif; ?>
                        >
                            <?php if ($booking): ?>
                                <?php if ($cell['status'] === 'in_progress'): ?>
                                    <i data-lucide="activity" style="width:12px;height:12px;"></i>
                                <?php elseif ($cell['status'] === 'maintenance'): ?>
                                    <i data-lucide="wrench" style="width:12px;height:12px;"></i>
                                <?php else: ?>
                                    <?= $booking['swimmers'] ?>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </td>
                    <?php endforeach; ?>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Pool Dimensions Visual -->
<div class="card" style="margin-top:20px;padding:20px;">
    <h4 style="margin:0 0 10px;font-size:14px;color:#6B7280;">المخطط التقريبي</h4>
    <div style="position:relative;width:100%;max-width:600px;margin:0 auto;">
        <div style="border:3px solid #0D7377;border-radius:12px;padding:10px;background:#F0FDFA;">
            <div style="display:flex;gap:2px;">
                <?php foreach ($lanes as $lane): ?>
                <div style="flex:1;height:60px;background:#CCFBF1;border:1px dashed #0D737740;border-radius:4px;display:flex;align-items:center;justify-content:center;font-size:11px;color:#0D7377;">
                    <?= (int) $lane['lane_number'] ?>
                </div>
                <?php endforeach; ?>
            </div>
            <div style="text-align:center;margin-top:8px;font-size:11px;color:#6B7280;">
                <?= e($pool->length_meters) ?>م (طول) × <?= e($pool->width_meters) ?>م (عرض)
                <?php if ($pool->depth_shallow || $pool->depth_deep): ?>
                — العمق: <?= e($pool->depth_shallow ?? '?') ?>م إلى <?= e($pool->depth_deep ?? '?') ?>م
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();

    // Auto-refresh every 30 seconds
    setInterval(function() {
        fetch('/api/pool/<?= (int) $pool->id ?>/state?date=<?= e($date) ?>')
            .then(r => r.json())
            .then(data => updateGrid(data))
            .catch(() => {});
    }, 30000);
});

function updateGrid(data) {
    var cells = data.cells || {};
    var statusColors = {available:'#10B981', booked:'#3B82F6', in_progress:'#F59E0B', maintenance:'#EF4444'};

    document.querySelectorAll('#poolGrid td[data-lane]').forEach(function(td) {
        var lane = parseInt(td.getAttribute('data-lane'));
        var slot = td.getAttribute('data-slot');
        if (cells[lane] && cells[lane][slot]) {
            var cell = cells[lane][slot];
            var color = statusColors[cell.status] || '#D1D5DB';
            var div = td.querySelector('.grid-cell');
            if (div) {
                div.style.background = color + '15';
                div.style.borderColor = color + '40';
                div.style.color = color;
                td.setAttribute('data-status', cell.status);
            }
        }
    });
}

function quickBook(lane, startTime, endTime) {
    window.location.href = '/pool/<?= (int) $pool->id ?>/book?date=<?= e($date) ?>&lane=' + lane + '&start=' + startTime + '&end=' + endTime;
}
</script>

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