<?php
/**
 * TASK INTELLIGENCE ENGINE — Redesigned Dashboard
 * Categories as cards | Completed section | Edit Task | Edit Categories
 */
$prevDay = date('Y-m-d', strtotime($targetDate . ' -1 day'));
$nextDay = date('Y-m-d', strtotime($targetDate . ' +1 day'));
$today   = date('Y-m-d');
$isToday = ($targetDate === $today);

$priorityProps = [
    'high'   => ['badge'=>'danger',  'icon'=>'fa-fire',  'name'=>'قصوى'],
    'medium' => ['badge'=>'warning', 'icon'=>'fa-bolt',  'name'=>'متوسطة'],
    'low'    => ['badge'=>'success', 'icon'=>'fa-leaf',  'name'=>'عادية'],
];

// Build catMap
$catMap = [];
if (!empty($customCategories)) {
    foreach ($customCategories as $c) {
        $key = $c->system_key ?: 'cat_'.$c->id;
        $catMap[$key] = [
            'id'     => $c->id,
            'name'   => $c->name,
            'bg'     => $c->bg_color,
            'text'   => $c->text_color,
            'border' => $c->border_color,
        ];
    }
}
$catFallback = ['id'=>0,'name'=>'عام','bg'=>'#f3f4f6','text'=>'#475569','border'=>'#e2e8f0'];

// Split tasks: pending vs done
$pendingTasks   = array_filter($regularTasks, fn($t) => $t->status !== 'done');
$completedTasks_list = array_filter($regularTasks, fn($t) => $t->status === 'done');

// Group pending by category
$grouped = [];
foreach ($pendingTasks as $t) {
    $cat = $t->category ?? 'other';
    $grouped[$cat][] = $t;
}
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap');

