<?php
use App\Modules\FacilityGrids\Models\FacilityZoneSchedule;
$__template->layout('Layout.main');
$dayNames = FacilityZoneSchedule::getDayNames();
$activityTypes = FacilityZoneSchedule::getActivityTypes();
$rows = (int) $grid->rows_count;
$cols = (int) $grid->cols_count;
$zones = $state['zones'] ?? [];
$schedules = $state['schedules'] ?? [];
$currentTime = $state['time'] ?? date('H:i');
$currentHour = (int) substr($currentTime, 0, 2);

// Operating hours (6 AM to 10 PM)
$startHour = 6;
$endHour = 22;

// Can user edit? (permission-based)
$canEdit = true; // Controller already authorized
$planMonth = $_GET['month'] ?? date('Y-m');
?>
<?php $__template->section('title'); ?>مراية — <?= e($grid->name_ar) ?><?php $__template->endSection(); ?>

<?php $__template->section('styles'); ?>
<style>
.hour-tabs {
    display: flex; gap: 0; overflow-x: auto; border-bottom: 2px solid #E5E7EB;
    padding-bottom: 0; margin-bottom: 0; scrollbar-width: thin;
}
.hour-tab {
    padding: 10px 16px; font-size: 13px; font-weight: 600;
    cursor: pointer; border: none; background: white; color: #6B7280;
    border-bottom: 3px solid transparent; white-space: nowrap;
    transition: all .15s;
}
.hour-tab:hover { color: #1e3a5f; background: #F0FDFA; }
.hour-tab.active { color: #1e3a5f; border-bottom-color: #1e3a5f; background: #F0FDFA; }
.hour-tab.has-schedule { position: relative; }
.hour-tab.has-schedule::after {
    content: ''; position: absolute; top: 6px; left: 6px;
    width: 6px; height: 6px; border-radius: 50%; background: #10B981;
}

.pool-grid {
    display: grid; gap: 6px; direction: ltr;
}
.pool-box {
    border-radius: 10px; border: 2px solid #E5E7EB; padding: 10px;
    min-height: 110px; position: relative; cursor: pointer;
    transition: all .2s; background: white;
}
.pool-box:hover { box-shadow: 0 4px 16px rgba(0,0,0,.1); transform: translateY(-1px); }
.pool-box.occupied {
    border-color: var(--box-color, #3B82F6);
    background: color-mix(in srgb, var(--box-color, #3B82F6) 6%, white);
}
.pool-box.available { border-color: #D1FAE5; background: #F0FDF4; border-style: dashed; }
.pool-box .box-header {
    display: flex; align-items: center; justify-content: space-between;
    margin-bottom: 6px; gap: 6px;
}
.pool-box .box-coach { font-size: 12px; font-weight: 700; color: #111; }
.pool-box .box-meta { font-size: 10px; color: #6B7280; margin-top: 2px; }
.pool-box .box-badge {
    font-size: 9px; font-weight: 700; padding: 2px 6px;
    border-radius: 4px; display: inline-block;
}
.pool-box .box-badge.male { background: #DBEAFE; color: #1D4ED8; }
.pool-box .box-badge.female { background: #FCE7F3; color: #BE185D; }
.pool-box .trainee-list { margin-top: 8px; border-top: 1px solid #F3F4F6; padding-top: 6px; }
.pool-box .trainee-item {
    display: flex; align-items: center; justify-content: space-between;
    font-size: 11px; padding: 3px 0; color: #374151;
}
.pool-box .trainee-item .remove-btn {
    color: #DC2626; cursor: pointer; opacity: 0; transition: opacity .15s;
    background: none; border: none; padding: 0;
}
.pool-box:hover .trainee-item .remove-btn { opacity: 1; }
.pool-box .box-count {
    position: absolute; top: -8px; right: -8px;
    background: #1F2937; color: white; border-radius: 50%;
    width: 22px; height: 22px; font-size: 10px; font-weight: 700;
    display: flex; align-items: center; justify-content: center;
}
.pool-box .box-empty {
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    height: 100%; color: #9CA3AF; font-size: 12px;
}

.row-label, .col-label {
    display: flex; align-items: center; justify-content: center;
    font-size: 12px; font-weight: 700; color: #374151;
    background: #F9FAFB; border-radius: 6px; padding: 8px 4px;
    cursor: pointer; transition: background .15s;
}
.row-label:hover, .col-label:hover { background: #E0F2FE; }
.row-label.selected, .col-label.selected { background: #1e3a5f; color: white; }

.pool-box.selected {
    border-color: #1e3a5f !important; box-shadow: 0 0 0 3px rgba(30,58,95,.25) !important;
    background: #F0FDFA !important;
}

.selection-toolbar {
    display: flex; align-items: center; gap: 8px; margin-bottom: 12px;
    padding: 10px 16px; background: #F9FAFB; border-radius: 10px; border: 1px solid #E5E7EB;
}
.sel-mode-btn {
    padding: 6px 14px; border-radius: 6px; border: 1px solid #D1D5DB;
    font-size: 12px; font-weight: 600; cursor: pointer; background: white;
    color: #374151; transition: all .15s; display: inline-flex; align-items: center; gap: 4px;
}
.sel-mode-btn:hover { border-color: #1e3a5f; color: #1e3a5f; }
.sel-mode-btn.active { background: #1e3a5f; color: white; border-color: #1e3a5f; }

.selection-actions {
    display: none; align-items: center; gap: 8px; margin-right: auto;
}
.selection-actions.visible { display: flex; }
.sel-count { font-size: 12px; font-weight: 700; color: #1e3a5f; }


.plan-header {
    display: flex; align-items: center; justify-content: space-between;
    flex-wrap: wrap; gap: 12px; margin-bottom: 16px;
    padding: 16px 20px; background: white; border-radius: 12px;
    border: 1px solid #E5E7EB;
}

.month-nav { display: flex; align-items: center; gap: 8px; }
.month-nav button {
    background: #F3F4F6; border: none; border-radius: 6px;
    padding: 6px 10px; cursor: pointer; font-size: 14px; color: #374151;
}
.month-nav button:hover { background: #E5E7EB; }
.month-nav .month-label { font-size: 16px; font-weight: 800; color: #111; min-width: 140px; text-align: center; }

/* Modal */
.modal-overlay {
    display: none; position: fixed; inset: 0; background: rgba(0,0,0,.4);
    z-index: 1000; align-items: center; justify-content: center;
}
.modal-overlay.active { display: flex; }
.modal-box {
    background: white; border-radius: 16px; padding: 24px;
    max-width: 480px; width: 90%; max-height: 90vh; overflow-y: auto;
    box-shadow: 0 20px 60px rgba(0,0,0,.2);
}
.modal-box h3 { margin: 0 0 16px; font-size: 16px; font-weight: 800; }
.modal-box label { display: block; font-size: 12px; font-weight: 600; color: #374151; margin-bottom: 4px; }
.modal-box input, .modal-box select { width: 100%; padding: 9px 12px; border: 1px solid #D1D5DB; border-radius: 8px; font-size: 13px; margin-bottom: 12px; }
.modal-box .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }

/* Drag */
.pool-box.drag-over { border-color: #F59E0B !important; background: #FFFBEB !important; }
.trainee-item[draggable="true"] { cursor: grab; }
.trainee-item[draggable="true"]:active { cursor: grabbing; }
</style>
<?php $__template->endSection(); ?>

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

<!-- Plan Header -->
<div class="plan-header">
    <div style="display:flex;align-items:center;gap:12px;">
        <a href="/facility-grids" style="color:#6B7280;text-decoration:none;font-size:13px;"><i data-lucide="arrow-right" style="width:14px;height:14px;vertical-align:middle;"></i></a>
        <div>
            <h2 style="margin:0;font-size:20px;font-weight:800;">مراية <?= e($grid->name_ar) ?></h2>
            <span style="font-size:12px;color:#6B7280;"><?= $rows ?> حارات × <?= $cols ?> أقسام</span>
        </div>
    </div>

    <div class="month-nav">
        <button onclick="changeMonth(-1)" title="الشهر السابق"><i data-lucide="chevron-right" style="width:16px;height:16px;"></i></button>
        <span class="month-label" id="monthLabel"><?= arabic_date($planMonth . '-01', 'F Y') ?></span>
        <button onclick="changeMonth(1)" title="الشهر التالي"><i data-lucide="chevron-left" style="width:16px;height:16px;"></i></button>
    </div>

    <div style="display:flex;align-items:center;gap:8px;">
        <input type="date" id="gridDate" value="<?= e($date) ?>" style="padding:8px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:13px;" onchange="reloadForDate()">
        <a href="/facility-grids/<?= (int) $grid->id ?>/schedules" class="btn btn-outline" style="font-size:12px;padding:8px 12px;">
            <i data-lucide="list" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> كل الجداول
        </a>
    </div>
</div>

<!-- Hour Tabs -->
<div class="card" style="padding:0;margin-bottom:16px;">
    <div class="hour-tabs" id="hourTabs">
        <?php for ($h = $startHour; $h < $endHour; $h++):
            $hStart = sprintf('%02d:00', $h);
            $hEnd = sprintf('%02d:00', $h + 1);
            $hasSchedule = false;
            foreach ($schedules as $sch) {
                if ($sch['start'] === substr($hStart, 0, 5)) { $hasSchedule = true; break; }
            }
            $isActive = ($h === $currentHour);
        ?>
        <button class="hour-tab <?= $isActive ? 'active' : '' ?> <?= $hasSchedule ? 'has-schedule' : '' ?>"
                data-hour="<?= $h ?>"
                onclick="selectHour(<?= $h ?>)">
            <?= $hStart ?>–<?= $hEnd ?>
        </button>
        <?php endfor; ?>
    </div>
</div>

<!-- Pool Grid for Selected Hour -->
<div class="card" style="padding:20px;" id="gridCard">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
        <div style="font-size:14px;font-weight:700;color:#374151;">
            <i data-lucide="clock" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;color:#6B7280;"></i>
            <span id="selectedHourLabel"><?= sprintf('%02d:00', $currentHour) ?>–<?= sprintf('%02d:00', $currentHour + 1) ?></span>
        </div>
        <div style="display:flex;gap:8px;font-size:11px;color:#6B7280;">
            <span><span style="display:inline-block;width:10px;height:10px;border-radius:3px;background:#F0FDF4;border:1px dashed #86EFAC;vertical-align:middle;margin-left:4px;"></span>متاح</span>
            <span><span style="display:inline-block;width:10px;height:10px;border-radius:3px;background:#DBEAFE;border:1px solid #3B82F6;vertical-align:middle;margin-left:4px;"></span>مشغول</span>
            <span><span style="display:inline-block;width:10px;height:10px;border-radius:3px;background:#F0FDFA;border:2px solid #1e3a5f;vertical-align:middle;margin-left:4px;"></span>محدد</span>
            <span style="color:#1F2937;font-weight:600;">خانة: ٥ | حارة طولية: ٨ | حارة عرضية: ٦</span>
        </div>
    </div>

    <!-- Selection Mode Toolbar -->
    <div class="selection-toolbar">
        <span style="font-size:12px;color:#6B7280;margin-left:8px;">
            <i data-lucide="mouse-pointer-2" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i>
            وضع التحديد:
        </span>
        <button class="sel-mode-btn active" data-mode="cells" onclick="setSelectionMode('cells')">
            <i data-lucide="grid-3x3" style="width:13px;height:13px;"></i> خانات
        </button>
        <button class="sel-mode-btn" data-mode="row" onclick="setSelectionMode('row')">
            <i data-lucide="arrow-left-right" style="width:13px;height:13px;"></i> حارة كاملة (طولي)
        </button>
        <button class="sel-mode-btn" data-mode="column" onclick="setSelectionMode('column')">
            <i data-lucide="arrow-up-down" style="width:13px;height:13px;"></i> حارة كاملة (عرضي)
        </button>
        <button class="sel-mode-btn" data-mode="all" onclick="setSelectionMode('all')">
            <i data-lucide="maximize-2" style="width:13px;height:13px;"></i> الكل
        </button>

        <div class="selection-actions" id="selActions">
            <span class="sel-count" id="selCount">0 محدد</span>
            <button class="btn btn-primary" style="font-size:12px;padding:6px 14px;" onclick="openMultiBoxModal()">
                <i data-lucide="edit-3" style="width:13px;height:13px;vertical-align:middle;margin-left:4px;"></i> تعيين المحدد
            </button>
            <button class="btn btn-outline" style="font-size:12px;padding:6px 14px;" onclick="clearSelection()">
                <i data-lucide="x" style="width:13px;height:13px;vertical-align:middle;margin-left:4px;"></i> إلغاء
            </button>
        </div>
    </div>

    <div class="pool-grid" id="poolGrid" style="grid-template-columns: 50px repeat(<?= $cols ?>, 1fr);">
        <!-- Corner (select all) -->
        <div class="row-label" onclick="selectAll()" title="تحديد الكل" style="cursor:pointer;font-size:10px;">الكل</div>
        <!-- Column Headers -->
        <?php for ($c = 0; $c < $cols; $c++): ?>
        <div class="col-label" data-col="<?= $c ?>" onclick="selectColumn(<?= $c ?>)"><?= e($grid->col_label_ar ?? 'قسم') ?> <?= $c + 1 ?></div>
        <?php endfor; ?>

        <!-- Rows -->
        <?php for ($r = 0; $r < $rows; $r++): ?>
            <div class="row-label" data-row="<?= $r ?>" onclick="selectRow(<?= $r ?>)"><?= e($grid->row_label_ar ?? 'حارة') ?> <?= $r + 1 ?></div>
            <?php for ($c = 0; $c < $cols; $c++):
                $key = $r . ':' . $c;
                $zone = $zones[$key] ?? null;
                $status = $zone['status'] ?? 'available';
                $schedule = $zone['schedule'] ?? null;
                $trainees = $zone['trainees'] ?? [];
                $traineeCount = $zone['trainee_count'] ?? 0;
                $cellColor = $schedule['color'] ?? '#3B82F6';
                $maxOcc = $zone['max_occupants'] ?? 5;

                // Check if this is part of active schedule for current hour
                $isCurrentHour = false;
                if ($schedule) {
                    $schStart = (int) substr($schedule['time'], 0, 2);
                    $isCurrentHour = ($schStart === $currentHour);
                }
            ?>
            <div class="pool-box <?= ($status === 'occupied' && $isCurrentHour) ? 'occupied' : 'available' ?>"
                 style="--box-color:<?= e($cellColor) ?>;"
                 data-row="<?= $r ?>" data-col="<?= $c ?>"
                 data-zone-id="<?= $zone['zone_id'] ?? 0 ?>"
                 ondragover="dragOver(event)" ondragleave="dragLeave(event)" ondrop="dropTrainee(event, <?= $zone['zone_id'] ?? 0 ?>)"
                 onclick="handleBoxClick(<?= $r ?>, <?= $c ?>, this, event)">

                <?php if ($status === 'occupied' && $isCurrentHour && $schedule): ?>
                    <?php if ($traineeCount > 0): ?>
                    <span class="box-count"><?= $traineeCount ?>/<?= $maxOcc ?></span>
                    <?php endif; ?>

                    <div class="box-header">
                        <span class="box-coach"><?= e($schedule['coach'] ?: $schedule['academy'] ?: $schedule['name']) ?></span>
                        <span class="box-badge <?= e($schedule['gender'] ?? 'male') ?>"><?= ($schedule['gender'] ?? 'male') === 'female' ? 'بنات' : 'ولاد' ?></span>
                    </div>
                    <div class="box-meta">
                        <?php if (!empty($schedule['age_group'])): ?><?= e($schedule['age_group']) ?> • <?php endif; ?>
                        <?= e($activityTypes[$schedule['activity_type'] ?? ''] ?? '') ?>
                    </div>

                    <?php if (!empty($trainees)): ?>
                    <div class="trainee-list">
                        <?php foreach ($trainees as $t): ?>
                        <div class="trainee-item" draggable="true" data-trainee-id="<?= $t['id'] ?>" ondragstart="dragStart(event, <?= $t['id'] ?>)">
                            <span><?= e($t['name']) ?></span>
                            <button class="remove-btn" onclick="event.stopPropagation();removeTrainee(<?= $t['id'] ?>)" title="إزالة">
                                <i data-lucide="x" style="width:12px;height:12px;"></i>
                            </button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="box-empty">
                        <i data-lucide="plus-circle" style="width:20px;height:20px;margin-bottom:4px;"></i>
                        <span>متاح</span>
                    </div>
                <?php endif; ?>
            </div>
            <?php endfor; ?>
        <?php endfor; ?>
    </div>
</div>

<!-- Box Edit/Create Modal -->
<div class="modal-overlay" id="boxModal">
    <div class="modal-box">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;">
            <h3 id="modalTitle">تعيين خانة</h3>
            <button onclick="closeModal()" style="background:none;border:none;cursor:pointer;color:#6B7280;"><i data-lucide="x" style="width:20px;height:20px;"></i></button>
        </div>

        <form id="boxForm" onsubmit="saveBox(event)">
            <input type="hidden" name="zone_selection_type" value="cells">
            <input type="hidden" name="zone_selection_json" id="modalSelJson" value="[]">
            <input type="hidden" name="plan_month" value="<?= e($planMonth) ?>">

            <div class="form-row">
                <div>
                    <label>اسم المدرب / الأكاديمية *</label>
                    <input type="text" name="schedule_name" id="modalName" required placeholder="مثال: ك. أحمد">
                </div>
                <div>
                    <label>نوع النشاط</label>
                    <select name="activity_type" id="modalActivity">
                        <?php foreach ($activityTypes as $k => $v): ?>
                        <option value="<?= e($k) ?>"><?= e($v) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div>
                    <label>الفئة العمرية</label>
                    <input type="text" name="age_group" id="modalAge" placeholder="مثال: 6-9 سنوات">
                </div>
                <div>
                    <label>الجنس *</label>
                    <select name="gender" id="modalGender">
                        <option value="male">ولاد</option>
                        <option value="female">بنات</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div>
                    <label>اليوم *</label>
                    <select name="day_of_week" id="modalDay">
                        <?php foreach ($dayNames as $d => $name): ?>
                        <option value="<?= $d ?>" <?= $d === (int) date('w', strtotime($date)) ? 'selected' : '' ?>><?= e($name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>اللون</label>
                    <input type="color" name="color" id="modalColor" value="#3B82F6" style="height:38px;padding:4px;">
                </div>
            </div>

            <input type="hidden" name="start_time" id="modalStart">
            <input type="hidden" name="end_time" id="modalEnd">
            <input type="hidden" name="effective_from" value="<?= e($planMonth) ?>-01">
            <input type="hidden" name="coach_name" id="modalCoachName">

            <div style="margin-top:16px;padding-top:12px;border-top:1px solid #E5E7EB;">
                <label>إضافة متدرب</label>
                <div style="display:flex;gap:8px;">
                    <input type="text" id="newTraineeName" placeholder="اسم المتدرب" style="flex:1;margin-bottom:0;">
                    <button type="button" onclick="addTraineeToBox()" class="btn btn-outline" style="padding:8px 14px;font-size:12px;margin-bottom:0;">
                        <i data-lucide="user-plus" style="width:14px;height:14px;"></i>
                    </button>
                </div>
            </div>

            <div style="display:flex;gap:12px;margin-top:20px;">
                <button type="submit" class="btn btn-primary" style="flex:1;padding:10px;">
                    <i data-lucide="save" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> حفظ
                </button>
                <button type="button" onclick="closeModal()" class="btn btn-outline" style="padding:10px 20px;">إلغاء</button>
            </div>
        </form>
    </div>
</div>

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

<?php $__template->section('scripts'); ?>
<script>
const GRID_ID = <?= (int) $grid->id ?>;
const ROWS = <?= $rows ?>;
const COLS = <?= $cols ?>;
const CSRF = document.querySelector('meta[name="csrf-token"]')?.content || '';
const PLAN_MONTH = '<?= e($planMonth) ?>';
let selectedHour = <?= $currentHour ?>;
let gridState = <?= json_encode($state, JSON_UNESCAPED_UNICODE) ?>;
let draggedTraineeId = null;

// ─── SELECTION STATE ───
let selectionMode = 'cells'; // cells, row, column, all
let selectedCells = []; // [{row, col}, ...]

function setSelectionMode(mode) {
    selectionMode = mode;
    clearSelection();
    document.querySelectorAll('.sel-mode-btn').forEach(b => b.classList.remove('active'));
    document.querySelector(`.sel-mode-btn[data-mode="${mode}"]`)?.classList.add('active');

    if (mode === 'all') {
        selectAll();
    }
}

function handleBoxClick(row, col, el, event) {
    if (event && event.target.closest('.remove-btn')) return;
    if (event && event.target.closest('.trainee-item[draggable]')) return;

    if (selectionMode === 'cells') {
        toggleCell(row, col);
    } else if (selectionMode === 'row') {
        selectRow(row);
    } else if (selectionMode === 'column') {
        selectColumn(col);
    } else if (selectionMode === 'all') {
        selectAll();
    }
}

function toggleCell(row, col) {
    const idx = selectedCells.findIndex(c => c.row === row && c.col === col);
    if (idx >= 0) {
        selectedCells.splice(idx, 1);
    } else {
        selectedCells.push({row, col});
    }
    updateSelectionVisuals();
}

function selectRow(row) {
    // Toggle: if entire row already selected, deselect it
    const rowCells = [];
    for (let c = 0; c < COLS; c++) rowCells.push({row, col: c});

    const allSelected = rowCells.every(rc => selectedCells.some(s => s.row === rc.row && s.col === rc.col));
    if (allSelected) {
        selectedCells = selectedCells.filter(s => s.row !== row);
    } else {
        // Remove any cells from this row first, then add all
        selectedCells = selectedCells.filter(s => s.row !== row);
        selectedCells.push(...rowCells);
    }
    updateSelectionVisuals();
}

function selectColumn(col) {
    const colCells = [];
    for (let r = 0; r < ROWS; r++) colCells.push({row: r, col});

    const allSelected = colCells.every(rc => selectedCells.some(s => s.row === rc.row && s.col === rc.col));
    if (allSelected) {
        selectedCells = selectedCells.filter(s => s.col !== col);
    } else {
        selectedCells = selectedCells.filter(s => s.col !== col);
        selectedCells.push(...colCells);
    }
    updateSelectionVisuals();
}

function selectAll() {
    if (selectedCells.length === ROWS * COLS) {
        clearSelection();
        return;
    }
    selectedCells = [];
    for (let r = 0; r < ROWS; r++) {
        for (let c = 0; c < COLS; c++) {
            selectedCells.push({row: r, col: c});
        }
    }
    updateSelectionVisuals();
}

function clearSelection() {
    selectedCells = [];
    updateSelectionVisuals();
}

function updateSelectionVisuals() {
    // Update boxes
    document.querySelectorAll('.pool-box').forEach(box => {
        const r = parseInt(box.dataset.row);
        const c = parseInt(box.dataset.col);
        const isSelected = selectedCells.some(s => s.row === r && s.col === c);
        box.classList.toggle('selected', isSelected);
    });

    // Update row labels
    document.querySelectorAll('.row-label[data-row]').forEach(label => {
        const r = parseInt(label.dataset.row);
        const rowFull = Array.from({length: COLS}, (_, c) => c).every(c =>
            selectedCells.some(s => s.row === r && s.col === c)
        );
        label.classList.toggle('selected', rowFull);
    });

    // Update col labels
    document.querySelectorAll('.col-label[data-col]').forEach(label => {
        const c = parseInt(label.dataset.col);
        const colFull = Array.from({length: ROWS}, (_, r) => r).every(r =>
            selectedCells.some(s => s.row === r && s.col === c)
        );
        label.classList.toggle('selected', colFull);
    });

    // Update action bar
    const actions = document.getElementById('selActions');
    const count = selectedCells.length;
    if (count > 0) {
        actions.classList.add('visible');
        document.getElementById('selCount').textContent = count + ' محدد';
    } else {
        actions.classList.remove('visible');
    }
}

function getSelectionType() {
    if (selectedCells.length === 0) return 'cells';
    if (selectedCells.length === ROWS * COLS) return 'all';

    // Check if it's a full row
    const rows = [...new Set(selectedCells.map(c => c.row))];
    if (rows.length === 1 && selectedCells.length === COLS) return 'row';

    // Check if it's full column(s)
    const cols = [...new Set(selectedCells.map(c => c.col))];
    if (cols.length === 1 && selectedCells.length === ROWS) return 'column';

    // Check if it's multiple full rows
    const allFullRows = rows.every(r =>
        Array.from({length: COLS}, (_, c) => c).every(c =>
            selectedCells.some(s => s.row === r && s.col === c)
        )
    );
    if (allFullRows && selectedCells.length === rows.length * COLS) return 'row';

    // Check if it's multiple full columns
    const allFullCols = cols.every(c =>
        Array.from({length: ROWS}, (_, r) => r).every(r =>
            selectedCells.some(s => s.row === r && s.col === c)
        )
    );
    if (allFullCols && selectedCells.length === cols.length * ROWS) return 'column';

    return 'cells';
}

function openMultiBoxModal() {
    if (selectedCells.length === 0) return;

    const selType = getSelectionType();
    document.querySelector('[name="zone_selection_type"]').value = selType;
    document.getElementById('modalSelJson').value = JSON.stringify(selectedCells);
    document.getElementById('modalStart').value = String(selectedHour).padStart(2,'0') + ':00';
    document.getElementById('modalEnd').value = String(selectedHour + 1).padStart(2,'0') + ':00';

    const count = selectedCells.length;
    let maxLabel = '';
    if (selType === 'row') maxLabel = ' (اقصى ٨ متدرب)';
    else if (selType === 'column') maxLabel = ' (اقصى ٦ متدرب)';
    else if (selType === 'all') maxLabel = ' (الحوض كامل)';
    else maxLabel = count > 1 ? ` (${count} خانات)` : '';

    document.getElementById('modalTitle').textContent = 'تعيين' + maxLabel;
    document.getElementById('boxForm').reset();
    document.querySelector('[name="zone_selection_type"]').value = selType;
    document.getElementById('modalSelJson').value = JSON.stringify(selectedCells);
    document.getElementById('modalStart').value = String(selectedHour).padStart(2,'0') + ':00';
    document.getElementById('modalEnd').value = String(selectedHour + 1).padStart(2,'0') + ':00';

    document.getElementById('boxModal').classList.add('active');
}

// ─── HOUR SELECTION ───
function selectHour(h) {
    selectedHour = h;
    document.querySelectorAll('.hour-tab').forEach(t => t.classList.remove('active'));
    document.querySelector(`.hour-tab[data-hour="${h}"]`)?.classList.add('active');
    document.getElementById('selectedHourLabel').textContent =
        String(h).padStart(2,'0') + ':00–' + String(h+1).padStart(2,'0') + ':00';
    clearSelection();
    refreshGrid();
}

function refreshGrid() {
    const date = document.getElementById('gridDate').value;
    fetch(`/api/facility-grids/${GRID_ID}/state?date=${date}&time=${String(selectedHour).padStart(2,'0')}:30`)
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                gridState = data.data;
                renderPoolGrid();
            }
        });
}

function renderPoolGrid() {
    const zones = gridState.zones || {};
    document.querySelectorAll('.pool-box').forEach(box => {
        const r = parseInt(box.dataset.row);
        const c = parseInt(box.dataset.col);
        const key = r + ':' + c;
        const zone = zones[key];
        if (!zone) return;

        const sch = zone.schedule;
        const isOccupied = zone.status === 'occupied' && sch;
        const isSelected = selectedCells.some(s => s.row === r && s.col === c);

        box.className = 'pool-box ' + (isOccupied ? 'occupied' : 'available') + (isSelected ? ' selected' : '');
        if (isOccupied) box.style.setProperty('--box-color', sch.color || '#3B82F6');

        let html = '';
        if (isOccupied) {
            const count = zone.trainee_count || 0;
            const max = zone.max_occupants || 5;
            if (count > 0) html += `<span class="box-count">${count}/${max}</span>`;
            html += `<div class="box-header">
                <span class="box-coach">${sch.coach || sch.academy || sch.name}</span>
                <span class="box-badge ${sch.gender || 'male'}">${(sch.gender||'male')==='female'?'بنات':'ولاد'}</span>
            </div>`;
            html += `<div class="box-meta">${sch.age_group ? sch.age_group + ' • ' : ''}${sch.activity_type||''}</div>`;
            if (zone.trainees && zone.trainees.length) {
                html += '<div class="trainee-list">';
                zone.trainees.forEach(t => {
                    html += `<div class="trainee-item" draggable="true" data-trainee-id="${t.id}" ondragstart="dragStart(event,${t.id})">
                        <span>${t.name}</span>
                        <button class="remove-btn" onclick="event.stopPropagation();removeTrainee(${t.id})" title="إزالة">
                            <i data-lucide="x" style="width:12px;height:12px;"></i>
                        </button>
                    </div>`;
                });
                html += '</div>';
            }
        } else {
            html = '<div class="box-empty"><i data-lucide="plus-circle" style="width:20px;height:20px;margin-bottom:4px;"></i><span>متاح</span></div>';
        }
        box.innerHTML = html;
    });
    lucide.createIcons();
}

// ─── MONTH NAVIGATION ───
function changeMonth(delta) {
    const parts = PLAN_MONTH.split('-');
    let y = parseInt(parts[0]), m = parseInt(parts[1]) + delta;
    if (m > 12) { m = 1; y++; }
    if (m < 1) { m = 12; y--; }
    const newMonth = y + '-' + String(m).padStart(2, '0');
    window.location.href = `/facility-grids/${GRID_ID}?month=${newMonth}&date=${newMonth}-01`;
}

function reloadForDate() {
    const date = document.getElementById('gridDate').value;
    window.location.href = `/facility-grids/${GRID_ID}?date=${date}&month=${PLAN_MONTH}`;
}

// ─── BOX MODAL (single cell click in cells mode when nothing selected) ───
function openBoxModal(row, col) {
    const key = row + ':' + col;
    const zone = gridState.zones[key];

    document.querySelector('[name="zone_selection_type"]').value = 'cells';
    document.getElementById('modalSelJson').value = JSON.stringify([{row, col}]);
    document.getElementById('modalStart').value = String(selectedHour).padStart(2,'0') + ':00';
    document.getElementById('modalEnd').value = String(selectedHour + 1).padStart(2,'0') + ':00';

    if (zone && zone.schedule) {
        document.getElementById('modalTitle').textContent = 'تعديل خانة';
        document.getElementById('modalName').value = zone.schedule.name || '';
        document.getElementById('modalActivity').value = zone.schedule.activity_type || '';
        document.getElementById('modalAge').value = zone.schedule.age_group || '';
        document.getElementById('modalGender').value = zone.schedule.gender || 'male';
        document.getElementById('modalColor').value = zone.schedule.color || '#3B82F6';
    } else {
        document.getElementById('modalTitle').textContent = 'تعيين خانة جديدة';
        document.getElementById('boxForm').reset();
        document.querySelector('[name="zone_selection_type"]').value = 'cells';
        document.getElementById('modalSelJson').value = JSON.stringify([{row, col}]);
        document.getElementById('modalStart').value = String(selectedHour).padStart(2,'0') + ':00';
        document.getElementById('modalEnd').value = String(selectedHour + 1).padStart(2,'0') + ':00';
    }

    document.getElementById('boxModal').classList.add('active');
}

function closeModal() {
    document.getElementById('boxModal').classList.remove('active');
}

function saveBox(e) {
    e.preventDefault();
    const form = document.getElementById('boxForm');
    const formData = new FormData(form);
    formData.append('_token', CSRF);
    formData.set('coach_name', formData.get('schedule_name'));

    fetch(`/facility-grids/${GRID_ID}/schedules`, {
        method: 'POST',
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            closeModal();
            clearSelection();
            refreshGrid();
        } else {
            alert(data.message || 'حدث خطأ');
        }
    });
}

// ─── TRAINEES ───
function addTraineeToBox() {
    const name = document.getElementById('newTraineeName').value.trim();
    if (!name) return;

    const selJson = document.getElementById('modalSelJson').value;
    const cells = JSON.parse(selJson);
    if (!cells.length) return;

    const key = cells[0].row + ':' + cells[0].col;
    const zone = gridState.zones[key];
    if (!zone) return;

    const formData = new FormData();
    formData.append('_token', CSRF);
    formData.append('zone_id', zone.zone_id);
    formData.append('trainee_name', name);

    fetch(`/facility-grids/${GRID_ID}/trainees`, {
        method: 'POST',
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            document.getElementById('newTraineeName').value = '';
            refreshGrid();
        } else {
            alert(data.message || 'خطأ');
        }
    });
}

function removeTrainee(traineeId) {
    if (!confirm('إزالة المتدرب؟')) return;
    const formData = new FormData();
    formData.append('_token', CSRF);

    fetch(`/facility-grids/${GRID_ID}/trainees/${traineeId}/remove`, {
        method: 'POST',
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        body: formData
    })
    .then(r => r.json())
    .then(data => { if (data.success) refreshGrid(); });
}

// ─── DRAG & DROP (Move Trainee) ───
function dragStart(e, traineeId) {
    draggedTraineeId = traineeId;
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/plain', traineeId);
    e.stopPropagation();
}

function dragOver(e) {
    e.preventDefault();
    e.currentTarget.classList.add('drag-over');
}

function dragLeave(e) {
    e.currentTarget.classList.remove('drag-over');
}

function dropTrainee(e, targetZoneId) {
    e.preventDefault();
    e.currentTarget.classList.remove('drag-over');
    if (!draggedTraineeId || !targetZoneId) return;

    const formData = new FormData();
    formData.append('_token', CSRF);
    formData.append('target_zone_id', targetZoneId);

    fetch(`/facility-grids/${GRID_ID}/trainees/${draggedTraineeId}/move`, {
        method: 'POST',
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) refreshGrid();
        else alert(data.message || 'لا يمكن النقل');
    });

    draggedTraineeId = null;
}

// Auto-refresh every 30s
setInterval(refreshGrid, 30000);
</script>
<?php $__template->endSection(); ?>
