<?php
require_once __DIR__ . '/footer.php';

if (!defined('PYRK_FOOTER_AUTO_INJECT')) {
    define('PYRK_FOOTER_AUTO_INJECT', true);

    /**
     * Safe footer injection. It must never white-screen the website.
     */
    ob_start(function ($html) {
        try {
            $section = $GLOBALS['pyrk_footer_section'] ?? null;
            if (!$section || stripos((string)$html, '</body>') === false || stripos((string)$html, 'class="pyrk-footer"') !== false || stripos((string)$html, "class='pyrk-footer'") !== false) {
                return $html;
            }

            $base = $section === 'admin' ? '../' : '';
            $headLink = '<link rel="stylesheet" href="' . htmlspecialchars($base . 'assets/css/footer.css', ENT_QUOTES, 'UTF-8') . '">';

            if (stripos((string)$html, 'assets/css/footer.css') === false && stripos((string)$html, '</head>') !== false) {
                $html = preg_replace('~</head>~i', $headLink . "\n</head>", (string)$html, 1);
            }

            $footer = function_exists('pyrk_capture_footer') ? pyrk_capture_footer((string)$section) : '';
            if ($footer === '') {
                return $html;
            }

            // Always expose the public privacy policy in the shared website footer.
            // This is additive only and keeps all existing manageable footer content unchanged.
            if (stripos($footer, 'pyrk-footer-privacy-link') === false) {
                $privacyHref = htmlspecialchars($base . 'privacy.php', ENT_QUOTES, 'UTF-8');
                $privacyLink = '<a class="pyrk-footer-privacy-link" href="' . $privacyHref . '" title="Read the Pyrk Privacy Policy" style="color:inherit;font-weight:900;text-decoration:none;white-space:nowrap">Privacy Policy</a>';
                $footerWithPrivacy = preg_replace_callback(
                    '~(<div class="pyrk-footer-bottom">.*?)(</div>\s*</footer>)~is',
                    static fn(array $matches): string => $matches[1] . $privacyLink . $matches[2],
                    $footer,
                    1
                );
                if (is_string($footerWithPrivacy) && $footerWithPrivacy !== '') {
                    $footer = $footerWithPrivacy;
                }
            }

            return preg_replace('~</body>~i', $footer . "\n</body>", (string)$html, 1);
        } catch (Throwable $e) {
            return $html;
        }
    });
}

if (!function_exists('pyrk_nav_brand_defaults')) {
    function pyrk_nav_brand_defaults(): array
    {
        return [
            'header_logo_text' => 'PY',
            'header_logo_image_path' => '',
            'header_admin_brand_name' => 'Pyrk Admin',
            'header_client_brand_name' => 'Pyrk',
            'header_subtitle' => 'Walking Club',
        ];
    }
}

if (!function_exists('pyrk_nav_brand_settings')) {
    function pyrk_nav_brand_settings(): array
    {
        static $cached = null;
        if (is_array($cached)) {
            return $cached;
        }

        $settings = pyrk_nav_brand_defaults();
        try {
            if (class_exists('App\\Core\\Database')) {
                $pdo = \App\Core\Database::connection();
                $keys = array_keys($settings);
                $placeholders = implode(',', array_fill(0, count($keys), '?'));
                $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN ($placeholders)");
                $stmt->execute($keys);
                foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
                    if (array_key_exists($row['setting_key'], $settings)) {
                        $settings[$row['setting_key']] = (string)$row['setting_value'];
                    }
                }
            }
        } catch (Throwable $e) {
            // Never allow brand settings to break the website.
        }

        $cached = $settings;
        return $settings;
    }
}