* { box-sizing: border-box; }
body { font-family: 'Tajawal', sans-serif; background: #f0f4f8; }

/* ── Header ── */
.todo-header { background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #fff; border-radius: 20px; padding: 24px 30px; margin-bottom: 28px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px; box-shadow: 0 10px 40px rgba(15,23,42,.25); }
.todo-header h1 { font-size: 1.6rem; font-weight: 900; margin: 0; letter-spacing: -0.5px; }
.todo-header p  { margin: 4px 0 0; font-size: .9rem; opacity: .65; }

/* Nav arrows */
.nav-arrows { display: flex; align-items: center; background: rgba(255,255,255,.1); backdrop-filter: blur(8px); padding: 6px 10px; border-radius: 50px; gap: 6px; }
.nav-arrows a { width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; opacity: .7; transition: .2s; text-decoration: none; }
.nav-arrows a:hover { opacity: 1; background: rgba(255,255,255,.15); }
.nav-arrows input[type=date] { background: transparent; border: none; color: #fff; font-family: 'Tajawal', sans-serif; font-weight: 800; font-size: 1rem; width: 130px; text-align: center; cursor: pointer; }
.nav-arrows input[type=date]::-webkit-calendar-picker-indicator { filter: invert(1); opacity: .6; cursor: pointer; }

/* ── Stat Widgets ── */
.stat-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; margin-bottom: 28px; }
.stat-card { background: #fff; border-radius: 16px; padding: 20px 22px; box-shadow: 0 4px 20px rgba(0,0,0,.04); border: 1px solid #e8edf2; display: flex; align-items: center; gap: 16px; }
.stat-icon { width: 52px; height: 52px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.4rem; flex-shrink: 0; }
.stat-val { font-size: 1.8rem; font-weight: 900; line-height: 1; color: #0f172a; }
.stat-lbl { font-size: .78rem; font-weight: 700; color: #94a3b8; text-transform: uppercase; letter-spacing: .8px; margin-top: 3px; }

/* Momentum ring */
.momentum-card { background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); color: #fff; }
.momentum-card .stat-val, .momentum-card .stat-lbl { color: #fff; }
.momentum-card .stat-icon { background: rgba(255,255,255,.2); color: #fff; }
.ring-wrap { position: relative; width: 52px; height: 52px; flex-shrink: 0; }
.ring-wrap svg { transform: rotate(-90deg); }
.ring-wrap .ring-text { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: .75rem; font-weight: 900; color: #fff; }

/* ── Quick Add Form ── */
.quick-add-box { background: #fff; border-radius: 16px; padding: 18px 20px; margin-bottom: 28px; box-shadow: 0 4px 20px rgba(0,0,0,.04); border: 1px solid #e8edf2; }
.quick-add-box h6 { font-weight: 800; color: #3b82f6; margin-bottom: 12px; font-size: .9rem; }
.quick-input-row { display: flex; gap: 10px; flex-wrap: wrap; align-items: stretch; }
.quick-input-row input[name=title] { flex: 1; min-width: 200px; border-radius: 50px; border: 2px solid #e2e8f0; padding: 10px 20px; font-family: 'Tajawal', sans-serif; font-size: .95rem; transition: border .2s; }
.quick-input-row input[name=title]:focus { border-color: #3b82f6; outline: none; }
.quick-meta { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-top: 10px; }
.quick-meta select { border: 1.5px solid #e2e8f0; border-radius: 50px; padding: 6px 14px; font-family: 'Tajawal', sans-serif; font-size: .85rem; font-weight: 700; color: #475569; cursor: pointer; background: #f8fafc; }
.btn-add-task { background: linear-gradient(135deg, #3b82f6, #2563eb); color: #fff; border: none; border-radius: 50px; padding: 10px 24px; font-family: 'Tajawal', sans-serif; font-weight: 800; font-size: .95rem; cursor: pointer; transition: .2s; white-space: nowrap; }
.btn-add-task:hover { transform: scale(1.03); box-shadow: 0 8px 20px rgba(59,130,246,.4); }

/* ── Focus Zone ── */
.focus-zone { background: linear-gradient(135deg, #f8fafc 0%, #eff6ff 100%); border: 2px dashed #93c5fd; border-radius: 20px; padding: 24px; margin-bottom: 28px; box-shadow: 0 4px 20px rgba(59,130,246,.05); position: relative; transition: all .3s; }
.focus-zone:hover { border-color: #3b82f6; box-shadow: 0 8px 30px rgba(59,130,246,.12); background: linear-gradient(135deg, #fff 0%, #eff6ff 100%); }
.focus-zone h5 { font-weight: 900; color: #1e40af; margin-bottom: 18px; font-size: 1.15rem; display: flex; align-items: center; justify-content: flex-start; gap: 8px; }
.focus-tasks-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 12px; min-height: 60px; }
.focus-empty { text-align: center; color: #60a5fa; padding: 20px; font-weight: 700; font-size: .95rem; background: rgba(255,255,255,.6); border-radius: 12px; border: 1px solid rgba(255,255,255,.8); box-shadow: inset 0 2px 10px rgba(59,130,246,.05); }

/* ── Category Grid ── */
.cats-section-header { font-weight: 800; color: #0f172a; margin-bottom: 16px; font-size: 1.05rem; }
.cats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; align-items: start; }
@media (max-width: 1199px) { .cats-grid { grid-template-columns: repeat(2, 1fr); } }
@media (max-width: 640px)  { .cats-grid { grid-template-columns: 1fr; } }

/* ── Category Card Accordion ── */
.cat-card { background: #fff; border-radius: 18px; box-shadow: 0 4px 20px rgba(0,0,0,.04); border: 1px solid #e8edf2; overflow: hidden; }
.cat-card-header { padding: 13px 18px; display: flex; align-items: center; justify-content: space-between; cursor: pointer; user-select: none; transition: background .15s; }
.cat-card-header:hover { background: #f8fafc; }
.cat-card-title { font-weight: 800; font-size: .95rem; display: flex; align-items: center; gap: 9px; flex: 1; min-width: 0; }
.cat-dot { width: 11px; height: 11px; border-radius: 50%; display: inline-block; flex-shrink: 0; }
.cat-count { font-size: .7rem; font-weight: 700; padding: 2px 9px; border-radius: 50px; white-space: nowrap; }
.cat-chevron { font-size: .75rem; color: #94a3b8; transition: transform .3s cubic-bezier(.4,0,.2,1); flex-shrink: 0; margin-right: 4px; }
.cat-card.open .cat-chevron { transform: rotate(180deg); }

/* Smooth accordion body */
.cat-collapse { display: grid; grid-template-rows: 0fr; transition: grid-template-rows .32s cubic-bezier(.4,0,.2,1); }
.cat-collapse.open { grid-template-rows: 1fr; }
.cat-collapse-inner { overflow: hidden; }
.cat-tasks-wrap { padding: 12px 14px 10px; display: flex; flex-direction: column; gap: 9px; }
.cat-empty { text-align: center; color: #cbd5e1; padding: 16px 10px; font-size: .85rem; font-weight: 600; }

/* ── Task Card (inside category) ── */
.task-card { background: #fafbfc; border: 1px solid #eef2f7; border-radius: 12px; padding: 12px 14px; display: flex; align-items: flex-start; gap: 12px; transition: all .25s; position: relative; }
.task-card:hover { background: #fff; box-shadow: 0 6px 20px rgba(0,0,0,.07); border-color: #d1d9e6; transform: translateY(-1px); }
.task-card.completed-card { opacity: .45; }

/* Custom checkbox */
.task-cb { appearance: none; -webkit-appearance: none; width: 20px; height: 20px; border-radius: 50%; border: 2px solid #cbd5e1; cursor: pointer; flex-shrink: 0; margin-top: 2px; transition: .2s; position: relative; }
.task-cb:checked { background: #22c55e; border-color: #22c55e; }
.task-cb:checked::after { content: '✓'; color: #fff; font-size: .7rem; font-weight: 900; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
.task-cb:hover:not(:checked) { border-color: #94a3b8; background: #f1f5f9; }

.task-body { flex: 1; min-width: 0; }
.task-name { font-weight: 700; font-size: .95rem; color: #1e293b; margin-bottom: 6px; word-break: break-word; line-height: 1.4; }
.task-name.done-name { text-decoration: line-through; color: #94a3b8; }
.task-badges { display: flex; flex-wrap: wrap; gap: 6px; }
.tbadge { font-size: .7rem; font-weight: 700; padding: 2px 9px; border-radius: 50px; display: inline-flex; align-items: center; gap: 4px; }
.tbadge-danger  { background: #fef2f2; color: #dc2626; }
.tbadge-warning { background: #fffbeb; color: #d97706; }
.tbadge-success { background: #f0fdf4; color: #16a34a; }
.tbadge-gray    { background: #f1f5f9; color: #64748b; }
.tbadge-over    { background: #dc2626; color: #fff; }

.task-actions { display: flex; flex-direction: column; align-items: center; gap: 4px; opacity: 0; transition: opacity .2s; }
.task-card:hover .task-actions { opacity: 1; }
.act-btn { background: none; border: none; cursor: pointer; width: 28px; height: 28px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: .8rem; transition: .15s; }
.act-btn.edit   { color: #3b82f6; } .act-btn.edit:hover   { background: #eff6ff; }
.act-btn.star   { color: #f59e0b; } .act-btn.star:hover   { background: #fffbeb; }
.act-btn.del    { color: #ef4444; } .act-btn.del:hover    { background: #fef2f2; }

/* ── Done card inside grid ── */
.done-grid-card { background: linear-gradient(145deg, #f0fdf4 0%, #dcfce7 100%) !important; border: 2px solid #86efac !important; }
.done-grid-card .cat-card-header { background: transparent; border-bottom: 1px solid rgba(134,239,172,.4); }
.done-grid-card .cat-card-header:hover { background: rgba(255,255,255,.5); }
.done-grid-card .cat-card-title { color: #15803d; }
.done-grid-card .cat-chevron { color: #4ade80; }

.done-item { background: rgba(255,255,255,.65); border: 1px solid rgba(134,239,172,.5); border-radius: 11px; padding: 10px 14px; display: flex; align-items: center; gap: 10px; transition: all .2s; }
.done-item:hover { background: #fff; box-shadow: 0 4px 14px rgba(34,197,94,.12); }
.done-item-check { color: #22c55e; font-size: 1.05rem; flex-shrink: 0; }
.done-item-name { font-weight: 700; font-size: .88rem; text-decoration: line-through; color: #6b7280; flex: 1; min-width: 0; word-break: break-word; line-height: 1.4; }
.done-item-cat { font-size: .68rem; font-weight: 700; padding: 2px 8px; border-radius: 50px; background: rgba(34,197,94,.1); color: #16a34a; white-space: nowrap; }

/* ── Overdue Strip ── */
.overdue-strip { background: #fef2f2; border: 1px solid #fecaca; border-right: 4px solid #ef4444; border-radius: 14px; padding: 14px 18px; margin-bottom: 22px; display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }

/* ── Modals ── */
.modal-header-custom { background: linear-gradient(135deg, #1e293b, #0f172a); color: #fff; border-radius: 16px 16px 0 0; padding: 18px 24px; }
.modal-body-custom { padding: 24px; }
.form-label-custom { font-weight: 700; color: #374151; font-size: .9rem; margin-bottom: 5px; }
.form-ctrl-custom { border: 1.5px solid #e2e8f0; border-radius: 10px; padding: 10px 14px; width: 100%; font-family: 'Tajawal', sans-serif; font-size: .95rem; transition: border .2s; }
.form-ctrl-custom:focus { border-color: #3b82f6; outline: none; box-shadow: 0 0 0 3px rgba(59,130,246,.15); }
.cat-edit-row { display: flex; align-items: center; gap: 10px; padding: 10px 0; border-bottom: 1px solid #f1f5f9; }
.cat-edit-row:last-child { border-bottom: none; }
.cat-color-dot { width: 14px; height: 14px; border-radius: 50%; flex-shrink: 0; }
.cat-name-input { flex: 1; border: 1.5px solid #e2e8f0; border-radius: 8px; padding: 7px 12px; font-family: 'Tajawal', sans-serif; font-weight: 700; font-size: .9rem; }
.cat-name-input:focus { border-color: #3b82f6; outline: none; }
.cat-save-btn { background: #3b82f6; color: #fff; border: none; border-radius: 8px; padding: 7px 14px; font-family: 'Tajawal', sans-serif; font-weight: 700; font-size: .85rem; cursor: pointer; transition: .2s; }
.cat-save-btn:hover { background: #2563eb; }
.cat-saved-badge { display: none; font-size: .8rem; font-weight: 700; color: #22c55e; }

/* Responsive */
@media (max-width: 640px) {
    .todo-header { flex-direction: column; text-align: center; }
    .stat-row { grid-template-columns: 1fr 1fr; }
    .focus-tasks-grid { grid-template-columns: 1fr; }
    .task-actions { opacity: 1; }
}
</style>

<div class="container-fluid py-3 px-3 px-md-4">

    <!-- OVERDUE STRIP -->
    <?php if(!empty($overdueTasks)): ?>
    <div class="overdue-strip">
        <div class="d-flex align-items-center gap-3">
            <div style="width:38px;height:38px;background:#fecaca;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
                <i class="fa-solid fa-triangle-exclamation text-danger"></i>
            </div>
            <div>
                <div class="fw-bold text-danger" style="font-size:.95rem;">لديك <?= count($overdueTasks) ?> مهمة متأخرة!</div>
                <div class="text-muted" style="font-size:.82rem;">لم تُنجز في وقتها — اعالجها الآن.</div>
            </div>
        </div>
        <button class="btn btn-danger btn-sm rounded-pill fw-bold" data-bs-toggle="modal" data-bs-target="#overdueModal">
            <i class="fa-solid fa-bolt me-1"></i> معالجة الآن
        </button>
    </div>
    <?php endif; ?>

    <!-- HEADER -->
    <div class="todo-header">
        <div>
            <h1>محرك المهام <i class="fa-solid fa-bolt text-warning ms-1" style="font-size:1.3rem;"></i></h1>
            <p>تخطيط ذكي، تنفيذ دقيق، زخم مستمر.</p>
        </div>
        <div class="nav-arrows">
            <a href="<?= BASE_URL ?>/todo/index?date=<?= $prevDay ?>"><i class="fa-solid fa-chevron-right"></i></a>
            <input type="date" value="<?= $targetDate ?>" onchange="window.location.href='<?= BASE_URL ?>/todo/index?date='+this.value">
            <a href="<?= BASE_URL ?>/todo/index?date=<?= $nextDay ?>"><i class="fa-solid fa-chevron-left"></i></a>
        </div>
        <div class="d-flex gap-2 flex-wrap justify-content-center">
            <button class="btn btn-sm rounded-pill fw-bold" style="background:rgba(255,255,255,.15);color:#fff;border:1px solid rgba(255,255,255,.25);" data-bs-toggle="modal" data-bs-target="#catModal">
                <i class="fa-solid fa-tags me-1"></i> إدارة التصنيفات
            </button>
            <a href="<?= BASE_URL ?>/todo/focus" class="btn btn-sm rounded-pill fw-bold" style="background:rgba(251,191,36,.2);color:#fbbf24;border:1px solid rgba(251,191,36,.3);">
                <i class="fa-solid fa-crosshairs me-1"></i> Zen Mode
            </a>
            <?php if(!$isToday): ?>
            <a href="<?= BASE_URL ?>/todo/index?date=<?= $today ?>" class="btn btn-sm rounded-pill fw-bold" style="background:rgba(255,255,255,.15);color:#fff;border:1px solid rgba(255,255,255,.25);">اليوم</a>
            <?php else: ?>
            <a href="<?= BASE_URL ?>/journal/manage" class="btn btn-sm rounded-pill fw-bold" style="background:rgba(255,255,255,.15);color:#fff;border:1px solid rgba(255,255,255,.25);">
                <i class="fa-solid fa-book-journal-whills me-1"></i> إغلاق اليوم
            </a>
            <?php endif; ?>
        </div>
    </div>

    <?= display_flash_message('todo') ?>

    <!-- STATS -->
    <div class="stat-row">
        <!-- Momentum -->
        <div class="stat-card momentum-card">
            <div class="ring-wrap">
                <svg width="52" height="52" viewBox="0 0 52 52">
                    <circle cx="26" cy="26" r="21" stroke="rgba(255,255,255,.25)" stroke-width="5" fill="none"/>
                    <circle id="momentumRing" cx="26" cy="26" r="21" stroke="#fff" stroke-width="5" fill="none"
                            stroke-linecap="round" stroke-dasharray="131.95" stroke-dashoffset="131.95"/>
                </svg>
                <div class="ring-text"><?= $momentumScore['score'] ?>%</div>
            </div>
            <div>
                <div class="stat-val"><?= $momentumScore['score'] ?>%</div>
                <div class="stat-lbl">الزخم اليومي</div>
                <div style="font-size:.78rem;color:rgba(255,255,255,.75);margin-top:3px;"><?= $momentumScore['label'] ?></div>
            </div>
        </div>
        <!-- Total -->
        <div class="stat-card">
            <div class="stat-icon" style="background:#eff6ff;"><i class="fa-solid fa-list-check" style="color:#3b82f6;"></i></div>
            <div>
                <div class="stat-val"><span id="doneCount"><?= $completedTasks ?></span> <span style="font-size:1rem;color:#94a3b8;font-weight:500;">/ <?= $totalTasks ?></span></div>
                <div class="stat-lbl">الإنجاز الرقمي</div>
            </div>
        </div>
        <!-- Pending -->
        <div class="stat-card">
            <div class="stat-icon" style="background:#fff7ed;"><i class="fa-solid fa-hourglass-half" style="color:#f59e0b;"></i></div>
            <div>
                <div class="stat-val"><?= count($pendingTasks) ?></div>
                <div class="stat-lbl">متبقية</div>
            </div>
        </div>
        <!-- Categories -->
        <div class="stat-card">
            <div class="stat-icon" style="background:#f0fdf4;"><i class="fa-solid fa-tags" style="color:#22c55e;"></i></div>
            <div>
                <div class="stat-val"><?= count($catMap) ?></div>
                <div class="stat-lbl">التصنيفات</div>
            </div>
        </div>
    </div>

    <!-- QUICK ADD -->
    <div class="quick-add-box">
        <h6><i class="fa-solid fa-plus me-1"></i> أضف مهمة جديدة بسرعة</h6>
        <form action="<?= BASE_URL ?>/todo/storeTask" method="POST">
            <?= csrf_field() ?>
            <input type="hidden" name="target_date" value="<?= $targetDate ?>">
            <div class="quick-input-row">
                <input type="text" name="title" placeholder="اكتب المهمة هنا..." required>
                <button type="submit" class="btn-add-task"><i class="fa-solid fa-paper-plane me-1"></i> إضافة</button>
            </div>
            <div class="quick-meta">
                <select name="priority">
                    <option value="low">🍃 عادية</option>
                    <option value="medium" selected>⚡ متوسطة</option>
                    <option value="high">🔥 قصوى</option>
                </select>
                <select name="category">
                    <?php foreach($catMap as $sysKey => $data): ?>
                    <option value="<?= $sysKey ?>"><?= htmlspecialchars($data['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <label style="font-size:.85rem;font-weight:700;color:#64748b;cursor:pointer;display:flex;align-items:center;gap:5px;">
                    <input type="checkbox" name="add_to_calendar" value="1" style="accent-color:#3b82f6;"> ربط بالتقويم
                </label>
            </div>
        </form>
    </div>

    <!-- FOCUS ZONE -->
    <?php if(!empty($focusTasks)): ?>
    <div class="focus-zone" id="focusContainer" ondragover="allowDrop(event)" ondrop="dropToFocus(event)" ondragenter="dragEnterFocus(event)" ondragleave="dragLeaveFocus(event)">
        <h5><i class="fa-solid fa-crosshairs me-2"></i> منطقة التركيز اليومي
            <span class="badge bg-primary bg-opacity-10 text-primary ms-2" style="font-size:.75rem;"><?= count($focusTasks) ?></span>
        </h5>
        <div class="focus-tasks-grid">
            <?php foreach($focusTasks as $t):
                $isDone = ($t->status === 'done');
                $pUI = $priorityProps[$t->priority] ?? $priorityProps['medium'];
                $cUI = $catMap[$t->category] ?? $catFallback;
            ?>
            <div class="task-card <?= $isDone ? 'completed-card' : '' ?>" id="task-card-<?= $t->id ?>" data-id="<?= $t->id ?>" data-title="<?= htmlspecialchars($t->title, ENT_QUOTES) ?>" data-category="<?= htmlspecialchars($t->category ?? '', ENT_QUOTES) ?>" data-priority="<?= $t->priority ?>" data-estimated="<?= $t->estimated_time ?>" data-description="<?= htmlspecialchars($t->description ?? '', ENT_QUOTES) ?>" draggable="true" ondragstart="dragStartTask(event)" style="border-right: 3px solid #3b82f6;">
                <input type="checkbox" class="task-cb" onchange="updateTaskStatus(<?= $t->id ?>, this.checked, '<?= $targetDate ?>')" <?= $isDone ? 'checked' : '' ?>>
                <div class="task-body">
                    <div class="task-name <?= $isDone ? 'done-name' : '' ?>"><?= htmlspecialchars($t->title) ?></div>
                    <div class="task-badges">
                        <span class="tbadge tbadge-<?= $pUI['badge'] ?>"><i class="fa-solid <?= $pUI['icon'] ?>"></i> <?= $pUI['name'] ?></span>
                        <span class="tbadge tbadge-gray"><?= htmlspecialchars($cUI['name']) ?></span>
                        <?php if($t->estimated_time > 0): ?>
                        <span class="tbadge tbadge-gray"><i class="fa-regular fa-clock"></i> <?= $t->estimated_time ?> دق</span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="task-actions">
                    <button class="act-btn edit" title="تعديل" onclick="openEditModal(<?= $t->id ?>)"><i class="fa-solid fa-pen"></i></button>
                    <button class="act-btn star" title="إزالة من التركيز" onclick="toggleFocus(<?= $t->id ?>, 0)"><i class="fa-solid fa-star"></i></button>
                    <button class="act-btn del" title="حذف" onclick="deleteTask(<?= $t->id ?>)"><i class="fa-solid fa-trash-can"></i></button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="focus-zone mb-4" id="focusContainer" ondragover="allowDrop(event)" ondrop="dropToFocus(event)" ondragenter="dragEnterFocus(event)" ondragleave="dragLeaveFocus(event)" style="min-height:90px;">
        <h5><i class="fa-solid fa-crosshairs me-2"></i> منطقة التركيز اليومي</h5>
        <div class="focus-empty"><i class="fa-regular fa-star fs-4 d-block mb-1"></i> اسحب مهمة هنا لتكون في بؤرة تركيزك</div>
    </div>
    <?php endif; ?>

    <!-- CATEGORIES SECTION -->
    <div class="cats-section">
        <h5 class="cats-section-header"><i class="fa-solid fa-layer-group me-2 text-secondary"></i> المهام — مُنظَّمة بالتصنيف
            <span class="text-muted" style="font-size:.85rem;font-weight:500;"> (<?= count($pendingTasks) ?> متبقية)</span>
        </h5>

        <div class="cats-grid">

        <?php
        foreach($catMap as $catKey => $cUI):
            $tasks = $grouped[$catKey] ?? [];
            $isOpen = ''; // default closed
        ?>
        <div class="cat-card <?= $isOpen ?>" id="cat-card-<?= $catKey ?>">
            <div class="cat-card-header" style="border-right: 4px solid <?= $cUI['border'] ?>;" onclick="toggleCat('<?= $catKey ?>')">
                <div class="cat-card-title">
                    <span class="cat-dot" style="background:<?= $cUI['border'] ?>;"></span>
                    <span><?= htmlspecialchars($cUI['name']) ?></span>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <span class="cat-count" style="background:<?= $cUI['bg'] ?>;color:<?= $cUI['text'] ?>;"><?= count($tasks) ?></span>
                    <i class="fa-solid fa-chevron-down cat-chevron"></i>
                </div>
            </div>
            <div class="cat-collapse <?= $isOpen ?>" id="cat-collapse-<?= $catKey ?>">
                <div class="cat-collapse-inner">
                    <div class="cat-tasks-wrap" id="cat-tasks-<?= $catKey ?>">
                        <?php if(empty($tasks)): ?>
                            <div class="cat-empty"><i class="fa-regular fa-circle-check me-1"></i> لا مهام معلقة</div>
                        <?php else:
                            foreach($tasks as $t):
                                $pUI = $priorityProps[$t->priority] ?? $priorityProps['medium'];
                                $isOverdue = $t->is_overdue ?? false;
                        ?>
                        <div class="task-card" id="task-card-<?= $t->id ?>"
                             data-id="<?= $t->id ?>"
                             data-title="<?= htmlspecialchars($t->title, ENT_QUOTES) ?>"
                             data-category="<?= htmlspecialchars($t->category ?? '', ENT_QUOTES) ?>"
                             data-priority="<?= $t->priority ?>"
                             data-estimated="<?= $t->estimated_time ?>"
                             data-description="<?= htmlspecialchars($t->description ?? '', ENT_QUOTES) ?>"
                             draggable="true" ondragstart="dragStartTask(event)">
                            <input type="checkbox" class="task-cb" onchange="updateTaskStatus(<?= $t->id ?>, this.checked, '<?= $targetDate ?>')">
                            <div class="task-body">
                                <div class="task-name"><?= htmlspecialchars($t->title) ?>
                                    <?php if($isOverdue): ?>
                                        <span class="tbadge tbadge-over ms-1" style="font-size:.62rem;">متأخرة!</span>
                                    <?php endif; ?>
                                    <?php if($t->event_id): ?><i class="fa-regular fa-calendar-check text-primary ms-1" style="font-size:.75rem;" title="مرتبطة بالتقويم"></i><?php endif; ?>
                                </div>
                                <div class="task-badges">
                                    <span class="tbadge tbadge-<?= $pUI['badge'] ?>"><i class="fa-solid <?= $pUI['icon'] ?>"></i> <?= $pUI['name'] ?></span>
                                    <?php if($t->estimated_time > 0): ?>
                                    <span class="tbadge tbadge-gray"><i class="fa-regular fa-clock"></i> <?= $t->estimated_time ?> دق</span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="task-actions">
                                <button class="act-btn edit" title="تعديل" onclick="openEditModal(<?= $t->id ?>)"><i class="fa-solid fa-pen"></i></button>
                                <button class="act-btn star" title="تسليط الضوء" onclick="toggleFocus(<?= $t->id ?>, 1)"><i class="fa-regular fa-star"></i></button>
                                <button class="act-btn del" title="حذف" onclick="deleteTask(<?= $t->id ?>)"><i class="fa-solid fa-trash-can"></i></button>
                            </div>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <!-- Uncategorized -->
        <?php
        $uncatTasks = [];
        foreach($pendingTasks as $t) {
            if(!isset($catMap[$t->category ?? ''])) $uncatTasks[] = $t;
        }
        if(!empty($uncatTasks)):
        ?>
        <div class="cat-card" id="cat-card-uncat">
            <div class="cat-card-header" style="border-right: 4px solid #94a3b8;" onclick="toggleCat('uncat')">
                <div class="cat-card-title"><span class="cat-dot" style="background:#94a3b8;"></span> غير مصنفة</div>
                <div class="d-flex align-items-center gap-2">
                    <span class="cat-count" style="background:#f1f5f9;color:#64748b;"><?= count($uncatTasks) ?></span>
                    <i class="fa-solid fa-chevron-down cat-chevron"></i>
                </div>
            </div>
            <div class="cat-collapse" id="cat-collapse-uncat">
                <div class="cat-collapse-inner">
                    <div class="cat-tasks-wrap">
                        <?php foreach($uncatTasks as $t):
                            $pUI = $priorityProps[$t->priority] ?? $priorityProps['medium'];
                        ?>
                        <div class="task-card" id="task-card-<?= $t->id ?>" data-id="<?= $t->id ?>" data-title="<?= htmlspecialchars($t->title, ENT_QUOTES) ?>" data-category="<?= htmlspecialchars($t->category ?? '', ENT_QUOTES) ?>" data-priority="<?= $t->priority ?>" data-estimated="<?= $t->estimated_time ?>" data-description="<?= htmlspecialchars($t->description ?? '', ENT_QUOTES) ?>" draggable="true" ondragstart="dragStartTask(event)">
                            <input type="checkbox" class="task-cb" onchange="updateTaskStatus(<?= $t->id ?>, this.checked, '<?= $targetDate ?>')">
                            <div class="task-body">
                                <div class="task-name"><?= htmlspecialchars($t->title) ?></div>
                                <div class="task-badges">
                                    <span class="tbadge tbadge-<?= $pUI['badge'] ?>"><i class="fa-solid <?= $pUI['icon'] ?>"></i> <?= $pUI['name'] ?></span>
                                </div>
                            </div>
                            <div class="task-actions">
                                <button class="act-btn edit" title="تعديل" onclick="openEditModal(<?= $t->id ?>)"><i class="fa-solid fa-pen"></i></button>
                                <button class="act-btn star" title="تسليط الضوء" onclick="toggleFocus(<?= $t->id ?>, 1)"><i class="fa-regular fa-star"></i></button>
                                <button class="act-btn del" title="حذف" onclick="deleteTask(<?= $t->id ?>)"><i class="fa-solid fa-trash-can"></i></button>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if(!empty($completedTasks_list)): ?>
        <!-- DONE CARD — 6th in grid -->
        <div class="cat-card done-grid-card" id="cat-card-done">
            <div class="cat-card-header" onclick="toggleCat('done')">
                <div class="cat-card-title">
                    <i class="fa-solid fa-circle-check" style="color:#22c55e;font-size:1rem;"></i>
                    <span>المنجزة اليوم &#127942;</span>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <span class="cat-count" id="doneGridCount" style="background:#dcfce7;color:#16a34a;"><?= count($completedTasks_list) ?></span>
                    <i class="fa-solid fa-chevron-down cat-chevron"></i>
                </div>
            </div>
            <div class="cat-collapse" id="cat-collapse-done">
                <div class="cat-collapse-inner">
                    <div class="cat-tasks-wrap" id="done-tasks-list" style="gap:8px;">
                        <?php foreach($completedTasks_list as $t):
                            $cUI = $catMap[$t->category] ?? $catFallback;
                        ?>
                        <div class="done-item" id="task-card-<?= $t->id ?>">
                            <i class="fa-solid fa-circle-check done-item-check"></i>
                            <span class="done-item-name"><?= htmlspecialchars($t->title) ?></span>
                            <span class="done-item-cat"><?= htmlspecialchars($cUI['name']) ?></span>
                            <button class="act-btn del" title="حذف" onclick="deleteDoneTask(<?= $t->id ?>)" style="opacity:.45;flex-shrink:0;"><i class="fa-solid fa-trash-can"></i></button>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        </div><!-- /cats-grid -->
    </div>

</div>

<!-- ── OVERDUE MODAL ── -->
<div class="modal fade" id="overdueModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
      <div class="modal-header-custom d-flex align-items-center justify-content-between">
        <h5 class="m-0 fw-bold"><i class="fa-solid fa-triangle-exclamation me-2 text-warning"></i> معالجة المهام المتأخرة</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body-custom">
        <p class="text-muted fw-600 mb-4" style="font-size:.9rem;">هذه المهام عالقة في الأيام الماضية. أنجزها، أؤجلها، أو احذفها.</p>
        <div id="overdueList">
          <?php if(!empty($overdueTasks)): foreach($overdueTasks as $ot): ?>
          <div class="d-flex align-items-center gap-2 p-3 mb-2 bg-light rounded-3 border" id="overdue-item-<?= $ot->id ?>">
            <div class="flex-grow-1 min-w-0">
              <div class="text-danger fw-bold" style="font-size:.75rem;"><?= $ot->target_date ?></div>
              <div class="fw-bold text-dark" style="font-size:.9rem;"><?= htmlspecialchars($ot->title) ?></div>
            </div>
            <button class="btn btn-sm btn-success rounded-pill fw-bold px-3" onclick="rescheduleTask(<?= $ot->id ?>, '<?= $today ?>')">
              <i class="fa-solid fa-arrow-turn-down me-1"></i>اليوم
            </button>
            <input type="date" class="form-control form-control-sm" style="width:130px;border-radius:50px;" onchange="rescheduleTask(<?= $ot->id ?>, this.value)">
            <button class="btn btn-sm btn-outline-danger rounded-circle" onclick="deleteOverdue(<?= $ot->id ?>)"><i class="fa-solid fa-trash-can"></i></button>
          </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- ── EDIT TASK MODAL ── -->
<div class="modal fade" id="editTaskModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
      <div class="modal-header-custom d-flex align-items-center justify-content-between">
        <h5 class="m-0 fw-bold"><i class="fa-solid fa-pen me-2"></i> تعديل المهمة</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body-custom">
        <input type="hidden" id="editTaskId">
        <div class="mb-3">
          <label class="form-label-custom">اسم المهمة *</label>
          <input type="text" id="editTitle" class="form-ctrl-custom" placeholder="اسم المهمة...">
        </div>
        <div class="mb-3">
          <label class="form-label-custom">الوصف (اختياري)</label>
          <textarea id="editDescription" class="form-ctrl-custom" rows="2" placeholder="وصف المهمة..."></textarea>
        </div>
        <div class="row g-3 mb-3">
          <div class="col-6">
            <label class="form-label-custom">الأولوية</label>
            <select id="editPriority" class="form-ctrl-custom">
              <option value="high">🔥 قصوى</option>
              <option value="medium" selected>⚡ متوسطة</option>
              <option value="low">🍃 عادية</option>
            </select>
          </div>
          <div class="col-6">
            <label class="form-label-custom">الوقت المقدر (دقيقة)</label>
            <input type="number" id="editEstimated" class="form-ctrl-custom" min="0" placeholder="0">
          </div>
        </div>
        <div class="mb-4">
          <label class="form-label-custom">التصنيف</label>
          <select id="editCategory" class="form-ctrl-custom">
            <?php foreach($catMap as $sysKey => $data): ?>
            <option value="<?= $sysKey ?>"><?= htmlspecialchars($data['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <button class="btn-add-task w-100" style="border-radius:10px;" onclick="saveTaskEdit()">
          <i class="fa-solid fa-check me-1"></i> حفظ التعديلات
        </button>
      </div>
    </div>
  </div>
</div>

<!-- ── CATEGORIES MODAL ── -->
<div class="modal fade" id="catModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
      <div class="modal-header-custom d-flex align-items-center justify-content-between">
        <h5 class="m-0 fw-bold"><i class="fa-solid fa-tags me-2"></i> إدارة التصنيفات</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body-custom">
        <p class="text-muted mb-4" style="font-size:.85rem;">يمكنك تغيير اسم أي تصنيف وسيُحدَّث في كل مكان.</p>
        <?php foreach($customCategories as $c): ?>
        <div class="cat-edit-row" data-cat-id="<?= $c->id ?>">
          <span class="cat-color-dot" style="background:<?= $c->border_color ?>;"></span>
          <input type="text" class="cat-name-input" value="<?= htmlspecialchars($c->name) ?>" data-original="<?= htmlspecialchars($c->name) ?>">
          <button class="cat-save-btn" onclick="saveCategory(this, <?= $c->id ?>)"><i class="fa-solid fa-check"></i> حفظ</button>
          <span class="cat-saved-badge"><i class="fa-solid fa-circle-check"></i> تم</span>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>
</div>

<script>
const THE_CSRF_TOKEN = '<?= $_SESSION['csrf_token'] ?? '' ?>';
const BASE = '<?= BASE_URL ?>';

// ── Momentum Ring ──
(function(){
    const ring = document.getElementById('momentumRing');
    if (!ring) return;
    const score = <?= $momentumScore['score'] ?>;
    const circ = 2 * Math.PI * 21; // 131.95
    setTimeout(() => {
        ring.style.transition = 'stroke-dashoffset .7s ease';
        ring.style.strokeDashoffset = circ - (score / 100 * circ);
    }, 300);
})();

// ── Toggle Done Section ──
function toggleDoneSection(el) {
    const list = document.getElementById('doneList');
    const chevron = document.getElementById('doneChevron');
    list.classList.toggle('open');
    if (chevron) chevron.style.transform = list.classList.contains('open') ? 'rotate(180deg)' : '';
}

// ── Toggle Category Accordion ──
function toggleCat(catKey) {
    const card     = document.getElementById('cat-card-'     + catKey);
    const collapse = document.getElementById('cat-collapse-' + catKey);
    if (!card || !collapse) return;
    const isOpen = card.classList.contains('open');
    card.classList.toggle('open', !isOpen);
    collapse.classList.toggle('open', !isOpen);
}

// ── Toast ──
function appToast(title, msg, type) {
    if (typeof OTIS !== 'undefined' && OTIS.toast) OTIS.toast(title, msg, type);
    else alert(title + ' — ' + msg);
}

// ── Update Task Status (check/uncheck) ──
function updateTaskStatus(taskId, isChecked, targetDate) {
    const card = document.getElementById('task-card-' + taskId);
    const newStatus = isChecked ? 'done' : 'pending';

    fetch(BASE + '/todo/updateStatus', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({task_id: taskId, status: newStatus, target_date: targetDate, csrf_token: THE_CSRF_TOKEN})
    }).then(r => r.json()).then(data => {
        if (data.success) {
            // Animate out then reload to move card to correct section
            if (card) {
                card.style.transition = 'all .35s ease';
                card.style.opacity = '0';
                card.style.transform = 'scale(.9)';
            }
            setTimeout(() => window.location.reload(), 380);
        } else {
            appToast('خطأ', 'فشل التحديث', 'danger');
        }
    });
}

// ── Toggle Focus ──
function toggleFocus(taskId, isFocus) {
    const card = document.getElementById('task-card-' + taskId);
    if (card) { card.style.opacity = '.4'; }
    fetch(BASE + '/todo/toggleFocus', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({task_id: taskId, is_focus: isFocus, csrf_token: THE_CSRF_TOKEN})
    }).then(r => r.json()).then(data => {
        if (data.success) setTimeout(() => window.location.reload(), 250);
    });
}

// ── Delete Task ──
function deleteTask(taskId) {
    if (!confirm('حذف هذه المهمة نهائياً؟')) return;
    fetch(BASE + '/todo/delete', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({task_id: taskId, csrf_token: THE_CSRF_TOKEN})
    }).then(r => r.json()).then(data => {
        if (data.success) {
            const card = document.getElementById('task-card-' + taskId);
            if (!card) return;

            // Find the parent cat-card to update count
            const tasksWrap = card.closest('.cat-tasks-wrap');
            const catCard   = card.closest('.cat-card');

            card.style.transition = 'all .28s ease';
            card.style.opacity    = '0';
            card.style.transform  = 'translateX(20px)';

            setTimeout(() => {
                card.remove();

                // Update count badge
                if (catCard) {
                    const badge     = catCard.querySelector('.cat-count');
                    const remaining = tasksWrap ? tasksWrap.querySelectorAll('.task-card').length : 0;
                    if (badge) badge.textContent = remaining;

                    // If empty, show placeholder
                    if (tasksWrap && remaining === 0) {
                        tasksWrap.innerHTML = '<div class="cat-empty"><i class="fa-regular fa-circle-check me-1"></i> لا مهام معلقة</div>';
                    }
                }

                // Update global "pending" count in section header
                const pHeader = document.querySelector('.cats-section-header span');
                if (pHeader) {
                    const allPending = document.querySelectorAll('.cats-grid .task-card').length;
                    pHeader.textContent = '(' + allPending + ' متبقية)';
                }

                // Update stat widget (المتبقية)
                const statPending = document.querySelector('.stat-card:nth-child(3) .stat-val');
                if (statPending) {
                    const cur = parseInt(statPending.textContent) || 0;
                    if (cur > 0) statPending.textContent = cur - 1;
                }
            }, 300);
        }
    });
}

// ── Delete Done Task (from the green card) ──
function deleteDoneTask(taskId) {
    if (!confirm('حذف هذه المهمة نهائياً؟')) return;
    fetch(BASE + '/todo/delete', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({task_id: taskId, csrf_token: THE_CSRF_TOKEN})
    }).then(r => r.json()).then(data => {
        if (data.success) {
            const item = document.getElementById('task-card-' + taskId);
            if (!item) return;
            item.style.transition = 'all .25s ease';
            item.style.opacity    = '0';
            item.style.transform  = 'translateX(20px)';
            setTimeout(() => {
                item.remove();
                // Update done count badge
                const badge = document.getElementById('doneGridCount');
                if (badge) {
                    const remaining = document.querySelectorAll('#done-tasks-list .done-item').length;
                    badge.textContent = remaining;
                    if (remaining === 0) {
                        document.getElementById('done-tasks-list').innerHTML =
                            '<div class="cat-empty"><i class="fa-regular fa-circle-check me-1"></i> لا مهام منجزة بعد</div>';
                    }
                }
            }, 270);
        }
    });
}

// ── Drag & Drop ──
function dragStartTask(ev) {
    const card = ev.target.closest('.task-card');
    if (!card) return;
    ev.dataTransfer.setData('text/plain', card.getAttribute('data-id'));
    setTimeout(() => { card.style.opacity = '.35'; }, 10);
}
function allowDrop(ev) { ev.preventDefault(); }
function dragEnterFocus(ev) { ev.preventDefault(); document.getElementById('focusContainer')?.classList.add('shadow-lg'); }
function dragLeaveFocus(ev) { document.getElementById('focusContainer')?.classList.remove('shadow-lg'); }
function dropToFocus(ev) {
    ev.preventDefault();
    document.getElementById('focusContainer')?.classList.remove('shadow-lg');
    const taskId = ev.dataTransfer.getData('text/plain');
    if (taskId) toggleFocus(taskId, 1);
}
function dropToRegular(ev) {
    ev.preventDefault();
    const taskId = ev.dataTransfer.getData('text/plain');
    if (taskId) toggleFocus(taskId, 0);
}

// ── Edit Task Modal ──
function openEditModal(taskId) {
    const card = document.getElementById('task-card-' + taskId);
    if (!card) return;
    document.getElementById('editTaskId').value       = taskId;
    document.getElementById('editTitle').value        = card.dataset.title       || '';
    document.getElementById('editDescription').value  = card.dataset.description || '';
    document.getElementById('editPriority').value     = card.dataset.priority    || 'medium';
    document.getElementById('editEstimated').value    = card.dataset.estimated   || '';
    document.getElementById('editCategory').value     = card.dataset.category    || '';
    const modal = new bootstrap.Modal(document.getElementById('editTaskModal'));
    modal.show();
}

function saveTaskEdit() {
    const taskId = document.getElementById('editTaskId').value;
    const title  = document.getElementById('editTitle').value.trim();
    if (!title) { alert('يجب كتابة اسم المهمة!'); return; }

    const payload = {
        csrf_token:     THE_CSRF_TOKEN,
        task_id:        taskId,
        title:          title,
        description:    document.getElementById('editDescription').value,
        priority:       document.getElementById('editPriority').value,
        estimated_time: document.getElementById('editEstimated').value,
        category:       document.getElementById('editCategory').value,
    };

    fetch(BASE + '/todo/updateTask', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify(payload)
    }).then(r => r.json()).then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('editTaskModal'))?.hide();
            appToast('تم ✓', 'تُحدِّثت المهمة بنجاح', 'success');
            setTimeout(() => window.location.reload(), 600);
        } else {
            appToast('خطأ', data.message || 'فشل الحفظ', 'danger');
        }
    });
}

// ── Save Category ──
function saveCategory(btn, catId) {
    const row   = btn.closest('.cat-edit-row');
    const input = row.querySelector('.cat-name-input');
    const badge = row.querySelector('.cat-saved-badge');
    const name  = input.value.trim();
    if (!name) return;

    btn.disabled = true;
    fetch(BASE + '/todo/updateCategory', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({csrf_token: THE_CSRF_TOKEN, cat_id: catId, name: name})
    }).then(r => r.json()).then(data => {
        btn.disabled = false;
        if (data.success) {
            badge.style.display = 'inline-flex';
            input.dataset.original = name;
            setTimeout(() => { badge.style.display = 'none'; }, 2000);
        } else {
            appToast('خطأ', data.message || 'فشل الحفظ', 'danger');
        }
    });
}

// ── Overdue Handlers ──
function rescheduleTask(taskId, newDate) {
    if (!newDate) return;
    fetch(BASE + '/todo/reschedule', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({task_id: taskId, new_date: newDate, csrf_token: THE_CSRF_TOKEN})
    }).then(r => r.json()).then(data => {
        if (data.success) {
            document.getElementById('overdue-item-' + taskId)?.remove();
            appToast('✓', 'تم إعادة الجدولة', 'success');
            setTimeout(() => window.location.reload(), 1200);
        }
    });
}
function deleteOverdue(taskId) {
    if (!confirm('إسقاط هذه المهمة نهائياً؟')) return;
    fetch(BASE + '/todo/delete', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({task_id: taskId, csrf_token: THE_CSRF_TOKEN})
    }).then(r => r.json()).then(data => {
        if (data.success) document.getElementById('overdue-item-' + taskId)?.remove();
    });
}
</script>
