<?php
$__template->layout('Layout.main');
$gridRows = (int) ($facility['pool_grid_rows'] ?? 0);
$gridCols = (int) ($facility['pool_grid_cols'] ?? 0);
?>
<?php $__template->section('title'); ?>شبكة <?= e($facility['name_ar']) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sa/pool-grid" class="btn btn-outline"><i data-lucide="arrow-right" style="width:16px;height:16px;vertical-align:middle;margin-left:4px;"></i> رجوع</a>
<?php $__template->endSection(); ?>

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

<style>
/* Top bar */
.pg-top{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:16px;}
.pg-top .date-nav{display:flex;align-items:center;gap:6px;}
.pg-top .date-nav button{background:none;border:1px solid #D1D5DB;border-radius:6px;padding:6px 10px;cursor:pointer;font-size:14px;line-height:1;}
.pg-top .date-nav button:hover{background:#F3F4F6;}
.pg-top .date-nav input[type=date]{border:1px solid #D1D5DB;border-radius:6px;padding:6px 10px;font-size:14px;font-family:inherit;}
.pg-top-actions{display:flex;gap:6px;margin-right:auto;}
.pg-top-actions button{background:none;border:1px solid #D1D5DB;border-radius:6px;padding:6px 10px;cursor:pointer;font-size:13px;display:flex;align-items:center;gap:4px;}
.pg-top-actions button:hover{background:#F3F4F6;}
.pg-top-actions button.active{background:#EFF6FF;border-color:#93C5FD;color:#1D4ED8;}

/* Timeline strip */
.pg-timeline-wrap{margin-bottom:16px;}
.pg-timeline{display:flex;gap:0;border:1px solid #E5E7EB;border-radius:8px;overflow-x:auto;background:#F9FAFB;user-select:none;}
.pg-slot{flex:0 0 auto;min-width:60px;padding:10px 8px;text-align:center;cursor:pointer;border-left:1px solid #E5E7EB;transition:all .15s;font-size:12px;font-weight:500;}
.pg-slot:first-child{border-left:none;}
.pg-slot:hover{background:#EFF6FF;}
.pg-slot.active{background:#2563EB;color:#fff;font-weight:700;}
.pg-slot .slot-time{font-size:10px;display:block;margin-top:2px;opacity:.7;}
.pg-timeline-info{font-size:12px;color:#6B7280;margin-top:4px;}

/* Grid setup panel */
.pg-setup{background:#FEF3C7;border:1px solid #F59E0B;border-radius:8px;padding:16px;margin-bottom:16px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;transition:all .2s;}
.pg-setup.neutral{background:#F3F4F6;border-color:#D1D5DB;}
.pg-setup.hidden{display:none;}
.pg-setup label{font-size:13px;font-weight:600;color:#92400E;}
.pg-setup.neutral label{color:#374151;}
.pg-setup input[type=number]{width:60px;border:1px solid #D1D5DB;border-radius:6px;padding:6px 8px;font-size:14px;text-align:center;}
.pg-setup button{background:#F59E0B;color:#fff;border:none;border-radius:6px;padding:8px 16px;font-size:13px;font-weight:600;cursor:pointer;}
.pg-setup.neutral button{background:#2563EB;}
.pg-setup button:hover{opacity:.9;}
.pg-setup .pg-size-current{font-size:13px;color:#6B7280;font-weight:500;}

/* Pool grid wrapper with headers */
.pg-grid-outer{display:inline-grid;gap:0;margin-bottom:16px;min-width:100%;}
.pg-col-header{text-align:center;font-size:11px;color:#6B7280;font-weight:600;padding:4px 0;cursor:pointer;border-radius:4px;transition:background .12s;user-select:none;}
.pg-col-header:hover{background:#DBEAFE;color:#1D4ED8;}
.pg-col-header.hl{background:#BFDBFE;color:#1D4ED8;}
.pg-row-header{display:flex;align-items:center;justify-content:center;font-size:11px;color:#6B7280;font-weight:600;padding:0 6px;cursor:pointer;border-radius:4px;transition:background .12s;user-select:none;}
.pg-row-header:hover{background:#DBEAFE;color:#1D4ED8;}
.pg-row-header.hl{background:#BFDBFE;color:#1D4ED8;}
.pg-corner{display:flex;align-items:center;justify-content:center;cursor:pointer;border-radius:4px;font-size:10px;color:#9CA3AF;transition:background .12s;user-select:none;}
.pg-corner:hover{background:#DBEAFE;color:#1D4ED8;}

/* Pool grid cells */
.pg-pool-wrap{position:relative;}
.pg-pool{display:inline-grid;gap:3px;padding:12px;background:#E0F2FE;border:2px solid #7DD3FC;border-radius:12px;min-width:100%;}
.pg-cell{width:100%;aspect-ratio:1;border-radius:6px;cursor:crosshair;transition:all .12s;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:11px;font-weight:500;border:2px solid transparent;user-select:none;position:relative;overflow:hidden;min-height:48px;}
.pg-cell:hover{transform:scale(1.04);z-index:1;box-shadow:0 2px 8px rgba(0,0,0,.15);}
.pg-cell.selected{border-color:#2563EB !important;box-shadow:0 0 0 2px rgba(37,99,235,.3);}
.pg-cell.status-free{background:#fff;border-color:#E5E7EB;}
.pg-cell.status-training{background:#DBEAFE;border-color:#93C5FD;}
.pg-cell.status-hourly{background:#D1FAE5;border-color:#6EE7B7;}
.pg-cell.status-blocked{background:#F3F4F6;border-color:#D1D5DB;}
.pg-cell.status-maintenance{background:#FEF3C7;border-color:#FCD34D;}
.pg-cell .cell-label{text-align:center;line-height:1.2;padding:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%;}
.pg-cell .cell-coord{position:absolute;top:2px;right:4px;font-size:9px;color:#9CA3AF;font-weight:400;}

/* Action bar */
.pg-actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:12px 16px;background:#F9FAFB;border:1px solid #E5E7EB;border-radius:8px;margin-bottom:16px;}
.pg-actions button{border:none;border-radius:6px;padding:8px 14px;font-size:13px;font-weight:500;cursor:pointer;transition:all .15s;font-family:inherit;}
.pg-actions button:disabled{opacity:.35;cursor:not-allowed;}
.pg-actions .btn-training{background:#DBEAFE;color:#1D4ED8;}
.pg-actions .btn-training:hover:not(:disabled){background:#BFDBFE;}
.pg-actions .btn-hourly{background:#D1FAE5;color:#065F46;}
.pg-actions .btn-hourly:hover:not(:disabled){background:#A7F3D0;}
.pg-actions .btn-blocked{background:#F3F4F6;color:#374151;}
.pg-actions .btn-blocked:hover:not(:disabled){background:#E5E7EB;}
.pg-actions .btn-maintenance{background:#FEF3C7;color:#92400E;}
.pg-actions .btn-maintenance:hover:not(:disabled){background:#FDE68A;}
.pg-actions .btn-clear{background:#FEE2E2;color:#991B1B;}
.pg-actions .btn-clear:hover:not(:disabled){background:#FECACA;}
.pg-actions .btn-copy{background:#E0E7FF;color:#3730A3;}
.pg-actions .btn-copy:hover:not(:disabled){background:#C7D2FE;}
.pg-sel-info{font-size:13px;color:#6B7280;margin-right:auto;}

/* Shortcuts hint */
.pg-shortcuts{font-size:11px;color:#9CA3AF;margin-bottom:12px;display:flex;gap:12px;flex-wrap:wrap;}
.pg-shortcuts kbd{background:#F3F4F6;border:1px solid #D1D5DB;border-radius:3px;padding:1px 4px;font-size:10px;font-family:monospace;}

/* Legend */
.pg-legend{display:flex;gap:14px;font-size:12px;color:#374151;flex-wrap:wrap;margin-top:12px;}
.pg-legend span{display:flex;align-items:center;gap:4px;}
.pg-legend .sw{width:16px;height:16px;border-radius:4px;border:1px solid #D1D5DB;}

/* Template side panel */
.pg-tpl-btn{position:relative;}
.pg-tpl-panel{position:fixed;top:0;left:0;width:380px;max-width:90vw;height:100vh;background:#fff;box-shadow:4px 0 20px rgba(0,0,0,.15);z-index:900;transform:translateX(-100%);transition:transform .25s ease;overflow-y:auto;display:flex;flex-direction:column;}
.pg-tpl-panel.open{transform:translateX(0);}
.pg-tpl-overlay{position:fixed;inset:0;background:rgba(0,0,0,.3);z-index:899;opacity:0;pointer-events:none;transition:opacity .2s;}
.pg-tpl-overlay.show{opacity:1;pointer-events:all;}
.pg-tpl-header{padding:16px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;background:#fff;z-index:1;}
.pg-tpl-header h3{margin:0;font-size:16px;font-weight:700;}
.pg-tpl-body{padding:16px 20px;flex:1;overflow-y:auto;}
.pg-tpl-item{border:1px solid #E5E7EB;border-radius:8px;padding:12px;margin-bottom:10px;position:relative;}
.pg-tpl-item .tpl-name{font-size:14px;font-weight:600;margin-bottom:4px;display:flex;align-items:center;gap:6px;}
.pg-tpl-item .tpl-name .dot{width:10px;height:10px;border-radius:50%;}
.pg-tpl-item .tpl-meta{font-size:11px;color:#6B7280;}
.pg-tpl-item .tpl-actions{display:flex;gap:6px;margin-top:8px;}
.pg-tpl-item .tpl-actions button{font-size:11px;padding:4px 8px;border-radius:4px;border:1px solid #D1D5DB;background:#fff;cursor:pointer;}
.pg-tpl-item .tpl-actions button:hover{background:#F3F4F6;}
.pg-tpl-item .tpl-actions .btn-expand{border-color:#10B981;color:#065F46;background:#D1FAE5;}
.pg-tpl-item .tpl-actions .btn-expand:hover{background:#A7F3D0;}

/* Modal */
.pg-modal-bg{position:fixed;inset:0;background:rgba(0,0,0,.4);z-index:1000;display:flex;align-items:center;justify-content:center;opacity:0;pointer-events:none;transition:opacity .2s;}
.pg-modal-bg.show{opacity:1;pointer-events:all;}
.pg-modal{background:#fff;border-radius:12px;padding:24px;width:500px;max-width:90vw;max-height:85vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.2);}
.pg-modal h3{margin:0 0 16px;font-size:18px;font-weight:700;}
.pg-modal label{display:block;margin-bottom:4px;font-size:13px;font-weight:500;color:#374151;}
.pg-modal select,.pg-modal input,.pg-modal textarea{width:100%;border:1px solid #D1D5DB;border-radius:6px;padding:8px 10px;font-size:14px;font-family:inherit;margin-bottom:12px;}
.pg-modal .m-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:16px;}
.pg-modal .m-actions button{padding:8px 18px;border-radius:6px;font-size:14px;font-weight:500;cursor:pointer;font-family:inherit;border:none;}
.pg-modal .m-confirm{background:#2563EB;color:#fff;}
.pg-modal .m-confirm:hover{background:#1D4ED8;}
.pg-modal .m-cancel{background:#fff;color:#374151;border:1px solid #D1D5DB !important;}

/* Template wizard steps */
.pg-wizard-steps{display:flex;gap:8px;margin-bottom:16px;}
.pg-wizard-steps .step{flex:1;height:4px;border-radius:2px;background:#E5E7EB;transition:background .2s;}
.pg-wizard-steps .step.done{background:#2563EB;}
.pg-wizard-steps .step.current{background:#93C5FD;}
.pg-wiz-days{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px;}
.pg-wiz-days button{width:40px;height:36px;border-radius:6px;border:1px solid #D1D5DB;background:#fff;font-size:12px;font-weight:600;cursor:pointer;transition:all .12s;}
.pg-wiz-days button.active{background:#2563EB;color:#fff;border-color:#2563EB;}

/* Loading */
.pg-loading{position:absolute;inset:0;background:rgba(255,255,255,.7);display:flex;align-items:center;justify-content:center;z-index:5;border-radius:12px;}
.pg-loading.hidden{display:none;}
.pg-spinner{width:32px;height:32px;border:3px solid #E5E7EB;border-top-color:#2563EB;border-radius:50%;animation:pgspin .6s linear infinite;}
@keyframes pgspin{to{transform:rotate(360deg);}}
</style>

<!-- Date Navigation + Actions -->
<div class="pg-top">
    <div class="date-nav">
        <button id="pgPrevDay" title="اليوم السابق"><i data-lucide="chevron-right" style="width:14px;height:14px;"></i></button>
        <input type="date" id="pgDate" value="<?= e($date) ?>">
        <button id="pgNextDay" title="اليوم التالي"><i data-lucide="chevron-left" style="width:14px;height:14px;"></i></button>
        <button id="pgToday" style="font-size:12px;padding:6px 12px;">اليوم</button>
    </div>
    <div class="pg-top-actions">
        <button id="pgSettingsToggle" title="إعدادات الشبكة (<?= $gridRows ?>×<?= $gridCols ?>)"><i data-lucide="settings" style="width:14px;height:14px;"></i> <?= $gridRows ?>×<?= $gridCols ?></button>
        <button id="pgTplToggle" class="pg-tpl-btn" title="القوالب الأسبوعية"><i data-lucide="calendar-range" style="width:14px;height:14px;"></i> القوالب</button>
    </div>
</div>

<!-- Grid Setup Panel (always in DOM, toggled) -->
<div class="pg-setup <?= ($gridRows > 0 && $gridCols > 0) ? 'hidden neutral' : '' ?>" id="pgSetup">
    <i data-lucide="grid-3x3" style="width:18px;height:18px;"></i>
    <span class="pg-size-current"><?= ($gridRows > 0) ? "الحالي: {$gridRows}×{$gridCols}" : 'لم يتم التهيئة' ?></span>
    <label>صفوف <input type="number" id="pgSetupRows" min="1" max="20" value="<?= $gridRows ?: 4 ?>"></label>
    <label>أعمدة <input type="number" id="pgSetupCols" min="1" max="20" value="<?= $gridCols ?: 6 ?>"></label>
    <button id="pgSetupSave">حفظ</button>
</div>

<!-- Timeline Strip (multi-select) -->
<div class="pg-timeline-wrap">
    <div class="pg-timeline" id="pgTimeline">
        <?php foreach ($slots as $i => $slot): ?>
        <div class="pg-slot<?= $i === 0 ? ' active' : '' ?>" data-idx="<?= $i ?>" data-start="<?= e($slot['start']) ?>" data-end="<?= e($slot['end']) ?>">
            <?= e($slot['start']) ?>
            <span class="slot-time"><?= e($slot['end']) ?></span>
        </div>
        <?php endforeach; ?>
    </div>
    <div class="pg-timeline-info" id="pgTimelineInfo">فترة واحدة محددة</div>
</div>

<!-- Action Bar -->
<div class="pg-actions">
    <span class="pg-sel-info" id="pgSelInfo">لا يوجد تحديد</span>
    <button class="btn-training" id="pgBtnTraining" disabled><i data-lucide="users" style="width:14px;height:14px;vertical-align:middle;margin-left:2px;"></i> تدريب</button>
    <button class="btn-hourly" id="pgBtnHourly" disabled><i data-lucide="clock" style="width:14px;height:14px;vertical-align:middle;margin-left:2px;"></i> ساعة</button>
    <button class="btn-blocked" id="pgBtnBlocked" disabled><i data-lucide="lock" style="width:14px;height:14px;vertical-align:middle;margin-left:2px;"></i> حجب</button>
    <button class="btn-maintenance" id="pgBtnMaint" disabled><i data-lucide="wrench" style="width:14px;height:14px;vertical-align:middle;margin-left:2px;"></i> صيانة</button>
    <button class="btn-copy" id="pgBtnCopy" title="نسخ من فترة أخرى"><i data-lucide="copy" style="width:14px;height:14px;vertical-align:middle;margin-left:2px;"></i> نسخ</button>
    <button class="btn-clear" id="pgBtnClear" disabled><i data-lucide="x" style="width:14px;height:14px;vertical-align:middle;margin-left:2px;"></i> مسح</button>
</div>

<!-- Keyboard Shortcuts -->
<div class="pg-shortcuts">
    <span><kbd>Ctrl+A</kbd> تحديد الكل</span>
    <span><kbd>Esc</kbd> إلغاء التحديد</span>
    <span><kbd>Shift+Click</kbd> تحديد مستطيل</span>
    <span><kbd>Ctrl+Click</kbd> إضافة/إزالة</span>
</div>

<!-- Pool Grid with Headers -->
<div class="pg-pool-wrap" style="position:relative;">
    <div class="pg-loading hidden" id="pgLoading"><div class="pg-spinner"></div></div>
    <div id="pgGridOuter" class="pg-grid-outer"></div>
</div>

<!-- Legend -->
<div class="pg-legend">
    <span><span class="sw" style="background:#fff;"></span> فارغ</span>
    <span><span class="sw" style="background:#DBEAFE;"></span> تدريب</span>
    <span><span class="sw" style="background:#D1FAE5;"></span> حجز ساعة</span>
    <span><span class="sw" style="background:#F3F4F6;"></span> محجوب</span>
    <span><span class="sw" style="background:#FEF3C7;"></span> صيانة</span>
</div>

<!-- Template Side Panel -->
<div class="pg-tpl-overlay" id="pgTplOverlay"></div>
<div class="pg-tpl-panel" id="pgTplPanel">
    <div class="pg-tpl-header">
        <h3>القوالب الأسبوعية</h3>
        <button id="pgTplClose" style="background:none;border:none;cursor:pointer;font-size:18px;color:#6B7280;">&times;</button>
    </div>
    <div class="pg-tpl-body" id="pgTplBody">
        <button id="pgTplCreate" style="width:100%;padding:10px;border:2px dashed #D1D5DB;border-radius:8px;background:none;cursor:pointer;font-size:13px;font-weight:600;color:#6B7280;margin-bottom:16px;">+ قالب جديد</button>
        <div id="pgTplList"></div>
    </div>
</div>

<!-- Modal -->
<div class="pg-modal-bg" id="pgModal">
    <div class="pg-modal">
        <h3 id="pgModalTitle">تعيين</h3>
        <div id="pgModalContent">
            <div id="pgModalGroup">
                <label>المجموعة</label>
                <select id="pgGroupSelect">
                    <option value="">اختر مجموعة...</option>
                    <?php foreach ($groups as $g): ?>
                    <option value="<?= (int) $g['id'] ?>">
                        <?= e($g['name_ar']) ?> — <?= e($g['coach_name'] ?? 'بدون مدرب') ?> (<?= (int) $g['current_count'] ?>/<?= (int) $g['max_capacity'] ?>)
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div id="pgModalCopy" style="display:none;">
                <label>نسخ من فترة</label>
                <select id="pgCopyFrom">
                    <?php foreach ($slots as $i => $slot): ?>
                    <option value="<?= e($slot['start']) ?>"><?= e($slot['start']) ?> - <?= e($slot['end']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <label>ملاحظات (اختياري)</label>
            <textarea id="pgNotes" rows="2" placeholder="ملاحظات..."></textarea>
        </div>
        <div class="m-actions">
            <button class="m-cancel" id="pgModalCancel">إلغاء</button>
            <button class="m-confirm" id="pgModalConfirm">تأكيد</button>
        </div>
    </div>
</div>

<!-- Template Wizard Modal -->
<div class="pg-modal-bg" id="pgTplWizModal">
    <div class="pg-modal" style="width:550px;">
        <h3 id="pgTplWizTitle">قالب جديد</h3>
        <div class="pg-wizard-steps" id="pgWizSteps">
            <div class="step current"></div>
            <div class="step"></div>
            <div class="step"></div>
            <div class="step"></div>
        </div>
        <div id="pgWizContent"></div>
        <div class="m-actions">
            <button class="m-cancel" id="pgWizBack">السابق</button>
            <button class="m-confirm" id="pgWizNext">التالي</button>
        </div>
    </div>
</div>

<!-- Expand Modal -->
<div class="pg-modal-bg" id="pgExpandModal">
    <div class="pg-modal" style="width:380px;">
        <h3>توسيع القالب</h3>
        <label>من تاريخ</label>
        <input type="date" id="pgExpandFrom" value="<?= e($date) ?>">
        <label>إلى تاريخ</label>
        <input type="date" id="pgExpandTo" value="">
        <div class="m-actions">
            <button class="m-cancel" id="pgExpandCancel">إلغاء</button>
            <button class="m-confirm" id="pgExpandConfirm">توسيع</button>
        </div>
    </div>
</div>

<script>
(function(){
    const FACILITY_ID = <?= (int) $facility['id'] ?>;
    const CSRF = '<?= e($_SESSION['_csrf_token'] ?? '') ?>';
    const SLOTS = <?= json_encode($slots, JSON_UNESCAPED_UNICODE) ?>;
    const GROUPS = <?= json_encode($groups, JSON_UNESCAPED_UNICODE) ?>;
    let GRID_ROWS = <?= $gridRows ?>;
    let GRID_COLS = <?= $gridCols ?>;

    let activeSlotIndices = new Set([0]);
    let lastClickedSlot = 0;
    let gridData = {};
    let selectedCells = new Set();
    let isDragging = false;
    let isDraggingTimeline = false;
    let dragMode = null;
    let pendingAction = null;
    let templates = [];
    let expandingTemplateId = null;

    const gridOuter = document.getElementById('pgGridOuter');
    const dateInput = document.getElementById('pgDate');
    const loading = document.getElementById('pgLoading');
    const selInfo = document.getElementById('pgSelInfo');
    const timeline = document.getElementById('pgTimeline');
    const timelineInfo = document.getElementById('pgTimelineInfo');
    const modal = document.getElementById('pgModal');
    const modalTitle = document.getElementById('pgModalTitle');

    // --- Date Navigation ---
    function currentDate(){ return dateInput.value; }
    function activeSlots(){ return Array.from(activeSlotIndices).sort((a,b)=>a-b).map(i => SLOTS[i]).filter(Boolean); }
    function firstActiveSlot(){ let sorted = Array.from(activeSlotIndices).sort((a,b)=>a-b); return SLOTS[sorted[0]] || SLOTS[0]; }

    document.getElementById('pgPrevDay').onclick = function(){ shiftDate(-1); };
    document.getElementById('pgNextDay').onclick = function(){ shiftDate(1); };
    document.getElementById('pgToday').onclick = function(){ dateInput.value = new Date().toISOString().slice(0,10); loadState(); };
    dateInput.onchange = function(){ loadState(); };

    function shiftDate(d){
        let dt = new Date(currentDate());
        dt.setDate(dt.getDate() + d);
        dateInput.value = dt.toISOString().slice(0,10);
        loadState();
    }

    // --- Timeline (Multi-select with drag + shift) ---
    timeline.addEventListener('mousedown', function(e){
        let slot = e.target.closest('.pg-slot');
        if(!slot) return;
        e.preventDefault();
        isDraggingTimeline = true;
        let idx = parseInt(slot.dataset.idx);

        if(e.shiftKey && activeSlotIndices.size > 0){
            let min = Math.min(lastClickedSlot, idx);
            let max = Math.max(lastClickedSlot, idx);
            activeSlotIndices.clear();
            for(let i = min; i <= max; i++) activeSlotIndices.add(i);
        } else if(e.ctrlKey || e.metaKey){
            if(activeSlotIndices.has(idx)) activeSlotIndices.delete(idx);
            else activeSlotIndices.add(idx);
        } else {
            activeSlotIndices.clear();
            activeSlotIndices.add(idx);
        }
        lastClickedSlot = idx;
        updateTimelineUI();
    });

    timeline.addEventListener('mousemove', function(e){
        if(!isDraggingTimeline) return;
        let slot = e.target.closest('.pg-slot');
        if(!slot) return;
        let idx = parseInt(slot.dataset.idx);
        let min = Math.min(lastClickedSlot, idx);
        let max = Math.max(lastClickedSlot, idx);
        activeSlotIndices.clear();
        for(let i = min; i <= max; i++) activeSlotIndices.add(i);
        updateTimelineUI();
    });

    document.addEventListener('mouseup', function(){
        if(isDraggingTimeline){
            isDraggingTimeline = false;
            clearSelection();
            loadState();
        }
        isDragging = false;
        dragMode = null;
    });

    function updateTimelineUI(){
        document.querySelectorAll('.pg-slot').forEach(function(s){
            s.classList.toggle('active', activeSlotIndices.has(parseInt(s.dataset.idx)));
        });
        let n = activeSlotIndices.size;
        timelineInfo.textContent = n === 1 ? 'فترة واحدة محددة' : n + ' فترات محددة';
    }

    // --- Grid Setup Toggle ---
    document.getElementById('pgSettingsToggle').onclick = function(){
        let setup = document.getElementById('pgSetup');
        setup.classList.toggle('hidden');
        this.classList.toggle('active', !setup.classList.contains('hidden'));
    };

    document.getElementById('pgSetupSave').onclick = function(){
        let r = parseInt(document.getElementById('pgSetupRows').value) || 0;
        let c = parseInt(document.getElementById('pgSetupCols').value) || 0;
        if(r < 1 || c < 1 || r > 20 || c > 20){ alert('الأبعاد يجب أن تكون بين 1 و 20'); return; }
        showLoading();
        apiPost('/api/sa/pool-grid/' + FACILITY_ID + '/update-grid', {rows: r, cols: c})
        .then(function(res){
            if(res.error){ alert(res.error); hideLoading(); return; }
            GRID_ROWS = r; GRID_COLS = c;
            document.getElementById('pgSetup').classList.add('hidden', 'neutral');
            document.getElementById('pgSettingsToggle').innerHTML = '<i data-lucide="settings" style="width:14px;height:14px;"></i> ' + r + '×' + c;
            if(typeof lucide !== 'undefined') lucide.createIcons();
            toast('تم حفظ أبعاد الشبكة: ' + r + '×' + c, 'success');
            loadState();
        });
    };

    // --- Render Grid with Row/Col Headers ---
    function renderGrid(){
        if(GRID_ROWS < 1 || GRID_COLS < 1){ gridOuter.innerHTML = '<div style="padding:20px;color:#92400E;font-size:14px;">يرجى تهيئة أبعاد الشبكة أولاً</div>'; return; }

        let cols = GRID_COLS + 1; // extra for row headers
        gridOuter.style.gridTemplateColumns = 'repeat(' + GRID_COLS + ', 1fr) 32px';
        gridOuter.style.gridTemplateRows = '28px repeat(' + GRID_ROWS + ', 1fr)';
        gridOuter.style.gap = '3px';

        let html = '';

        // Column headers row
        for(let c = 0; c < GRID_COLS; c++){
            html += '<div class="pg-col-header" data-col="' + c + '">' + (c+1) + '</div>';
        }
        // Corner (select all)
        html += '<div class="pg-corner" id="pgSelectAll" title="تحديد الكل">⊞</div>';

        // Data rows
        for(let r = 0; r < GRID_ROWS; r++){
            for(let c = 0; c < GRID_COLS; c++){
                let key = r + ':' + c;
                let cell = gridData[key] || {status:'free', label:'', type:null};
                let cls = 'pg-cell status-' + (cell.status || 'free');
                if(selectedCells.has(key)) cls += ' selected';
                html += '<div class="' + cls + '" data-r="' + r + '" data-c="' + c + '" data-key="' + key + '">';
                html += '<span class="cell-coord">' + (r+1) + ',' + (c+1) + '</span>';
                if(cell.label) html += '<span class="cell-label">' + esc(cell.label) + '</span>';
                html += '</div>';
            }
            // Row header
            html += '<div class="pg-row-header" data-row="' + r + '">' + (r+1) + '</div>';
        }

        gridOuter.innerHTML = html;
        bindCells();
        bindHeaders();
        updateSelectionUI();
    }

    // --- Header Click Handlers ---
    function bindHeaders(){
        gridOuter.querySelectorAll('.pg-col-header').forEach(function(el){
            el.addEventListener('click', function(e){
                let c = parseInt(el.dataset.col);
                if(e.shiftKey){
                    for(let r = 0; r < GRID_ROWS; r++) selectedCells.add(r + ':' + c);
                } else {
                    let allSelected = true;
                    for(let r = 0; r < GRID_ROWS; r++){
                        if(!selectedCells.has(r + ':' + c)){ allSelected = false; break; }
                    }
                    if(allSelected){
                        for(let r = 0; r < GRID_ROWS; r++) selectedCells.delete(r + ':' + c);
                    } else {
                        if(!e.ctrlKey && !e.metaKey) selectedCells.clear();
                        for(let r = 0; r < GRID_ROWS; r++) selectedCells.add(r + ':' + c);
                    }
                }
                updateSelectionUI();
            });
        });

        gridOuter.querySelectorAll('.pg-row-header').forEach(function(el){
            el.addEventListener('click', function(e){
                let r = parseInt(el.dataset.row);
                if(e.shiftKey){
                    for(let c = 0; c < GRID_COLS; c++) selectedCells.add(r + ':' + c);
                } else {
                    let allSelected = true;
                    for(let c = 0; c < GRID_COLS; c++){
                        if(!selectedCells.has(r + ':' + c)){ allSelected = false; break; }
                    }
                    if(allSelected){
                        for(let c = 0; c < GRID_COLS; c++) selectedCells.delete(r + ':' + c);
                    } else {
                        if(!e.ctrlKey && !e.metaKey) selectedCells.clear();
                        for(let c = 0; c < GRID_COLS; c++) selectedCells.add(r + ':' + c);
                    }
                }
                updateSelectionUI();
            });
        });

        let corner = document.getElementById('pgSelectAll');
        if(corner){
            corner.onclick = function(){
                let total = GRID_ROWS * GRID_COLS;
                if(selectedCells.size === total){
                    selectedCells.clear();
                } else {
                    for(let r=0;r<GRID_ROWS;r++) for(let c=0;c<GRID_COLS;c++) selectedCells.add(r+':'+c);
                }
                updateSelectionUI();
            };
        }
    }

    // --- Cell Interactions ---
    function bindCells(){
        gridOuter.querySelectorAll('.pg-cell').forEach(function(el){
            el.addEventListener('mousedown', function(e){
                if(e.button !== 0) return;
                e.preventDefault();
                isDragging = true;
                let key = el.dataset.key;
                if(e.ctrlKey || e.metaKey){
                    if(selectedCells.has(key)){ selectedCells.delete(key); dragMode = 'deselect'; }
                    else { selectedCells.add(key); dragMode = 'select'; }
                } else if(e.shiftKey && selectedCells.size > 0){
                    rectSelect(key);
                    dragMode = 'select';
                } else {
                    selectedCells.clear();
                    selectedCells.add(key);
                    dragMode = 'select';
                }
                updateSelectionUI();
            });
            el.addEventListener('mouseenter', function(){
                if(!isDragging) return;
                let key = el.dataset.key;
                if(dragMode === 'select') selectedCells.add(key);
                else selectedCells.delete(key);
                updateSelectionUI();
            });
        });
    }

    function rectSelect(endKey){
        let last = Array.from(selectedCells).pop();
        if(!last) return;
        let [r1, c1] = last.split(':').map(Number);
        let [r2, c2] = endKey.split(':').map(Number);
        let minR = Math.min(r1,r2), maxR = Math.max(r1,r2);
        let minC = Math.min(c1,c2), maxC = Math.max(c1,c2);
        for(let r = minR; r <= maxR; r++){
            for(let c = minC; c <= maxC; c++){
                selectedCells.add(r + ':' + c);
            }
        }
    }

    document.addEventListener('keydown', function(e){
        if(e.key === 'Escape') clearSelection();
        if((e.ctrlKey || e.metaKey) && e.key === 'a' && !isInput(e.target)){
            e.preventDefault();
            for(let r=0;r<GRID_ROWS;r++) for(let c=0;c<GRID_COLS;c++) selectedCells.add(r+':'+c);
            updateSelectionUI();
        }
    });

    function isInput(el){ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT'; }

    function clearSelection(){
        selectedCells.clear();
        updateSelectionUI();
    }

    function updateSelectionUI(){
        let n = selectedCells.size;
        let slotsN = activeSlotIndices.size;
        if(n === 0){
            selInfo.textContent = 'لا يوجد تحديد';
        } else if(slotsN > 1){
            selInfo.textContent = n + ' مربع × ' + slotsN + ' فترات';
        } else {
            selInfo.textContent = n + ' مربع محدد';
        }
        let has = n > 0;
        document.getElementById('pgBtnTraining').disabled = !has;
        document.getElementById('pgBtnHourly').disabled = !has;
        document.getElementById('pgBtnBlocked').disabled = !has;
        document.getElementById('pgBtnMaint').disabled = !has;
        document.getElementById('pgBtnClear').disabled = !has;

        gridOuter.querySelectorAll('.pg-cell').forEach(function(el){
            el.classList.toggle('selected', selectedCells.has(el.dataset.key));
        });

        // Highlight row/col headers
        gridOuter.querySelectorAll('.pg-col-header').forEach(function(el){
            let c = parseInt(el.dataset.col);
            let any = false;
            for(let r = 0; r < GRID_ROWS; r++){ if(selectedCells.has(r+':'+c)){ any = true; break; } }
            el.classList.toggle('hl', any);
        });
        gridOuter.querySelectorAll('.pg-row-header').forEach(function(el){
            let r = parseInt(el.dataset.row);
            let any = false;
            for(let c = 0; c < GRID_COLS; c++){ if(selectedCells.has(r+':'+c)){ any = true; break; } }
            el.classList.toggle('hl', any);
        });
    }

    // --- Actions (multi-slot aware) ---
    document.getElementById('pgBtnTraining').onclick = function(){ showModal('training'); };
    document.getElementById('pgBtnHourly').onclick = function(){ showModal('hourly'); };
    document.getElementById('pgBtnBlocked').onclick = function(){ doAssign('blocked'); };
    document.getElementById('pgBtnMaint').onclick = function(){ doAssign('maintenance'); };
    document.getElementById('pgBtnCopy').onclick = function(){ showModal('copy'); };
    document.getElementById('pgBtnClear').onclick = function(){
        if(!confirm('هل تريد مسح التعيينات من المربعات المحددة؟')) return;
        doClear();
    };

    function showModal(action){
        pendingAction = action;
        document.getElementById('pgModalGroup').style.display = (action === 'training') ? '' : 'none';
        document.getElementById('pgModalCopy').style.display = (action === 'copy') ? '' : 'none';
        if(action === 'training') modalTitle.textContent = 'تعيين تدريب';
        else if(action === 'hourly') modalTitle.textContent = 'حجز ساعة';
        else if(action === 'copy') modalTitle.textContent = 'نسخ من فترة أخرى';
        document.getElementById('pgNotes').value = '';
        document.getElementById('pgGroupSelect').value = '';
        modal.classList.add('show');
    }

    function hideModal(){ modal.classList.remove('show'); pendingAction = null; }
    document.getElementById('pgModalCancel').onclick = hideModal;
    modal.addEventListener('click', function(e){ if(e.target === modal) hideModal(); });

    document.getElementById('pgModalConfirm').onclick = function(){
        if(pendingAction === 'training'){
            let gid = document.getElementById('pgGroupSelect').value;
            if(!gid){ alert('اختر مجموعة'); return; }
            doAssign('training', parseInt(gid));
        } else if(pendingAction === 'hourly'){
            doAssign('hourly', null);
        } else if(pendingAction === 'copy'){
            doCopy();
        }
        hideModal();
    };

    function buildCells(){
        let cells = [];
        selectedCells.forEach(function(key){
            let [r, c] = key.split(':').map(Number);
            cells.push({row: r, col: c});
        });
        return cells;
    }

    function buildSlots(){
        return activeSlots().map(function(s){ return {start_time: s.start, end_time: s.end}; });
    }

    function doAssign(action, groupId){
        let slots = buildSlots();
        let notes = document.getElementById('pgNotes').value.trim();
        showLoading();
        apiPost('/api/sa/pool-grid/' + FACILITY_ID + '/assign', {
            date: currentDate(),
            slots: slots,
            action: action,
            cells: buildCells(),
            group_id: groupId || null,
            notes: notes || ''
        }).then(function(res){
            if(res.error){ alert(res.error); hideLoading(); return; }
            let msg = 'تم: ' + (res.assigned || 0) + ' مربع';
            if(res.skipped) msg += ' | تخطي: ' + res.skipped;
            toast(msg, 'success');
            clearSelection();
            loadState();
        });
    }

    function doClear(){
        let slots = buildSlots();
        showLoading();
        apiPost('/api/sa/pool-grid/' + FACILITY_ID + '/clear', {
            date: currentDate(),
            slots: slots,
            cells: buildCells()
        }).then(function(res){
            if(res.error){ alert(res.error); hideLoading(); return; }
            toast('تم المسح: ' + (res.cleared || 0), 'success');
            clearSelection();
            loadState();
        });
    }

    function doCopy(){
        let slot = firstActiveSlot();
        let fromTime = document.getElementById('pgCopyFrom').value;
        if(fromTime === slot.start){ alert('لا يمكن النسخ من نفس الفترة'); return; }
        showLoading();
        apiPost('/api/sa/pool-grid/' + FACILITY_ID + '/copy-slot', {
            date: currentDate(),
            from_time: fromTime,
            to_slots: buildSlots().map(function(s){ return {start: s.start_time, end: s.end_time}; })
        }).then(function(res){
            if(res.error){ alert(res.error); hideLoading(); return; }
            toast('تم النسخ: ' + (res.copied || 0) + ' مربع', 'success');
            loadState();
        });
    }

    // --- Template Panel ---
    document.getElementById('pgTplToggle').onclick = function(){
        document.getElementById('pgTplPanel').classList.add('open');
        document.getElementById('pgTplOverlay').classList.add('show');
        loadTemplates();
    };
    document.getElementById('pgTplClose').onclick = closeTplPanel;
    document.getElementById('pgTplOverlay').onclick = closeTplPanel;

    function closeTplPanel(){
        document.getElementById('pgTplPanel').classList.remove('open');
        document.getElementById('pgTplOverlay').classList.remove('show');
    }

    function loadTemplates(){
        fetch('/api/sa/pool-grid/' + FACILITY_ID + '/templates', {
            headers: {'X-Requested-With': 'XMLHttpRequest'}
        })
        .then(function(r){ return r.json(); })
        .then(function(data){
            templates = data.templates || [];
            renderTemplateList();
        })
        .catch(function(){ document.getElementById('pgTplList').innerHTML = '<p style="color:#991B1B;font-size:13px;">خطأ في التحميل</p>'; });
    }

    function renderTemplateList(){
        let html = '';
        if(templates.length === 0){
            html = '<p style="color:#6B7280;font-size:13px;text-align:center;">لا توجد قوالب بعد</p>';
        }
        templates.forEach(function(t){
            html += '<div class="pg-tpl-item">';
            html += '<div class="tpl-name"><span class="dot" style="background:' + esc(t.color || '#3B82F6') + ';"></span>' + esc(t.name) + '</div>';
            html += '<div class="tpl-meta">' + (t.entries_count || 0) + ' إدخال' + (t.is_active ? '' : ' — <b style="color:#DC2626;">معطّل</b>') + '</div>';
            html += '<div class="tpl-actions">';
            html += '<button class="btn-expand" onclick="pgExpandTemplate(' + t.id + ')">توسيع</button>';
            html += '<button onclick="pgEditTemplate(' + t.id + ')">تعديل</button>';
            html += '<button onclick="pgDeleteTemplate(' + t.id + ')">حذف</button>';
            html += '</div></div>';
        });
        document.getElementById('pgTplList').innerHTML = html;
    }

    // Template wizard state
    let wizStep = 0;
    let wizData = {name:'', color:'#3B82F6', days:[], slots:[], zoneType:'all', zones:{}, action:'training', group_id:null, label:'', notes:''};

    document.getElementById('pgTplCreate').onclick = function(){ openWizard(); };

    function openWizard(editData){
        wizStep = 0;
        wizData = editData || {name:'', color:'#3B82F6', days:[], slots:[], zoneType:'all', zones:{}, action:'training', group_id:null, label:'', notes:''};
        renderWizStep();
        document.getElementById('pgTplWizModal').classList.add('show');
    }

    function closeWizard(){
        document.getElementById('pgTplWizModal').classList.remove('show');
    }

    document.getElementById('pgWizBack').onclick = function(){
        if(wizStep === 0) closeWizard();
        else { wizStep--; renderWizStep(); }
    };

    document.getElementById('pgWizNext').onclick = function(){
        if(!validateWizStep()) return;
        if(wizStep === 3){
            saveTemplate();
            return;
        }
        wizStep++;
        renderWizStep();
    };

    function validateWizStep(){
        if(wizStep === 0 && !wizData.name.trim()){ alert('ادخل اسم القالب'); return false; }
        if(wizStep === 1 && wizData.days.length === 0){ alert('اختر يوم واحد على الأقل'); return false; }
        if(wizStep === 2 && wizData.slots.length === 0){ alert('اختر فترة واحدة على الأقل'); return false; }
        return true;
    }

    const DAY_NAMES = ['أحد','إثنين','ثلاثاء','أربعاء','خميس','جمعة','سبت'];

    function renderWizStep(){
        let steps = document.querySelectorAll('#pgWizSteps .step');
        steps.forEach(function(s, i){
            s.className = 'step' + (i < wizStep ? ' done' : '') + (i === wizStep ? ' current' : '');
        });

        let nextBtn = document.getElementById('pgWizNext');
        nextBtn.textContent = wizStep === 3 ? 'حفظ' : 'التالي';
        document.getElementById('pgWizBack').textContent = wizStep === 0 ? 'إلغاء' : 'السابق';

        let content = document.getElementById('pgWizContent');
        let html = '';

        if(wizStep === 0){
            html += '<label>اسم القالب</label>';
            html += '<input type="text" id="pgWizName" value="' + esc(wizData.name) + '" placeholder="مثال: تدريب صباحي أسبوعي">';
            html += '<label>اللون</label>';
            html += '<input type="color" id="pgWizColor" value="' + (wizData.color || '#3B82F6') + '" style="width:60px;height:36px;padding:2px;cursor:pointer;">';
        } else if(wizStep === 1){
            html += '<label>أيام الأسبوع</label>';
            html += '<div class="pg-wiz-days">';
            for(let d = 0; d < 7; d++){
                let active = wizData.days.includes(d) ? ' active' : '';
                html += '<button type="button" class="wiz-day' + active + '" data-d="' + d + '">' + DAY_NAMES[d] + '</button>';
            }
            html += '</div>';
        } else if(wizStep === 2){
            html += '<label>الفترات الزمنية (اختر واحدة أو أكثر)</label>';
            html += '<div style="display:flex;flex-wrap:wrap;gap:4px;max-height:200px;overflow-y:auto;">';
            SLOTS.forEach(function(s, i){
                let active = wizData.slots.some(function(ws){ return ws.start === s.start; }) ? ' active' : '';
                html += '<button type="button" class="wiz-slot' + active + '" data-idx="' + i + '" style="padding:6px 10px;border-radius:4px;border:1px solid #D1D5DB;background:' + (active ? '#2563EB;color:#fff' : '#fff') + ';font-size:12px;cursor:pointer;">' + s.start + '-' + s.end + '</button>';
            });
            html += '</div>';
        } else if(wizStep === 3){
            html += '<label>نوع التعيين</label>';
            html += '<select id="pgWizAction"><option value="training"' + (wizData.action==='training'?' selected':'') + '>تدريب</option><option value="hourly"' + (wizData.action==='hourly'?' selected':'') + '>حجز ساعة</option><option value="blocked"' + (wizData.action==='blocked'?' selected':'') + '>حجب</option><option value="maintenance"' + (wizData.action==='maintenance'?' selected':'') + '>صيانة</option></select>';
            html += '<div id="pgWizGroupWrap"><label>المجموعة</label><select id="pgWizGroup"><option value="">اختر...</option>';
            GROUPS.forEach(function(g){ html += '<option value="' + g.id + '"' + (wizData.group_id==g.id?' selected':'') + '>' + esc(g.name_ar) + '</option>'; });
            html += '</select></div>';
            html += '<label>نطاق التحديد</label>';
            html += '<select id="pgWizZoneType"><option value="all"' + (wizData.zoneType==='all'?' selected':'') + '>كامل الشبكة</option><option value="row"' + (wizData.zoneType==='row'?' selected':'') + '>صفوف محددة</option><option value="column"' + (wizData.zoneType==='column'?' selected':'') + '>أعمدة محددة</option><option value="cells"' + (wizData.zoneType==='cells'?' selected':'') + '>مربعات محددة (التحديد الحالي)</option></select>';
            html += '<p style="font-size:11px;color:#6B7280;margin-top:4px;">لـ "مربعات محددة": سيستخدم التحديد الحالي على الشبكة</p>';
            if(wizData.zoneType === 'row'){
                html += '<label>أرقام الصفوف (مفصولة بفاصلة)</label>';
                html += '<input type="text" id="pgWizRows" value="' + (wizData.zones.rows||[]).join(',') + '" placeholder="1,2,3">';
            } else if(wizData.zoneType === 'column'){
                html += '<label>أرقام الأعمدة (مفصولة بفاصلة)</label>';
                html += '<input type="text" id="pgWizCols" value="' + (wizData.zones.cols||[]).join(',') + '" placeholder="1,2,3">';
            }
        }

        content.innerHTML = html;

        // Bind step-specific events
        if(wizStep === 0){
            document.getElementById('pgWizName').oninput = function(){ wizData.name = this.value; };
            document.getElementById('pgWizColor').oninput = function(){ wizData.color = this.value; };
        } else if(wizStep === 1){
            content.querySelectorAll('.wiz-day').forEach(function(btn){
                btn.onclick = function(){
                    let d = parseInt(btn.dataset.d);
                    let idx = wizData.days.indexOf(d);
                    if(idx >= 0) wizData.days.splice(idx, 1);
                    else wizData.days.push(d);
                    btn.classList.toggle('active');
                };
            });
        } else if(wizStep === 2){
            content.querySelectorAll('.wiz-slot').forEach(function(btn){
                btn.onclick = function(){
                    let i = parseInt(btn.dataset.idx);
                    let s = SLOTS[i];
                    let existing = wizData.slots.findIndex(function(ws){ return ws.start === s.start; });
                    if(existing >= 0) wizData.slots.splice(existing, 1);
                    else wizData.slots.push(s);
                    btn.classList.toggle('active');
                    btn.style.background = btn.classList.contains('active') ? '#2563EB' : '#fff';
                    btn.style.color = btn.classList.contains('active') ? '#fff' : '';
                };
            });
        } else if(wizStep === 3){
            let actionSel = document.getElementById('pgWizAction');
            let groupWrap = document.getElementById('pgWizGroupWrap');
            actionSel.onchange = function(){
                wizData.action = this.value;
                groupWrap.style.display = this.value === 'training' ? '' : 'none';
            };
            groupWrap.style.display = wizData.action === 'training' ? '' : 'none';

            let zoneSel = document.getElementById('pgWizZoneType');
            zoneSel.onchange = function(){
                wizData.zoneType = this.value;
                renderWizStep();
            };
        }
    }

    function saveTemplate(){
        // Collect final step data
        if(wizStep === 3){
            wizData.action = document.getElementById('pgWizAction').value;
            if(wizData.action === 'training'){
                wizData.group_id = parseInt(document.getElementById('pgWizGroup').value) || null;
                if(!wizData.group_id){ alert('اختر مجموعة'); return; }
            }
            wizData.zoneType = document.getElementById('pgWizZoneType').value;
            if(wizData.zoneType === 'row'){
                let val = (document.getElementById('pgWizRows')?.value || '').split(',').map(function(x){ return parseInt(x.trim()) - 1; }).filter(function(x){ return !isNaN(x) && x >= 0; });
                wizData.zones = {rows: val};
            } else if(wizData.zoneType === 'column'){
                let val = (document.getElementById('pgWizCols')?.value || '').split(',').map(function(x){ return parseInt(x.trim()) - 1; }).filter(function(x){ return !isNaN(x) && x >= 0; });
                wizData.zones = {cols: val};
            } else if(wizData.zoneType === 'cells'){
                wizData.zones = buildCells();
            } else {
                wizData.zones = {};
            }
        }

        // Build entries array (one entry per day × slot combo)
        let entries = [];
        wizData.days.forEach(function(day){
            wizData.slots.forEach(function(slot){
                entries.push({
                    day_of_week: day,
                    start_time: slot.start + ':00',
                    end_time: slot.end + ':00',
                    zone_selection_type: wizData.zoneType,
                    zone_selection_json: wizData.zoneType === 'cells' ? wizData.zones : JSON.stringify(wizData.zones),
                    assignment_type: wizData.action,
                    group_id: wizData.group_id,
                    label: wizData.name,
                    notes: ''
                });
            });
        });

        apiPost('/api/sa/pool-grid/' + FACILITY_ID + '/templates', {
            name: wizData.name,
            description: '',
            color: wizData.color,
            entries: entries
        }).then(function(res){
            if(res.error){ alert(res.error); return; }
            toast('تم إنشاء القالب: ' + wizData.name, 'success');
            closeWizard();
            loadTemplates();
        });
    }

    // Global functions for template actions
    window.pgExpandTemplate = function(id){
        expandingTemplateId = id;
        let today = new Date().toISOString().slice(0,10);
        document.getElementById('pgExpandFrom').value = today;
        let twoWeeks = new Date(); twoWeeks.setDate(twoWeeks.getDate() + 14);
        document.getElementById('pgExpandTo').value = twoWeeks.toISOString().slice(0,10);
        document.getElementById('pgExpandModal').classList.add('show');
    };

    document.getElementById('pgExpandCancel').onclick = function(){
        document.getElementById('pgExpandModal').classList.remove('show');
    };

    document.getElementById('pgExpandConfirm').onclick = function(){
        let from = document.getElementById('pgExpandFrom').value;
        let to = document.getElementById('pgExpandTo').value;
        if(!from || !to){ alert('اختر التواريخ'); return; }
        if(from > to){ alert('تاريخ البداية يجب أن يكون قبل النهاية'); return; }
        document.getElementById('pgExpandModal').classList.remove('show');
        showLoading();
        apiPost('/api/sa/pool-grid/' + FACILITY_ID + '/templates/' + expandingTemplateId + '/expand', {
            from_date: from,
            to_date: to
        }).then(function(res){
            hideLoading();
            if(res.error){ alert(res.error); return; }
            toast('تم التوسيع: ' + (res.generated || 0) + ' مربع | تخطي: ' + (res.skipped || 0), 'success');
            loadState();
            loadTemplates();
        });
    };

    window.pgEditTemplate = function(id){
        toast('التعديل — قريباً', 'success');
    };

    window.pgDeleteTemplate = function(id){
        if(!confirm('هل تريد حذف هذا القالب؟')) return;
        apiPost('/api/sa/pool-grid/' + FACILITY_ID + '/templates/' + id + '/delete', {})
        .then(function(res){
            if(res.error){ alert(res.error); return; }
            toast('تم الحذف', 'success');
            loadTemplates();
        });
    };

    // --- API ---
    function loadState(){
        if(GRID_ROWS < 1 || GRID_COLS < 1){ renderGrid(); hideLoading(); return; }
        showLoading();
        let slot = firstActiveSlot();
        fetch('/api/sa/pool-grid/' + FACILITY_ID + '/state?date=' + encodeURIComponent(currentDate()) + '&start_time=' + encodeURIComponent(slot.start) + '&end_time=' + encodeURIComponent(slot.end), {
            headers: {'X-Requested-With': 'XMLHttpRequest'}
        })
        .then(function(r){ return r.json(); })
        .then(function(data){
            if(data.error){ toast(data.error, 'error'); hideLoading(); renderGrid(); return; }
            GRID_ROWS = data.rows || GRID_ROWS;
            GRID_COLS = data.cols || GRID_COLS;
            gridData = data.grid || {};
            renderGrid();
            hideLoading();
        })
        .catch(function(){ toast('خطأ في تحميل البيانات', 'error'); hideLoading(); });
    }

    function apiPost(url, body){
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': CSRF,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(body)
        }).then(function(r){ return r.json(); }).catch(function(){ return {error:'خطأ في الاتصال'}; });
    }

    function showLoading(){ loading.classList.remove('hidden'); }
    function hideLoading(){ loading.classList.add('hidden'); }

    function toast(msg, type){
        let el = document.createElement('div');
        el.style.cssText = 'position:fixed;top:20px;left:50%;transform:translateX(-50%);padding:12px 24px;border-radius:8px;font-size:14px;font-weight:500;z-index:9999;box-shadow:0 4px 12px rgba(0,0,0,.15);transition:opacity .3s;font-family:inherit;';
        el.style.background = type === 'success' ? '#D1FAE5' : '#FEE2E2';
        el.style.color = type === 'success' ? '#065F46' : '#991B1B';
        el.textContent = msg;
        document.body.appendChild(el);
        setTimeout(function(){ el.style.opacity = '0'; setTimeout(function(){ el.remove(); }, 300); }, 3000);
    }

    function esc(s){ return s ? String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;') : ''; }

    // --- Init ---
    if(GRID_ROWS > 0 && GRID_COLS > 0) loadState();
    else renderGrid();
    if(typeof lucide !== 'undefined') lucide.createIcons();
})();
</script>

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