if (!function_exists('pyrk_render_nav')) {
function pyrk_render_nav(string $section = 'client'): void
{
    global $user;
    $GLOBALS['pyrk_footer_section'] = $section;

    $safe = static fn($value) => htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    $role = $user['role_name'] ?? 'guest';
    $isStaff = in_array($role, ['super_admin', 'event_manager', 'walk_leader'], true);
    $canPerm = static function (string $permission) use ($user): bool { return $user && \App\Core\Auth::hasPermission($permission, $user); };
    $inAdmin = $section === 'admin';
    $clientBase = $inAdmin ? '../' : '';
    $current = basename($_SERVER['PHP_SELF'] ?? '');
    $brand = pyrk_nav_brand_settings();

    $isActive = static function (array $files) use ($current): string {
        return in_array($current, $files, true) ? ' active' : '';
    };

    $brandHref = $inAdmin ? 'dashboard.php' : 'index.php';
    $brandTitle = $inAdmin ? ($brand['header_admin_brand_name'] ?: 'Pyrk Admin') : ($brand['header_client_brand_name'] ?: 'Pyrk');
    $brandSubtitle = $brand['header_subtitle'] ?: 'Walking Club';
    $logoText = strtoupper(substr(trim((string)($brand['header_logo_text'] ?: 'PY')), 0, 6));
    $logoPath = trim((string)($brand['header_logo_image_path'] ?? ''));
    $logoSrc = $logoPath !== '' ? $clientBase . ltrim($logoPath, '/') : '';
    $displayRole = str_replace('_', ' ', $role);

    $hasAssignedOrCreatedWalks = false;
    if ($user && $inAdmin) {
        try {
            $pdoNav = \App\Core\Database::connection();
            $userIdNav = (int)($user['id'] ?? 0);
            if ($userIdNav > 0) {
                $ownWalks = 0;
                try {
                    $ownStmt = $pdoNav->prepare('SELECT COUNT(*) FROM walks WHERE created_by = ?');
                    $ownStmt->execute([$userIdNav]);
                    $ownWalks = (int)$ownStmt->fetchColumn();
                } catch (\Throwable) {
                    $ownWalks = 0;
                }

                $assignedWalks = 0;
                try {
                    $tableStmt = $pdoNav->prepare('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?');
                    $tableStmt->execute(['walk_staff_assignments']);
                    if ((int)$tableStmt->fetchColumn() > 0) {
                        $assignStmt = $pdoNav->prepare('SELECT COUNT(*) FROM walk_staff_assignments WHERE user_id = ?');
                        $assignStmt->execute([$userIdNav]);
                        $assignedWalks = (int)$assignStmt->fetchColumn();
                    }
                } catch (\Throwable) {
                    $assignedWalks = 0;
                }

                $hasAssignedOrCreatedWalks = ($ownWalks + $assignedWalks) > 0;
            }
        } catch (\Throwable) {
            $hasAssignedOrCreatedWalks = false;
        }
    }

    $canSeeWalksMenu = $canPerm('walks.manage')
        || $canPerm('walks.view_all')
        || $canPerm('walks.view_assigned')
        || $canPerm('walks.create')
        || $canPerm('walks.edit')
        || $canPerm('walks.assign_staff')
        || $canPerm('walks.delete')
        || $canPerm('attendance.manage')
        || $hasAssignedOrCreatedWalks;
    $canSeeRoutesMenu = $canPerm('routes.manage') || $canPerm('routes.delete');
    $canSeeAttendanceMenu = $canPerm('attendance.manage') || $canSeeWalksMenu;
    $canSeeEventsMenu = $canSeeRoutesMenu || $canSeeWalksMenu || $canSeeAttendanceMenu;

    ?>
<style>
  .brand.brand-managed .brand-mark { overflow: hidden; flex: 0 0 auto; }
  .brand.brand-managed .brand-logo-img { width: 100%; height: 100%; object-fit: cover; display: block; border-radius: inherit; }
  .brand.brand-managed .brand-copy strong { max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .pyrk-live-clock { display:grid; gap:1px; min-width:132px; padding:7px 11px; border:1px solid rgba(28,124,84,.18); border-radius:16px; background:linear-gradient(135deg,#ecfdf3,#fff); color:#0f172a; box-shadow:0 8px 22px rgba(16,24,40,.05); }
  .pyrk-live-clock span { font-size:.62rem; font-weight:1000; letter-spacing:.12em; text-transform:uppercase; color:#0f7f55; line-height:1; }
  .pyrk-live-clock strong { font-size:.98rem; letter-spacing:.02em; line-height:1.1; }
  .pyrk-live-clock small { color:#64748b; font-size:.67rem; font-weight:900; line-height:1.1; }
  @media (max-width: 1180px) { .pyrk-live-clock { min-width:112px; padding:6px 9px; } .pyrk-live-clock small { display:none; } }
  .user-chip.user-chip-link { color: inherit; text-decoration: none; transition: transform .18s ease, box-shadow .18s ease, border-color .18s ease; }
  .user-chip.user-chip-link:hover, .user-chip.user-chip-link:focus-visible { transform: translateY(-1px); border-color: rgba(18,133,104,.35); box-shadow: 0 10px 24px rgba(15,23,42,.09); outline: none; }
  .user-chip.user-chip-link.active { border-color: rgba(18,133,104,.42); background: rgba(18,133,104,.08); }
  @media (max-width: 980px) { .brand.brand-managed .brand-copy strong { max-width: 140px; } .pyrk-live-clock { order:20; width:100%; } }
</style>
<header class="topbar pro-nav" data-pyrk-nav>
  <a class="brand brand-managed" href="<?= $safe($brandHref) ?>" aria-label="<?= $safe($brandTitle) ?> home">
    <span class="brand-mark">
      <?php if ($logoSrc !== ''): ?>
        <img class="brand-logo-img" src="<?= $safe($logoSrc) ?>" alt="<?= $safe($brandTitle) ?> logo">
      <?php else: ?>
        <?= $safe($logoText) ?>
      <?php endif; ?>
    </span>
    <span class="brand-copy"><strong><?= $safe($brandTitle) ?></strong><small><?= $safe($brandSubtitle) ?></small></span>
  </a>

  <button class="nav-toggle" type="button" aria-label="Open menu" aria-expanded="false" data-nav-toggle>
    <span></span><span></span><span></span>
  </button>

  <nav class="nav-menu" aria-label="Main navigation" data-nav-menu>
    <?php if ($inAdmin): ?>
      <a class="nav-link<?= $isActive(['dashboard.php']) ?>" href="dashboard.php">Dashboard</a>

      <?php if ($canSeeEventsMenu): ?>
      <div class="nav-group">
        <button class="nav-group-btn<?= $isActive(['routes.php', 'walks.php', 'walks_open.php', 'walks_closed.php', 'walks_finished.php', 'walks_archived.php', 'attendance.php']) ?>" type="button" aria-expanded="false">Events <span>▾</span></button>
        <div class="nav-dropdown nav-dropdown-wide nav-dropdown-pro">
          <?php if ($canSeeRoutesMenu): ?><a class="<?= $isActive(['routes.php']) ?>" href="routes.php"><strong>🗺️ Routes</strong><small>Create routes, checkpoints and stations</small></a><?php endif; ?>
          <?php if ($canSeeWalksMenu): ?>
            <a class="<?= $isActive(['walks.php']) ?>" href="walks.php"><strong>📅 Upcoming walks</strong><small>Future walks; Open ones also appear in Open</small></a>
            <a class="<?= $isActive(['walks_open.php']) ?>" href="walks_open.php"><strong>🟢 Open walks</strong><small>Upcoming, today and overdue walks still open for operations</small></a>
            <a class="<?= $isActive(['walks_closed.php', 'walks_finished.php']) ?>" href="walks_closed.php"><strong>🏁 Closed walks</strong><small>Walks explicitly marked Closed or Completed</small></a>
            <a class="<?= $isActive(['walks_archived.php']) ?>" href="walks_archived.php"><strong>🗄️ Archived walks</strong><small>Archived walk records and restore actions</small></a>
          <?php endif; ?>
          <?php if ($canSeeAttendanceMenu): ?><a class="<?= $isActive(['attendance.php']) ?>" href="attendance.php"><strong>✅ Attendance</strong><small>QR check-in and finish tracking for allowed walks</small></a><?php endif; ?>
        </div>
      </div>
      <?php endif; ?>

      <div class="nav-group">
        <button class="nav-group-btn<?= $isActive(['members.php', 'groups.php', 'users.php', 'waivers.php']) ?>" type="button" aria-expanded="false">People <span>▾</span></button>
        <div class="nav-dropdown nav-dropdown-wide nav-dropdown-pro">
          <?php if ($canPerm('users.manage') || $canPerm('users.delete')): ?>
            <a class="<?= $isActive(['users.php']) ?>" href="users.php"><strong>👤 System users</strong><small>Admins, managers and walk leaders</small></a>
          <?php endif; ?>
          <?php if ($canPerm('members.view') || $canPerm('members.manage') || $canPerm('members.delete')): ?>
            <a class="<?= $isActive(['members.php']) ?>" href="members.php"><strong>👥 Members CRM</strong><small>Client accounts, health notes and kilometers</small></a>
            <a class="<?= $isActive(['waivers.php']) ?>" href="waivers.php"><strong>🖊️ Signed waivers</strong><small>View signed waiver records, signatures and audit proof</small></a>
          <?php endif; ?>
          <?php if ($canPerm('groups.manage')): ?><a class="<?= $isActive(['groups.php']) ?>" href="groups.php"><strong>🏷️ Member groups</strong><small>VIP, corporate and invitation segments</small></a><?php endif; ?>
        </div>
      </div>

      <div class="nav-group">
        <button class="nav-group-btn<?= $isActive(['loyalty.php', 'inactivity_rules.php', 'badges.php', 'prizes.php', 'coupons.php']) ?>" type="button" aria-expanded="false">Rewards <span>▾</span></button>
        <div class="nav-dropdown nav-dropdown-wide nav-dropdown-pro">
          <?php if ($canPerm('loyalty.manage')): ?><a class="<?= $isActive(['loyalty.php']) ?>" href="loyalty.php"><strong>⭐ Loyalty points</strong><small>Adjust member points and view ledger</small></a><?php endif; ?>
          <?php if ($canPerm('loyalty.manage')): ?><a class="<?= $isActive(['inactivity_rules.php']) ?>" href="inactivity_rules.php"><strong>⏳ Inactivity rules</strong><small>Deduct points from inactive members automatically</small></a><?php endif; ?>
          <?php if ($canPerm('badges.manage')): ?><a class="<?= $isActive(['badges.php']) ?>" href="badges.php"><strong>🏅 Badges</strong><small>Create badge rules and award badges</small></a><?php endif; ?>
          <?php if ($canPerm('rewards.manage')): ?><a class="<?= $isActive(['prizes.php']) ?>" href="prizes.php"><strong>🎁 Prizes & claims</strong><small>Prize catalog, stock and fulfilment queue</small></a><?php endif; ?>
          <?php if ($canPerm('rewards.manage')): ?><a class="<?= $isActive(['coupons.php']) ?>" href="coupons.php"><strong>🎟️ Coupons</strong><small>Discount codes for paid walks</small></a><?php endif; ?>
        </div>
      </div>

      <div class="nav-group">
        <button class="nav-group-btn<?= $isActive(['photos.php', 'polls.php', 'payments.php', 'payment_methods.php', 'manual_notifications.php', 'push_notification_presets.php', 'walk_email_templates.php', 'whatsapp_presets.php', 'notifications.php', 'security.php', 'footer.php']) ?>" type="button" aria-expanded="false">Operations <span>▾</span></button>
        <div class="nav-dropdown nav-dropdown-wide nav-dropdown-pro">
          <?php if ($canPerm('photo_contest.manage')): ?><a class="<?= $isActive(['photos.php']) ?>" href="photos.php"><strong>📸 Photo contest</strong><small>Approve photos, close votes and select winners</small></a><?php endif; ?>
          <?php if (in_array($role, ['super_admin','event_manager'], true)): ?><a class="<?= $isActive(['polls.php']) ?>" href="polls.php"><strong>🗳️ Member polls</strong><small>Ask members about timing, dates, locations and routes</small></a><?php endif; ?>
          <?php if ($canPerm('payments.manage')): ?><a class="<?= $isActive(['payments.php']) ?>" href="payments.php"><strong>💳 Walk payments</strong><small>Paid walks, who paid, amount and payment type</small></a><?php endif; ?>
          <?php if ($canPerm('payments.manage')): ?><a class="<?= $isActive(['payment_methods.php']) ?>" href="payment_methods.php"><strong>💼 Payment methods</strong><small>Manage cash, card, transfer and other methods</small></a><?php endif; ?>
          <?php if ($canPerm('notifications.manage')): ?>
            <a class="<?= $isActive(['manual_notifications.php']) ?>" href="manual_notifications.php"><strong>🔔 Push notifications</strong><small>Send manual email, web and phone notices to members</small></a>
            <a class="<?= $isActive(['walk_email_templates.php']) ?>" href="walk_email_templates.php"><strong>✍️ Walk email content</strong><small>Customize invitation and reminder emails per walk</small></a>
          <?php endif; ?>
          <?php if ($canPerm('notifications.manage') || $canPerm('walks.manage') || $canPerm('walks.edit')): ?>
            <a class="<?= $isActive(['push_notification_presets.php']) ?>" href="push_notification_presets.php"><strong>🔔 Push notification presets</strong><small>Manage reusable push and in-app notification messages</small></a>
            <a class="<?= $isActive(['whatsapp_presets.php']) ?>" href="whatsapp_presets.php"><strong>💬 WhatsApp message presets</strong><small>Create, edit, default and remove reusable WhatsApp messages</small></a>
          <?php endif; ?>
          <?php if ($canPerm('notifications.manage') || $canPerm('backups.manage')): ?>
            <a class="<?= $isActive(['notifications.php']) ?>" href="notifications.php"><strong>✉️ Email & backup center</strong><small>Email events, delivery log and DB backups</small></a>
          <?php endif; ?>
          <?php if ($canPerm('security.manage')): ?>
            <a class="<?= $isActive(['security.php']) ?>" href="security.php"><strong>🔐 Security center</strong><small>Block accounts, login IPs and session settings</small></a>
          <?php endif; ?>
          <?php if ($canPerm('branding.manage')): ?>
            <a class="<?= $isActive(['footer.php']) ?>" href="footer.php"><strong>🎨 Branding & footer</strong><small>Top logo, names, footer and social links</small></a>
          <?php endif; ?>
        </div>
      </div>
    <?php else: ?>
      <a class="nav-link<?= $isActive(['index.php']) ?>" href="index.php">Dashboard</a>
      <a class="nav-link<?= $isActive(['polls.php']) ?>" href="polls.php">Polls</a>
      <a class="nav-link<?= $isActive(['notifications.php']) ?>" href="notifications.php">Notifications</a>

      <div class="nav-group">
        <button class="nav-group-btn<?= $isActive(['walk.php', 'my_qr.php', 'profile.php']) ?>" type="button" aria-expanded="false">My Club <span>▾</span></button>
        <div class="nav-dropdown">
          <?php if (!$isStaff): ?><a class="<?= $isActive(['profile.php']) ?>" href="profile.php"><strong>My Profile</strong><small>View and update your personal and safety details</small></a><?php endif; ?>
          <a href="index.php#walks"><strong>Upcoming walks</strong><small>Register, sign waiver and view route maps</small></a>
          <a class="<?= $isActive(['my_qr.php']) ?>" href="my_qr.php"><strong>My QR code</strong><small>Show this at check-in</small></a>
          <a href="index.php#badges"><strong>Badges & loyalty</strong><small>Track achievements and points</small></a>
          <a href="index.php#rewards"><strong>Claim prizes</strong><small>Redeem points for Pyrk rewards</small></a>
          <a href="index.php#history"><strong>Walk history</strong><small>View kilometers and attendance</small></a>
        </div>
      </div>
    <?php endif; ?>
  </nav>

  <div class="nav-user">
    <div class="pyrk-live-clock" data-pyrk-live-clock data-pyrk-server-epoch="<?= time() ?>" data-pyrk-timezone="Asia/Beirut" title="Official Pyrk system time">
      <span>Lebanon time</span>
      <strong>--:--:--</strong>
      <small>Asia/Beirut</small>
    </div>
    <?php if ($inAdmin): ?>
      <a class="nav-action-pill" href="../index.php">Client Portal</a>
    <?php elseif ($isStaff): ?>
      <a class="nav-action-pill" href="admin/dashboard.php">Admin Portal</a>
    <?php endif; ?>
    <a class="nav-action-pill<?= $isActive(['change_password.php']) ?>" href="<?= $safe($clientBase . 'change_password.php') ?>">Password</a>

    <?php if ($inAdmin || $isStaff): ?>
    <div class="user-chip" title="<?= $safe($role) ?>">
      <?php if (!empty($user['profile_photo_path'])): ?>
        <img src="<?= $safe($clientBase . $user['profile_photo_path']) ?>" alt="<?= $safe($user['full_name'] ?? 'User') ?>">
      <?php else: ?>
        <span><?= $safe(strtoupper(substr($user['full_name'] ?? 'P', 0, 1))) ?></span>
      <?php endif; ?>
      <div><strong><?= $safe($user['full_name'] ?? 'Guest') ?></strong><small><?= $safe($displayRole) ?></small></div>
    </div>
    <?php else: ?>
    <a class="user-chip user-chip-link<?= $isActive(['profile.php']) ?>" href="profile.php" title="Open my profile" aria-label="Open my profile">
      <?php if (!empty($user['profile_photo_path'])): ?>
        <img src="<?= $safe($clientBase . $user['profile_photo_path']) ?>" alt="<?= $safe($user['full_name'] ?? 'User') ?>">
      <?php else: ?>
        <span><?= $safe(strtoupper(substr($user['full_name'] ?? 'P', 0, 1))) ?></span>
      <?php endif; ?>
      <div><strong><?= $safe($user['full_name'] ?? 'Guest') ?></strong><small>My Profile</small></div>
    </a>
    <?php endif; ?>
    <a class="btn btn-small btn-logout" href="<?= $safe($clientBase . 'login-dev.php?logout=1') ?>">Logout</a>
  </div>
</header>
<script>
(function(){
  const root = document.currentScript.previousElementSibling;
  if (!root || root.dataset.navReady === '1') return;
  root.dataset.navReady = '1';
  const toggle = root.querySelector('[data-nav-toggle]');
  const menu = root.querySelector('[data-nav-menu]');
  const groupButtons = root.querySelectorAll('.nav-group-btn');

  if (toggle && menu) {
    toggle.addEventListener('click', function(){
      const open = root.classList.toggle('nav-open');
      toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    });
  }

  groupButtons.forEach(function(btn){
    btn.addEventListener('click', function(event){
      event.stopPropagation();
      const group = btn.closest('.nav-group');
      const isOpen = group.classList.contains('open');
      root.querySelectorAll('.nav-group.open').forEach(function(item){
        if (item !== group) {
          item.classList.remove('open');
          const b = item.querySelector('.nav-group-btn');
          if (b) b.setAttribute('aria-expanded', 'false');
        }
      });
      group.classList.toggle('open', !isOpen);
      btn.setAttribute('aria-expanded', !isOpen ? 'true' : 'false');
    });
  });

  document.addEventListener('click', function(event){
    if (!root.contains(event.target)) {
      root.querySelectorAll('.nav-group.open').forEach(function(group){
        group.classList.remove('open');
        const btn = group.querySelector('.nav-group-btn');
        if (btn) btn.setAttribute('aria-expanded', 'false');
      });
    }
  });

  const clockFormatter = new Intl.DateTimeFormat('en-GB', {
    timeZone: 'Asia/Beirut',
    weekday: 'short',
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });

  function updatePyrkLebanonClocks(){
    const nowPerf = (window.performance && performance.now) ? performance.now() : Date.now();
    document.querySelectorAll('[data-pyrk-live-clock]').forEach(function(clock){
      if (!clock.dataset.pyrkLoadedPerf) clock.dataset.pyrkLoadedPerf = String(nowPerf);
      const loadedPerf = Number(clock.dataset.pyrkLoadedPerf || nowPerf);
      const serverEpoch = Number(clock.dataset.pyrkServerEpoch || root.dataset.pyrkServerEpoch || Math.floor(Date.now()/1000));
      const current = new Date((serverEpoch * 1000) + (nowPerf - loadedPerf));
      const parts = clockFormatter.formatToParts(current).reduce(function(map, part){ map[part.type] = part.value; return map; }, {});
      const time = [parts.hour, parts.minute, parts.second].filter(Boolean).join(':');
      const date = [parts.weekday, parts.day, parts.month, parts.year].filter(Boolean).join(' ');
      const strong = clock.querySelector('strong');
      const small = clock.querySelector('small');
      if (strong) strong.textContent = time || clockFormatter.format(current);
      if (small) small.textContent = date + ' · Asia/Beirut';
    });
  }
  updatePyrkLebanonClocks();
  setInterval(updatePyrkLebanonClocks, 1000);

  document.addEventListener('keydown', function(event){
    if (event.key === 'Escape') {
      root.classList.remove('nav-open');
      if (toggle) toggle.setAttribute('aria-expanded', 'false');
      root.querySelectorAll('.nav-group.open').forEach(function(group){
        group.classList.remove('open');
        const btn = group.querySelector('.nav-group-btn');
        if (btn) btn.setAttribute('aria-expanded', 'false');
      });
    }
  });
})();
</script>
<script defer src="<?= $safe($clientBase . 'assets/js/native_device_bridge.js?v=2') ?>"></script>
<link rel="stylesheet" href="<?= $safe($clientBase . 'assets/css/native_app_bottom_edge.css?v=1') ?>">
<?php if ($inAdmin): ?>
<link rel="stylesheet" href="<?= $safe($clientBase . 'assets/css/native_app_mobile_polish.css?v=7-admin-dock') ?>">
<script defer src="<?= $safe($clientBase . 'assets/js/native_app_mobile_polish.js?v=7-admin-dock') ?>"></script>
<?php endif; ?>
<?php
}
}
