<?php
/**
 * Decision-Driven Control Center for OTIS Life System
 */
?>
<style>
/* CSS styles for the dashboard */
.fade-in { animation: fadeIn 0.4s ease-in-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

/* Alert Color Variables */
.alert-red { background-color: #fee2e2; border-left: 4px solid #ef4444; color: #991b1b; }
.alert-yellow { background-color: #fef9c3; border-left: 4px solid #eab308; color: #854d0e; }
.alert-green { background-color: #dcfce3; border-left: 4px solid #22c55e; color: #166534; }

.quick-action-btn { transition: transform 0.15s ease-in-out; border: 2px solid transparent;}
.quick-action-btn:hover { transform: translateY(-3px); box-shadow: 0 6px 12px rgba(0,0,0,0.08); }

.pulse-primary { box-shadow: 0 0 0 0 rgba(13, 110, 253, 0.4); animation: pulse 2s infinite; }
@keyframes pulse { 0% { box-shadow: 0 0 0 0 rgba(13, 110, 253, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(13, 110, 253, 0); } 100% { box-shadow: 0 0 0 0 rgba(13, 110, 253, 0); } }

.widget { transition: opacity 0.3s; }
.widget.hidden { display: none !important; }

/* Custom larger checkboxes */
.form-check-input.huge-check {
    width: 1.5em;
    height: 1.5em;
    cursor: pointer;
    border-width: 2px;
}
.form-check-input.huge-check:checked {
    background-color: #198754;
    border-color: #198754;
}
</style>

<div class="row mb-3 mt-2 align-items-center">
    <div class="col-8">
        <h2 class="fw-bold mb-0 text-dark"><?= $timeContext ?>، <span class="text-primary"><?= htmlspecialchars($_SESSION['username'] ?? '') ?></span></h2>
    </div>
    <div class="col-4 text-end">
        <!-- Settings Toggle Dropdown -->
        <div class="dropdown">
            <button class="btn btn-light btn-sm rounded-circle shadow-sm" type="button" data-bs-toggle="dropdown" title="تخصيص لوحة القيادة"><i class="fa-solid fa-sliders"></i></button>
            <ul class="dropdown-menu dropdown-menu-end shadow-sm border-0 rounded-4" id="widget-toggles">
                <li class="dropdown-header fw-bold">تخصيص العرض</li>
                <li><label class="dropdown-item py-2" style="cursor:pointer;"><input type="checkbox" checked class="form-check-input widget-toggle me-2 border-secondary" data-target="widget-scorecard"> التقييم اليومي والمؤشرات</label></li>
                <li><label class="dropdown-item py-2" style="cursor:pointer;"><input type="checkbox" checked class="form-check-input widget-toggle me-2 border-secondary" data-target="widget-quick"> الإجراءات السريعة (أزرار)</label></li>
                <li><label class="dropdown-item py-2" style="cursor:pointer;"><input type="checkbox" checked class="form-check-input widget-toggle me-2 border-secondary" data-target="widget-tasks"> المهام والأهداف</label></li>
                <li><label class="dropdown-item py-2" style="cursor:pointer;"><input type="checkbox" checked class="form-check-input widget-toggle me-2 border-secondary" data-target="widget-context"> السياق اليومي (الأحداث/الصحة)</label></li>
            </ul>
        </div>
    </div>
</div>

<div id="liveFeedback" style="display:none;" class="alert alert-success shadow-sm rounded-3 fade-in py-2 px-3 fw-bold mb-4"></div>

<?php
/* ── SYSTEM RADAR WIDGET ─────────────────────────────────────── */
$radarColors = [
    'critical' => ['bg'=>'rgba(220,53,69,0.1)','border'=>'#dc3545','badge'=>'danger','icon'=>'fa-triangle-exclamation','text'=>'CRITICAL'],
    'warning'  => ['bg'=>'rgba(253,126,20,0.1)','border'=>'#fd7e14','badge'=>'warning','icon'=>'fa-bell','text'=>'WARNING'],
];

if (!empty($radarInsight)):
    $sev = strtolower($radarInsight['severity'] ?? $radarInsight['type'] ?? 'warning');
    $rc  = $radarColors[$sev] ?? $radarColors['warning'];
    $msg = htmlspecialchars($radarInsight['msg'] ?? $radarInsight['message'] ?? '');
    $icon= $radarInsight['icon'] ?? 'fa-robot';
?>
<div class="fade-in mb-4">
    <a href="<?= BASE_URL ?>/advisor" class="text-decoration-none">
        <div class="rounded-4 px-4 py-3 d-flex align-items-center gap-3 shadow-sm"
             style="background:<?= $rc['bg'] ?>; border:1px solid <?= $rc['border'] ?>; border-right:5px solid <?= $rc['border'] ?>;">
            <div style="font-size:1.5rem; color:<?= $rc['border'] ?>; flex-shrink:0;">
                <i class="fa-solid <?= $icon ?>"></i>
            </div>
            <div class="flex-grow-1">
                <div class="d-flex align-items-center gap-2 mb-1">
                    <span class="badge bg-<?= $rc['badge'] ?> rounded-pill" style="font-size:9px; letter-spacing:.5px;"><?= $rc['text'] ?></span>
                    <small class="text-muted fw-bold" style="font-size:10px;">رادار النظام الذكي</small>
                </div>
                <div class="fw-bold lh-sm" style="font-size:13px;"><?= $msg ?></div>
            </div>
            <div class="text-muted" style="flex-shrink:0; font-size:0.85rem;"><i class="fa-solid fa-chevron-left"></i></div>
        </div>
    </a>
</div>
<?php endif; ?>

<?php if (!empty($systemDecisions['budget_lock_suggested']) && $systemDecisions['budget_lock_suggested']): ?>
<div class="alert rounded-4 mb-4 fade-in d-flex align-items-center gap-3 shadow-sm"
     style="background:rgba(253,126,20,0.08); border:1px solid rgba(253,126,20,0.3); border-right:5px solid #fd7e14;">
    <i class="fa-solid fa-lock text-warning fs-5"></i>
    <div>
        <span class="fw-bold">العقل المحلل يقترح تجميد الإنفاق</span>
        <small class="d-block text-muted" style="font-size:11px;">رصد نمط إنفاق مرتفع — <a href="<?= BASE_URL ?>/advisor" class="text-warning fw-bold">راجع التحليل الكامل ←</a></small>
    </div>
</div>
<?php endif; ?>

<div id="dashboard-main-container">
    <script>
        // Synchronous reorder to prevent flicker
        (function() {
            const savedOrder = JSON.parse(localStorage.getItem('otis_dashboard_layout') || 'null');
            if (savedOrder && Array.isArray(savedOrder)) {
                // We will defer the reordering until DOM is parsed (but before paint)
                document.addEventListener('DOMContentLoaded', () => {
                    const container = document.getElementById('dashboard-main-container');
                    if (!container) return;
                    savedOrder.forEach(id => {
                        const el = document.getElementById(id);
                        if (el) container.appendChild(el);
                    });
                });
            }
        })();
    </script>

<!-- Streak Risk Alerts -->
<?php foreach ($streakRisks as $risk): ?>
<div class="row mb-2 fade-in">
    <div class="col-12">
        <div class="alert alert-warning border-0 shadow-sm rounded-4 py-2 px-3 fw-bold mb-0" style="border-right: 4px solid #ffc107;">
            <i class="fa-solid fa-triangle-exclamation me-2"></i> <?= htmlspecialchars($risk) ?>
        </div>
    </div>
</div>
<?php endforeach; ?>

<!-- 1. Smart Action Box + Advisor -->
<?php if($smartAction): ?>
<div class="dashboard-widget-wrapper position-relative" id="widget-smart-wrapper">
    <div class="position-absolute drag-handle text-muted" style="right: 15px; top: 15px; cursor: grab; z-index: 10;"><i class="fa-solid fa-grip px-2 py-1 bg-light rounded shadow-sm opacity-50"></i></div>
    <div class="row mb-3 fade-in">
        <div class="col-12">
            <div class="alert alert-<?= $smartAction['type'] ?> border-0 shadow-sm rounded-4 d-flex align-items-center mb-2 px-4 py-3" style="border-right: 6px solid var(--bs-<?= $smartAction['type'] ?>);">
                <div class="fs-2 me-3"><i class="fa-solid <?= $smartAction['icon'] ?>"></i></div>
                <div>
                    <h6 class="fw-bold mb-1 opacity-75">توجيه صانع القرار</h6>
                    <div class="mb-0 fs-5 fw-bold"><?= htmlspecialchars($smartAction['text']) ?></div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- 2. Quick Actions -->
<div class="dashboard-widget-wrapper position-relative" id="widget-quick-wrapper">
    <div class="position-absolute drag-handle text-muted" style="right: 5px; top: -10px; cursor: grab; z-index: 10;"><i class="fa-solid fa-grip px-2 py-1 bg-light rounded shadow-sm opacity-50"></i></div>
    <div class="row mb-4 g-2 fade-in widget" id="widget-quick">
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/todo" class="btn btn-primary w-100 py-3 rounded-4 quick-action-btn fw-bold shadow-sm">
            <i class="fa-solid fa-plus d-block fs-4 mb-2"></i> إضافة مهمة
        </a>
    </div>
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/finance" class="btn btn-success text-white w-100 py-3 rounded-4 quick-action-btn fw-bold shadow-sm">
            <i class="fa-solid fa-money-bill-transfer d-block fs-4 mb-2"></i> تسجيل مصروف
        </a>
    </div>
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/health" class="btn btn-warning text-dark w-100 py-3 rounded-4 quick-action-btn fw-bold shadow-sm">
            <i class="fa-solid fa-apple-whole d-block fs-4 mb-2"></i> تسجيل وجبة/ماء
        </a>
    </div>
    <div class="col-6 col-md-3">
        <a href="<?= BASE_URL ?>/behavior" class="btn btn-dark w-100 py-3 rounded-4 quick-action-btn fw-bold shadow-sm">
            <i class="fa-solid fa-brain d-block fs-4 mb-2"></i> تسجيل سلوك
        </a>
    </div>
    <div class="col-12 mt-2">
        <a href="<?= BASE_URL ?>/advisor" class="btn w-100 py-3 rounded-4 quick-action-btn fw-bold shadow-sm text-white" style="background-color: #818cf8; border-color: #818cf8;">
            <i class="fa-solid fa-robot d-block fs-4 mb-2"></i> المستشار الذكي
        </a>
    </div>
</div>
</div>

<!-- 3. Daily Score & At-A-Glance -->
<div class="dashboard-widget-wrapper position-relative" id="widget-scorecard-wrapper">
    <div class="position-absolute drag-handle text-muted" style="right: 5px; top: -10px; cursor: grab; z-index: 10;"><i class="fa-solid fa-grip px-2 py-1 bg-light rounded shadow-sm opacity-50"></i></div>
    <div class="row mb-4 fade-in widget" id="widget-scorecard">
    <div class="col-12 col-md-3 mb-3 mb-md-0">
        <div class="card border-0 shadow-sm rounded-4 h-100 text-center text-white <?= $dailyScore >= 80 ? 'bg-success' : ($dailyScore >= 50 ? 'bg-primary' : 'bg-dark') ?>">
            <div class="card-body d-flex flex-column justify-content-center p-4">
                <div class="opacity-75 mb-1 fw-bold"><i class="fa-solid fa-gauge-high"></i> نسبة إنجاز اليوم</div>
                <div class="display-4 fw-bold"><?= $dailyScore ?>%</div>
            </div>
        </div>
    </div>
    <div class="col-12 col-md-9">
        <div class="row g-2 h-100">
            <!-- Finance -->
            <div class="col-6 col-md-3">
                <div class="card border-0 bg-white shadow-sm rounded-4 h-100 p-3 text-center <?= $spentToday > 500 ? 'border border-danger border-2' : '' ?>">
                    <div class="bg-light rounded-circle d-inline-flex mx-auto mb-2 align-items-center justify-content-center" style="width:45px; height:45px;">
                        <i class="fa-solid fa-wallet text-secondary fs-5"></i>
                    </div>
                    <small class="d-block text-secondary fw-bold">صرف اليوم</small>
                    <strong class="fs-5 <?= $spentToday > 500 ? 'text-danger' : 'text-dark' ?>"><?= $spentToday ?> <span class="fs-7">ج</span></strong>
                </div>
            </div>
            <!-- Spiritual -->
            <?php
            $sColors = ['high' => 'success', 'medium' => 'warning', 'low' => 'secondary'];
            $sTerms = ['high' => 'مرتفع', 'medium' => 'متوازن', 'low' => 'هادئ'];
            $scColor = $sColors[$spiritualState ?? 'medium'];
            $scTerm = $sTerms[$spiritualState ?? 'medium'];
            ?>
            <div class="col-6 col-md-3">
                <a href="<?= BASE_URL ?>/spiritual" class="text-decoration-none">
                    <div class="card border-0 bg-white shadow-sm rounded-4 h-100 p-3 text-center transition-all <?= $spiritualState == 'low' ? 'border border-warning border-2' : '' ?>">
                        <div class="bg-<?= $scColor ?> bg-opacity-10 rounded-circle d-inline-flex mx-auto mb-2 align-items-center justify-content-center" style="width:45px; height:45px;">
                            <i class="fa-solid fa-kaaba text-<?= $scColor ?> fs-5"></i>
                        </div>
                        <small class="d-block text-secondary fw-bold">حالة الروحانيات</small>
                        <strong class="fs-5 text-<?= $scColor ?>"><?= $scTerm ?></strong>
                        <div class="mt-1">
                            <small class="text-muted fw-bold" style="font-size: 0.75rem;">استمرارية <?= $spiritualConsistency ?? 50 ?>%</small>
                        </div>
                    </div>
                </a>
            </div>
            <!-- DES: Unified Discipline & Identity -->
            <div class="col-6 col-md-3">
                <div class="card border-0 bg-white shadow-sm rounded-4 h-100 p-3 text-center position-relative overflow-hidden">
                    <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex mx-auto mb-2 align-items-center justify-content-center" style="width:45px; height:45px;">
                        <i class="fa-solid fa-gauge-high text-primary fs-5"></i>
                    </div>
                    <small class="d-block text-secondary fw-bold">الانضباط الكلي</small>
                    <strong class="fs-5 text-dark"><?= $disciplineScore ?>%</strong>
                    <div class="mt-1">
                        <small class="text-info fw-bold" style="font-size: 0.75rem;"><?= $identityNarrative ?></small>
                    </div>
                </div>
            </div>
            <!-- Health -->
            <div class="col-6 col-md-3">
                <div class="card border-0 bg-white shadow-sm rounded-4 h-100 p-3 text-center">
                    <div class="bg-light rounded-circle d-inline-flex mx-auto mb-2 align-items-center justify-content-center" style="width:45px; height:45px;">
                        <i class="fa-solid fa-droplet text-secondary fs-5"></i>
                    </div>
                    <small class="d-block text-secondary fw-bold">الماء</small>
                    <strong class="fs-5 text-info"><?= $waterToday ?> <span class="fs-7">أكواب</span></strong>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<div class="dashboard-widget-wrapper position-relative" id="widget-tasks-wrapper">
    <div class="position-absolute drag-handle text-muted" style="right: -5px; top: -10px; cursor: grab; z-index: 10;"><i class="fa-solid fa-grip px-2 py-1 bg-light rounded shadow-sm opacity-50"></i></div>
<div class="row g-4 fade-in">
    <!-- 4. Priority & Focus (Left) OR Evening Mode Review -->
    <div class="col-lg-8 widget" id="widget-tasks">
        
        <?php if ($isEveningMode): ?>
            <!-- Evening Mode / Daily Review -->
            <div class="card border-0 shadow-sm rounded-4 text-white p-5 text-center" style="background: linear-gradient(135deg, #2c3e50, #34495e);">
                <div class="display-3 mb-3">🌙</div>
                <h3 class="fw-bold mb-3">تقييم اليوم</h3>
                <p class="text-light text-opacity-75 fs-5 mb-4">انتهى يومك تقريباً. انتقل إلى مركز العمليات لتقييم إنجازاتك وتدوين يومك.</p>
                <div class="d-flex justify-content-center gap-3">
                    <a href="<?= BASE_URL ?>/journal" class="btn btn-warning rounded-pill px-5 py-3 fw-bold fs-5 text-dark shadow"><i class="fa-solid fa-pen-fancy me-2"></i> الشروع في التقييم واليومية</a>
                </div>
                <?php if ($tasksTotal > 0 && $tasksDone < $tasksTotal): ?>
                    <p class="mt-4 text-warning fw-bold fs-7 mb-0"><i class="fa-solid fa-triangle-exclamation me-1"></i> لا يزال هناك دورة مهام مفتوحة (<?= $tasksTotal - $tasksDone ?> مهام متبقية).</p>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <!-- Normal Focus Column -->
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h5 class="fw-bold text-dark mb-0"><i class="fa-solid fa-bullseye text-primary me-2"></i> بؤرة التركيز</h5>
            </div>

            <?php if ($primaryTask): ?>
                <div class="card border-primary shadow rounded-4 mb-4 pulse-primary bg-primary bg-opacity-10 position-relative overflow-hidden">
                    <div class="position-absolute" style="top: -20px; right: -20px; font-size: 8rem; opacity: 0.05;">
                        <i class="fa-solid fa-bolt"></i>
                    </div>
                    <div class="card-body p-4 d-flex align-items-center">
                        <input type="checkbox" class="form-check-input huge-check mx-3 mt-0" onchange="completeTask(<?= $primaryTask->id ?>, this)">
                        <div class="flex-grow-1 ms-2">
                            <span class="badge bg-danger mb-2 position-relative z-1 px-3 py-2 rounded-pill"><i class="fa-solid fa-fire me-1"></i> أولوية قصوى</span>
                            <h3 class="fw-bold text-dark mb-2 position-relative z-1"><?= htmlspecialchars($primaryTask->title) ?></h3>
                            <div class="d-flex gap-2 text-dark opacity-75 fw-bold position-relative z-1">
                                <span><i class="fa-solid fa-folder me-1"></i> <?= htmlspecialchars($primaryTask->category) ?></span>
                                <?php if ($primaryTask->estimated_time > 0): ?>
                                    <span>• <i class="fa-regular fa-clock me-1"></i> <?= $primaryTask->estimated_time ?> دق</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php elseif ($tasksTotal > 0 && $tasksDone === $tasksTotal): ?>
                <div class="card border-0 shadow-sm rounded-4 p-5 text-center bg-success bg-opacity-10 mb-4">
                    <div class="fs-1 mb-2">🏆</div>
                    <h4 class="fw-bold text-success mb-0">تم إنجاز كل مهام اليوم بنجاح وامتياز.</h4>
                </div>
            <?php else: ?>
                <div class="card border-0 shadow-sm rounded-4 p-5 text-center bg-white mb-4">
                    <div class="fs-1 text-muted opacity-25 mb-3"><i class="fa-solid fa-list-check"></i></div>
                    <p class="mb-0 text-muted fw-bold">قائمة التركيز فارغة حالياً.</p>
                </div>
            <?php endif; ?>

            <!-- Pending list -->
            <?php if (count($pendingTasks) > ($primaryTask ? 1 : 0)): ?>
                <h6 class="fw-bold text-secondary mb-3"><i class="fa-solid fa-list-ul me-2"></i> مهام قيد الانتظار</h6>
                <div class="card border-0 shadow-sm rounded-4 bg-white">
                    <ul class="list-group list-group-flush rounded-4">
                        <?php foreach($pendingTasks as $t): 
                            if ($primaryTask && $t->id == $primaryTask->id) continue;
                        ?>
                        <li class="list-group-item d-flex align-items-center p-3 border-light py-3 hover-bg-light transition-all">
                            <input type="checkbox" class="form-check-input huge-check mx-3 mt-0" onchange="completeTask(<?= $t->id ?>, this)">
                            <div>
                                <h6 class="mb-1 fw-bold text-dark fs-5"><?= htmlspecialchars($t->title) ?></h6>
                                <small class="text-secondary fw-bold"><i class="fa-solid fa-tag me-1 text-muted"></i> <?= htmlspecialchars($t->category) ?> <?= $t->estimated_time ? " • <i class='fa-regular fa-clock me-1'></i> {$t->estimated_time} دق" : "" ?></small>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- 5. Context & Alerts (Right) -->
    <div class="col-lg-4 widget" id="widget-context">
        <h6 class="fw-bold text-secondary mb-3"><i class="fa-solid fa-compass me-2"></i> سياق اليوم</h6>
        
        <?php foreach ($healthAlerts as $a): ?>
            <div class="alert alert-<?= $a['type'] ?> border-0 shadow-sm rounded-4 py-3 px-3 fw-bold d-flex align-items-start mb-3" style="border-right: 4px solid var(--bs-<?= $a['type'] ?>);">
                <i class="fa-solid <?= $a['type'] == 'warning' ? 'fa-triangle-exclamation' : 'fa-info-circle' ?> ms-0 me-3 mt-1 fs-5"></i> 
                <span><?= htmlspecialchars($a['text']) ?></span>
            </div>
        <?php endforeach; ?>

        <div class="card border-0 shadow-sm rounded-4 bg-white mb-3">
            <div class="card-body p-4">
                <h6 class="fw-bold text-dark border-bottom pb-2 mb-3"><i class="fa-regular fa-calendar me-2 text-primary"></i> المواعيد المجدولة</h6>
                <?php if (empty($todayEvents)): ?>
                    <div class="text-center py-3 text-muted">
                        <i class="fa-regular fa-calendar-xmark fa-2x mb-2 opacity-25 d-block"></i>
                        <span class="fs-7 fw-bold">لا يوجد التزامات مجدولة.</span>
                    </div>
                <?php else: ?>
                    <ul class="list-unstyled mb-0">
                        <?php foreach ($todayEvents as $ev): ?>
                        <li class="d-flex align-items-start gap-3 mb-3 bg-light p-2 rounded-3">
                            <span class="badge text-dark bg-white border shadow-sm px-2 py-2 text-wrap" style="min-width:55px;">
                                <i class="fa-regular fa-clock d-block mb-1 opacity-50"></i>
                                <?= $ev->start_time ? date('H:i', strtotime($ev->start_time)) : 'اليوم' ?>
                            </span>
                            <div class="ps-2" style="border-right: 4px solid <?= htmlspecialchars($ev->color_hex ?: '#0d6efd') ?>;">
                                <div class="fw-bold text-dark lh-sm mb-1"><?= htmlspecialchars($ev->title) ?></div>
                                <small class="text-secondary opacity-75 d-block" style="font-size:0.7rem;"><i class="fa-solid fa-tag me-1"></i><?= htmlspecialchars($ev->category) ?></small>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
</div> <!-- End Tasks Wrapper -->
</div> <!-- End Dashboard Sortable Container -->


<script>
// Live Feedback for task completion
function displayFeedback(msg) {
    const feedback = document.getElementById('liveFeedback');
    feedback.innerHTML = `<i class="fa-solid fa-check-circle me-2"></i>` + msg;
    feedback.style.display = 'block';
    setTimeout(() => {
        feedback.style.display = 'none';
        window.location.reload(); 
    }, 1000);
}

// Complete Task Action
function completeTask(id, checkbox) {
    checkbox.disabled = true;
    const row = checkbox.closest('.card, .list-group-item');
    if (row) row.style.opacity = '0.5';

    displayFeedback('تم إنجاز المهمة بنجاح!');
    
    fetch(`<?= BASE_URL ?>/todo/updateStatus`, { 
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ task_id: id, status: 'done', target_date: '<?= date('Y-m-d') ?>' })
    }).catch(console.error);
}

// Widget Toggles Personalization
document.addEventListener('DOMContentLoaded', () => {
    const toggles = document.querySelectorAll('.widget-toggle');
    
    // Load state
    toggles.forEach(toggle => {
        const targetId = toggle.getAttribute('data-target');
        const state = localStorage.getItem('dashboard_widget_' + targetId);
        if (state === 'hidden') {
            toggle.checked = false;
            document.getElementById(targetId)?.classList.add('hidden');
        }
        
        toggle.addEventListener('change', (e) => {
            const checked = e.target.checked;
            const target = document.getElementById(targetId);
            if (checked) {
                target?.classList.remove('hidden');
                localStorage.setItem('dashboard_widget_' + targetId, 'visible');
            } else {
                target?.classList.add('hidden');
                localStorage.setItem('dashboard_widget_' + targetId, 'hidden');
            }
        });
    });
    // Drag & Drop Layout Personalization
    if (typeof Sortable !== 'undefined') {
        const sortableContainer = document.getElementById('dashboard-main-container');
        if (sortableContainer) {
            new Sortable(sortableContainer, {
                animation: 250,
                handle: '.drag-handle',
                ghostClass: 'opacity-50',
                onEnd: function () {
                    const order = [];
                    document.querySelectorAll('.dashboard-widget-wrapper').forEach(el => {
                        if (el.id) order.push(el.id);
                    });
                    localStorage.setItem('otis_dashboard_layout', JSON.stringify(order));
                    // Sync to DB
                    fetch('<?= BASE_URL ?>/system/saveDashboardLayout', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify({ layout: order })
                    }).catch(console.error);
                }
            });
        }
    }
});
</script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
