<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$DEBUG = (isset($_GET['debug']) && $_GET['debug'] === '1');
if ($DEBUG) {
    ini_set('display_errors', '1');
    ini_set('display_startup_errors', '1');
    error_reporting(E_ALL);
}

if (empty($_SESSION['user_id'])) {
    header("Location: index.html?e=1");
    exit;
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/inc/layout.php';

$pdo = null;
if (function_exists('db')) {
    $pdo = db();
} elseif (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
    $pdo = $GLOBALS['pdo'];
}

if (!$pdo instanceof PDO) {
    http_response_code(500);
    die('DB not ready');
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$branchId = (int)($_SESSION['branch_id'] ?? 1);
$userName = (string)($_SESSION['name'] ?? $_SESSION['username'] ?? 'مستخدم');
$role     = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

/* تعريب حالات المهام */
$TASK_STATUS = [
    'OPEN'   => 'مفتوحة',
    'DONE'   => 'قيد التنفيذ',
    'CLOSED' => 'مغلقة',
    'NEW'    => 'مفتوحة',
];

function task_status_label(string $code, array $map): string
{
    $code = strtoupper(trim($code));
    return $map[$code] ?? $code;
}

/* تعريب الأولويات */
$TASK_PRIORITY = [
    'HIGH'   => 'عالية',
    'MEDIUM' => 'متوسطة',
    'LOW'    => 'منخفضة',
];

function task_priority_label(string $code, array $map): string
{
    $code = strtoupper(trim($code));
    return $map[$code] ?? $code;
}

$msg = trim((string)($_GET['msg'] ?? ''));
$err = trim((string)($_GET['err'] ?? ''));

/* اسم الفرع */
try {
    $st = $pdo->prepare("SELECT name_ar FROM branches WHERE id = ? LIMIT 1");
    $st->execute([$branchId]);
    $currentBranchName = (string)($st->fetchColumn() ?: 'أبوظبي');
} catch (Throwable $e) {
    $currentBranchName = match ($branchId) {
        2 => 'دبي',
        3 => 'الشارقة',
        default => 'أبوظبي',
    };
}

/* جلب المهام للفرع */
$tasks = [];
try {
    $st = $pdo->prepare("
        SELECT DISTINCT
            t.id,
            t.title,
            t.status,
            t.priority,
            t.due_date,
            t.created_at,
            t.created_by,
            COALESCE(u.name, u.username, '') AS added_by
        FROM tasks t
        LEFT JOIN users u ON u.id = t.created_by
        WHERE t.branch_id = ?
       ORDER BY t.created_at DESC, t.id DESC
        LIMIT 200
    ");
    $st->execute([$branchId]);
    $tasks = $st->fetchAll();
} catch (Throwable $e) {
    $st = $pdo->prepare("
        SELECT DISTINCT
            id,
            title,
            status,
            priority,
            due_date,
            created_at,
            created_by
        FROM tasks
        WHERE branch_id = ?
        ORDER BY (status='OPEN') DESC,
                 (due_date IS NULL) ASC,
                 due_date ASC,
                 id DESC
        LIMIT 200
    ");
    $st->execute([$branchId]);
    $tasks = $st->fetchAll();
}

$seen = [];

render_layout_start('المهام');
?>

<style>
  :root{
    --bg-main:#07171d;
    --bg-card:rgba(255,255,255,.05);
    --bg-card-2:rgba(255,255,255,.04);
    --line:rgba(255,255,255,.08);
    --line-soft:rgba(255,255,255,.05);
    --text:#ffffff;
    --muted:rgba(255,255,255,.68);
    --gold:#d4af37;
    --gold-2:#ffd76a;
    --gold-soft:rgba(212,175,55,.14);
    --danger:#f87171;
    --danger-soft:rgba(248,113,113,.12);
    --success:#34d399;
    --success-soft:rgba(52,211,153,.12);
    --blue:#60a5fa;
    --blue-soft:rgba(96,165,250,.12);
    --warning:#fbbf24;
    --warning-soft:rgba(251,191,36,.12);
    --shadow:0 18px 40px rgba(0,0,0,.16);
  }

  body{
    background:
      radial-gradient(circle at 20% 20%, rgba(10,77,87,.85), transparent 40%),
      radial-gradient(circle at 80% 80%, rgba(13,106,122,.55), transparent 40%),
      #021d23;
  }

  .tasks-page{
    color:var(--text);
    width:100%;
    max-width:100%;
  }

  .tasks-page *{
    box-sizing:border-box;
  }

  .tasks-page .topbar-local{
    min-height:68px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    padding:10px 12px;
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    position:sticky;
    top:12px;
    z-index:10;
    margin-bottom:18px;
    backdrop-filter:blur(12px);
  }

  .tasks-page .branch-switch{
    position:relative;
    display:inline-flex;
    align-items:center;
  }

  .tasks-page .branch-btn{
    display:flex;
    align-items:center;
    gap:8px;
    background:rgba(255,255,255,.05);
    border:1px solid var(--line);
    border-radius:999px;
    padding:10px 14px;
    cursor:pointer;
    font-family:inherit;
    box-shadow:0 8px 18px rgba(0,0,0,.10);
    color:#fff;
    backdrop-filter:blur(8px);
  }

  .tasks-page .branch-dot{
    width:8px;
    height:8px;
    border-radius:50%;
    background:var(--gold);
    box-shadow:0 0 0 4px rgba(212,175,55,.14);
  }

  .tasks-page .branch-name{
    font-weight:800;
    color:#fff;
  }

  .tasks-page .branch-caret{
    opacity:.7;
    font-size:14px;
    color:#fff;
  }

  .tasks-page .branch-menu{
    position:absolute;
    top:calc(100% + 8px);
    right:0;
    min-width:170px;
    background:#0b1f26;
    border:1px solid var(--line);
    border-radius:14px;
    box-shadow:0 18px 40px rgba(0,0,0,.22);
    padding:8px;
    display:none;
    z-index:999;
  }

  .tasks-page .branch-choice{
    width:100%;
    text-align:right;
    background:transparent;
    border:0;
    padding:10px;
    border-radius:10px;
    cursor:pointer;
    font-family:inherit;
    font-weight:800;
    color:#fff;
  }

  .tasks-page .branch-choice:hover{
    background:rgba(255,255,255,.06);
  }

  .tasks-page .page-head{
    margin:18px 6px 14px;
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
  }

  .tasks-page .pageTitle{
    font-size:30px;
    font-weight:900;
    color:#ffffff;
    margin:0;
  }

  .tasks-page .pageSub{
    color:rgba(255,255,255,.72);
    font-size:14px;
    margin-top:6px;
  }

  .tasks-page .card{
    background:var(--bg-card);
    border:1px solid var(--line);
    border-radius:18px;
    box-shadow:var(--shadow);
    overflow:hidden;
    backdrop-filter:blur(12px);
  }

  .tasks-page .cardHead{
    padding:14px 16px;
    border-bottom:1px solid var(--line);
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
  }

  .tasks-page .btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    height:42px;
    padding:0 14px;
    border-radius:999px;
    border:1px solid rgba(212,175,55,.25);
    background:linear-gradient(135deg,#ffd76a,#d4af37);
    font-weight:900;
    color:#1d1600;
    cursor:pointer;
    text-decoration:none;
    box-shadow:0 12px 24px rgba(212,175,55,.18);
    transition:.18s ease;
  }

  .tasks-page .btn:hover{
    transform:translateY(-2px);
    box-shadow:0 16px 28px rgba(212,175,55,.24);
  }

  .tasks-page .msg{
    margin:12px 6px 0;
    padding:10px 12px;
    border-radius:14px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
  }

  .tasks-page .ok{
    color:#86efac;
  }

  .tasks-page .bad{
    color:#fca5a5;
  }

  .tasks-page .muted{
    color:var(--muted);
    font-size:13px;
  }

  .tasks-page .nowrap{
    white-space:nowrap;
  }

  .tasks-page table{
    width:100%;
    border-collapse:collapse;
  }

  .tasks-page th,
  .tasks-page td{
    padding:12px 14px;
    border-bottom:1px solid var(--line);
    text-align:right;
    font-size:14px;
    vertical-align:middle;
  }

  .tasks-page th{
    background:rgba(255,255,255,.04);
    color:rgba(255,255,255,.72);
  }

  .tasks-page td{
    color:#fff;
  }

  .tasks-page tbody tr{
    transition:.18s ease;
  }

  .tasks-page tbody tr:hover td{
    background:rgba(255,255,255,.03);
  }

  .tasks-page .badge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:6px 10px;
    border-radius:999px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    font-weight:800;
    font-size:12px;
  }

  .tasks-page .open{
    color:var(--success);
  }

  .tasks-page .mid{
    color:var(--blue);
  }

  .tasks-page .closed{
    color:var(--warning);
  }

  .tasks-page .pbadge{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:6px 10px;
    border-radius:999px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    font-weight:900;
    font-size:12px;
  }

  .tasks-page .pbadge.high{
    color:var(--danger);
    background:var(--danger-soft);
    border-color:rgba(248,113,113,.20);
  }

  .tasks-page .pbadge.medium{
    color:var(--warning);
    background:var(--warning-soft);
    border-color:rgba(251,191,36,.20);
  }

  .tasks-page .pbadge.low{
    color:var(--success);
    background:var(--success-soft);
    border-color:rgba(52,211,153,.20);
  }

  .tasks-page tr.p-high td{
    background:rgba(127,29,29,.08);
  }

  .tasks-page tr.p-medium td{
    background:rgba(120,53,15,.08);
  }

  .tasks-page tr.p-low td{
    background:rgba(6,78,59,.08);
  }

  .tasks-page tr.p-high td,
  .tasks-page tr.p-medium td,
  .tasks-page tr.p-low td{
    border-bottom-color:var(--line);
  }

  .tasks-page tr.p-high td:first-child{
    box-shadow:inset -6px 0 0 #ef4444;
  }

  .tasks-page tr.p-medium td:first-child{
    box-shadow:inset -6px 0 0 #f59e0b;
  }

  .tasks-page tr.p-low td:first-child{
    box-shadow:inset -6px 0 0 #10b981;
  }

  .tasks-page .actions{
    display:flex;
    gap:8px;
    justify-content:flex-start;
    flex-wrap:wrap;
  }

  .tasks-page .iconBtn{
    width:40px;
    height:40px;
    border-radius:12px;
    border:1px solid var(--line);
    background:rgba(255,255,255,.05);
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    color:#fff;
    transition:.18s ease;
  }

  .tasks-page .iconBtn:hover{
    background:rgba(255,255,255,.08);
    transform:translateY(-1px);
  }

  .tasks-page .icon{
    width:18px;
    height:18px;
  }

  .tasks-page .danger{
    border-color:rgba(248,113,113,.22);
    background:rgba(248,113,113,.08);
  }

  .tasks-page .danger:hover{
    background:rgba(248,113,113,.14);
  }

  .tasks-page .footerNote{
    margin-top:18px;
    padding:14px 18px;
    border-radius:16px;
    background:rgba(255,255,255,.04);
    border:1px solid rgba(255,255,255,.08);
    backdrop-filter:blur(8px);
    color:rgba(255,255,255,.75);
    font-size:13px;
  }

  .tasks-page .footer-inner{
    display:flex;
    justify-content:space-between;
    align-items:center;
    flex-wrap:wrap;
    gap:10px;
  }

  .tasks-page .footer-copy{
    color:#ffd76a !important;
    font-weight:700;
    letter-spacing:.3px;
  }

  .tasks-page .footer-system{
    font-weight:800;
    color:#d4af37;
    letter-spacing:.5px;
  }

  @media (max-width:980px){
    .tasks-page .card{
      overflow:auto;
    }
  }

  @media (max-width:700px){
    .tasks-page .footer-inner{
      flex-direction:column;
      text-align:center;
    }

    .tasks-page .pageTitle{
      font-size:24px;
    }
  }
  /* =========================
   TASK STATUS - LEGEND UI
========================= */

.tasks-page .badge{
  position:relative;
  display:inline-flex;
  align-items:center;
  justify-content:center;

  min-width:100px;
  height:34px;
  padding:0 14px;

  border-radius:999px;
  font-size:12px;
  font-weight:900;
  letter-spacing:.3px;

  border:1px solid transparent;
  overflow:hidden;

  backdrop-filter:blur(10px);
  -webkit-backdrop-filter:blur(10px);

  box-shadow:
    0 10px 22px rgba(0,0,0,.22),
    inset 0 1px 0 rgba(255,255,255,.2);

  transition:.25s ease;
}

/* لمعة متحركة */
.tasks-page .badge::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;
  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.55),
    transparent
  );
  transform:skewX(-20deg);
  animation:taskBadgeShine 4s infinite;
}

@keyframes taskBadgeShine{
  0%{ left:-70%; opacity:0 }
  40%{ opacity:.8 }
  100%{ left:130%; opacity:0 }
}

/* ================= الحالات ================= */

/* مفتوحة */
.tasks-page .badge.open{
  background:linear-gradient(135deg,#059669,#34d399);
  color:#ecfdf5;
  border-color:rgba(52,211,153,.45);

  box-shadow:
    0 12px 28px rgba(52,211,153,.35),
    0 0 18px rgba(52,211,153,.25);
}

/* قيد التنفيذ */
.tasks-page .badge.mid{
  background:linear-gradient(135deg,#3b82f6,#60a5fa);
  color:#ecf3ff;
  border-color:rgba(96,165,250,.45);

  box-shadow:
    0 12px 28px rgba(96,165,250,.35),
    0 0 18px rgba(96,165,250,.25);
}

/* مغلقة */
.tasks-page .badge.closed{
  background:linear-gradient(135deg,#d97706,#fbbf24);
  color:#1a1400;
  border-color:rgba(251,191,36,.45);

  box-shadow:
    0 12px 28px rgba(251,191,36,.35),
    0 0 18px rgba(251,191,36,.25);
}

/* hover */
.tasks-page .badge:hover{
  transform:translateY(-2px) scale(1.05);
}
/* =========================
   TASK PRIORITY - LEGEND UI
========================= */

.tasks-page .pbadge{
  position:relative;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  min-width:96px;
  height:34px;
  padding:0 14px;
  border-radius:999px;
  overflow:hidden;
  font-size:12px;
  font-weight:900;
  letter-spacing:.3px;
  border:1px solid transparent;
  box-shadow:
    0 10px 22px rgba(0,0,0,.22),
    inset 0 1px 0 rgba(255,255,255,.22);
  transition:.25s ease;
}

.tasks-page .pbadge::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;
  background:linear-gradient(120deg,transparent,rgba(255,255,255,.55),transparent);
  transform:skewX(-20deg);
  animation:priorityShine 4s infinite;
}

@keyframes priorityShine{
  0%{left:-70%;opacity:0;}
  40%{opacity:.8;}
  100%{left:130%;opacity:0;}
}

/* عالية */
.tasks-page .pbadge.high{
  background:linear-gradient(135deg,#dc2626,#f87171);
  color:#fff5f5;
  border-color:rgba(248,113,113,.48);
  box-shadow:
    0 12px 28px rgba(248,113,113,.34),
    0 0 20px rgba(248,113,113,.25);
}

/* متوسطة */
.tasks-page .pbadge.medium{
  background:linear-gradient(135deg,#d97706,#fbbf24);
  color:#1a1400;
  border-color:rgba(251,191,36,.48);
  box-shadow:
    0 12px 28px rgba(251,191,36,.34),
    0 0 20px rgba(251,191,36,.25);
}

/* منخفضة */
.tasks-page .pbadge.low{
  background:linear-gradient(135deg,#059669,#34d399);
  color:#ecfdf5;
  border-color:rgba(52,211,153,.48);
  box-shadow:
    0 12px 28px rgba(52,211,153,.34),
    0 0 20px rgba(52,211,153,.25);
}

.tasks-page .pbadge:hover{
  transform:translateY(-2px) scale(1.05);
}
/* =========================
   LEGEND ADD BUTTON
========================= */

.tasks-page .btn{
  position:relative;
  display:inline-flex;
  align-items:center;
  justify-content:center;
  gap:8px;

  height:46px;
  padding:0 20px;

  border-radius:999px;
  border:1px solid rgba(212,175,55,.5);

  background:linear-gradient(135deg,#ffd76a,#d4af37);
  color:#1a1400;

  font-size:14px;
  font-weight:900;
  letter-spacing:.3px;
  text-decoration:none;

  overflow:hidden;

  box-shadow:
    0 15px 30px rgba(212,175,55,.35),
    0 0 25px rgba(212,175,55,.25),
    inset 0 2px 6px rgba(255,255,255,.35);

  transition:all .25s ease;
}

/* لمعة متحركة */
.tasks-page .btn::after{
  content:"";
  position:absolute;
  top:0;
  left:-70%;
  width:50%;
  height:100%;

  background:linear-gradient(
    120deg,
    transparent,
    rgba(255,255,255,.6),
    transparent
  );

  transform:skewX(-20deg);
  animation:btnShine 3.5s infinite;
}

@keyframes btnShine{
  0%{ left:-70%; opacity:0 }
  40%{ opacity:.9 }
  100%{ left:130%; opacity:0 }
}

/* hover */
.tasks-page .btn:hover{
  transform:translateY(-3px) scale(1.04);

  box-shadow:
    0 20px 40px rgba(212,175,55,.45),
    0 0 35px rgba(212,175,55,.35),
    inset 0 2px 6px rgba(255,255,255,.4);
}

/* ضغط */
.tasks-page .btn:active{
  transform:scale(.95);
}
</style>
<div class="tasks-page">
  <div class="topbar-local">
    
    <div class="top-left">
      <!-- فارغ حتى يبقى الشريط بنفس التصميم -->
    </div>    <a class="btn" href="<?= h(u('task_add.php')) ?>">إضافة مهمة</a>
  </div>

  <?php if ($msg !== ''): ?>
    <div class="msg ok"><?= h($msg) ?></div>
  <?php endif; ?>

  <?php if ($err !== ''): ?>
    <div class="msg bad"><?= h($err) ?></div>
  <?php endif; ?>

  <div class="page-head">
    <div>
      <h1 class="pageTitle">المهام</h1>
      <div class="pageSub">عرض مهام الفرع الحالي فقط</div>
    </div>
    <div class="muted">عدد المهام: <?= (int)count($tasks) ?></div>
  </div>

  <div class="card">
    <div class="cardHead">
      <div>قائمة المهام</div>
      <?php if ($DEBUG): ?>
        <div class="muted">وضع التشخيص مفعل</div>
      <?php endif; ?>
    </div>

    <div style="overflow:auto">
      <table>
        <thead>
          <tr>
            <th style="width:90px">#</th>
            <th>العنوان</th>
            <th style="width:140px">الحالة</th>
            <th style="width:140px">الأولوية</th>
            <th style="width:170px">أضيفت بواسطة</th>
            <th style="width:160px">تاريخ الاستحقاق</th>
            <th style="width:170px">تاريخ الإنشاء</th>
            <th style="width:140px">إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$tasks): ?>
            <tr>
              <td colspan="8" class="muted">لا توجد مهام لهذا الفرع.</td>
            </tr>
          <?php else: ?>
            <?php foreach ($tasks as $t): ?>
              <?php
                $id = (int)($t['id'] ?? 0);
                if ($id <= 0) continue;
                if (isset($seen[$id])) continue;
                $seen[$id] = true;

                $statusCode = strtoupper((string)($t['status'] ?? 'OPEN'));
                $statusText = task_status_label($statusCode, $TASK_STATUS);

                $badgeClass = 'mid';
                if (in_array($statusCode, ['OPEN', 'NEW'], true)) {
                    $badgeClass = 'open';
                } elseif ($statusCode === 'CLOSED') {
                    $badgeClass = 'closed';
                }

                $priorityCode = strtoupper((string)($t['priority'] ?? 'MEDIUM'));
                $priorityText = task_priority_label($priorityCode, $TASK_PRIORITY);

                $rowClass = 'p-medium';
                $pBadgeClass = 'medium';
                if ($priorityCode === 'HIGH') {
                    $rowClass = 'p-high';
                    $pBadgeClass = 'high';
                } elseif ($priorityCode === 'LOW') {
                    $rowClass = 'p-low';
                    $pBadgeClass = 'low';
                }

                $addedBy = (string)($t['added_by'] ?? '');
                if ($addedBy === '') $addedBy = '—';
              ?>
              <tr class="<?= h($rowClass) ?>">
                <td class="nowrap"><?= $id ?></td>
                <td><?= h((string)($t['title'] ?? '')) ?></td>

                <td class="nowrap">
                  <span class="badge <?= h($badgeClass) ?>"><?= h($statusText) ?></span>
                </td>

                <td class="nowrap">
                  <span class="pbadge <?= h($pBadgeClass) ?>"><?= h($priorityText) ?></span>
                </td>

                <td class="nowrap"><?= h($addedBy) ?></td>
                <td class="nowrap"><?= h((string)($t['due_date'] ?? '')) ?></td>
                <td class="nowrap"><?= h((string)($t['created_at'] ?? '')) ?></td>

                <td>
                  <div class="actions">
                    <a class="iconBtn" href="<?= h(u('task_edit.php?id=' . $id)) ?>" title="تعديل">
                      <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <path d="M12 20h9"></path>
                        <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"></path>
                      </svg>
                    </a>

                    <form method="post" action="<?= h(u('task_delete.php')) ?>" onsubmit="return confirm('حذف المهمة؟');" style="display:inline">
                      <input type="hidden" name="id" value="<?= $id ?>">
                      <button class="iconBtn danger" type="submit" title="حذف">
                        <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                          <polyline points="3 6 5 6 21 6"></polyline>
                          <path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path>
                          <path d="M10 11v6"></path>
                          <path d="M14 11v6"></path>
                          <path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"></path>
                        </svg>
                      </button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
(function(){
  const branchBtn  = document.getElementById('branchBtn');
  const branchMenu = document.getElementById('branchMenu');

  function closeMenu(){
    if (!branchMenu) return;
    branchMenu.style.display = 'none';
    if (branchBtn) branchBtn.setAttribute('aria-expanded','false');
  }

  function toggleMenu(){
    if (!branchMenu || !branchBtn) return;
    const isOpen = branchMenu.style.display === 'block';
    branchMenu.style.display = isOpen ? 'none' : 'block';
    branchBtn.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
  }

  if (branchBtn && branchMenu){
    branchBtn.addEventListener('click', function(e){
      e.stopPropagation();
      toggleMenu();
    });

    document.addEventListener('click', closeMenu);
    document.addEventListener('keydown', function(e){
      if (e.key === 'Escape') closeMenu();
    });
  }
})();
</script>

<?php render_layout_end(); ?>