<?php
  // Build user display and menu data
  $userName  = trim((string) (session()->get('user_name') ?? ''));
  $userEmail = trim((string) (session()->get('user_email') ?? ''));
  $rawRole   = session()->get('role');
  $allRoles  = array_map(fn($r)=> strtolower(trim((string)$r)), (array) (session()->get('roles') ?? []));
  $currentRole = strtolower((string) ($rawRole ?? 'guest'));
  $otherRoles  = array_values(array_filter($allRoles, fn($r) => $r !== '' && $r !== $currentRole));

  // Compute initials from name, fallback to email/letter U
  $initials = 'U';
  if ($userName !== '') {
      $parts = preg_split('/\s+/', $userName);
      $first = $parts[0] ?? '';
      $last  = count($parts) > 1 ? end($parts) : '';
      $initials = strtoupper(substr($first, 0, 1) . ($last !== '' ? substr($last, 0, 1) : ''));
  } elseif ($userEmail !== '') {
      $initials = strtoupper(substr($userEmail, 0, 1));
  }

  // Style palettes
  $styleCfg = config('Style');
  $sess = session();
  $currentAccent = $sess->get('style_color') ?? ($styleCfg->defaultStyle ?? 'blue');
  $currentMenu   = $sess->get('menu_color')  ?? ($styleCfg->defaultMenu  ?? 'white');
  // Build current menu palette (supports custom)
  if ($currentMenu === 'custom') {
      $menuLP = [
        'bg' => (string)($sess->get('menu_custom_bg') ?? '#0f172a'),
        'text' => (string)($sess->get('menu_custom_text') ?? '#ffffff'),
        'mode' => (string)($sess->get('menu_custom_mode') ?? 'dark'),
      ];
  } else {
      $menuLP = $styleCfg->menuPalettes[$currentMenu] ?? ($styleCfg->menuPalettes[$styleCfg->defaultMenu] ?? [
        'bg' => '#ffffff', 'text' => '#334155', 'mode' => 'light']);
  }
  $resolveMenuMode = function (string $mode, string $bg): string {
      $mode = strtolower(trim($mode));
      if ($mode === 'light' || $mode === 'dark') return $mode;
      $hex = ltrim(trim($bg), '#');
      if (strlen($hex) === 3) {
          $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
      }
      if (strlen($hex) !== 6) return 'dark';
      $r = hexdec(substr($hex, 0, 2));
      $g = hexdec(substr($hex, 2, 2));
      $b = hexdec(substr($hex, 4, 2));
      $lum = (0.2126 * $r + 0.7152 * $g + 0.0722 * $b) / 255.0;
      return ($lum < 0.5) ? 'dark' : 'light';
  };
  $headerMode = $resolveMenuMode((string)($menuLP['mode'] ?? 'light'), (string)($menuLP['bg'] ?? '#0f172a'));
  $headerModeCls = ($headerMode === 'dark') ? 'navbar-dark' : 'navbar-light';
?>

<header class="navbar <?= esc($headerModeCls) ?> sticky-top bg-white border-bottom flex-md-nowrap p-0 shadow-sm">
  <div class="d-flex align-items-center w-100">
    <!-- Brand (left) -->
    <a class="navbar-brand col-md-3 col-lg-2 mr-0 px-1" href="/administrator/administratordashboard">
      <img src="<?= base_url('assets/images/logo.png') ?>" alt="School Icon" style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover; margin-right: 8px;">
      <strong>School Management Dashboard</strong>
    </a>

    <!-- Spacer pushes avatar to the right -->
    <div class="ms-auto"></div>

    <!-- Gmail-like avatar with initials (top-right) -->
    <div class="dropdown me-2">
      <button class="btn p-0 bg-transparent border-0" id="userAvatarMenu" data-bs-toggle="dropdown" data-bs-auto-close="outside" aria-expanded="false" aria-label="Open user menu">
        <div class="rounded-circle text-white fw-semibold d-flex align-items-center justify-content-center"
             style="width: 40px; height: 40px; background-color: var(--mgmt-primary);">
          <?= esc($initials) ?>
        </div>
      </button>
      <div class="dropdown-menu dropdown-menu-end p-0" aria-labelledby="userAvatarMenu" style="min-width: 260px;">
        <div class="px-3 py-3 d-flex align-items-center">
          <div class="rounded-circle text-white fw-semibold d-flex align-items-center justify-content-center me-3"
               style="width: 36px; height: 36px; background-color: var(--mgmt-primary);">
            <?= esc($initials) ?>
          </div>
          <div>
            <div class="fw-semibold mb-0" style="line-height: 1.2;">
              <?= esc($userName !== '' ? $userName : 'User') ?>
            </div>
            <div class="text-muted small" style="line-height: 1.2;">
              <?= esc($currentRole) ?><?= $userEmail ? ' · ' . esc($userEmail) : '' ?>
            </div>
          </div>
        </div>
        <div class="dropdown-divider"></div>
        <?php if (!empty($otherRoles)): ?>
          <a class="dropdown-item d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#ddRoleBody" role="button" aria-expanded="false" aria-controls="ddRoleBody">
            Switch Role <i class="bi bi-chevron-down ms-2"></i>
          </a>
          <div class="collapse" id="ddRoleBody">
            <div class="px-2 pb-2">
              <?php foreach ($otherRoles as $r): ?>
                <form method="post" action="<?= site_url('set-role') ?>" class="mb-1">
                  <?= csrf_field() ?>
                  <input type="hidden" name="selected_role" value="<?= esc($r) ?>">
                  <button type="submit" class="dropdown-item">Switch to <?= esc(ucfirst(str_replace('_', ' ', $r))) ?></button>
                </form>
              <?php endforeach; ?>
            </div>
          </div>
          <div class="dropdown-divider"></div>
        <?php endif; ?>

        <a class="dropdown-item d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#ddStyleBody" role="button" aria-expanded="false" aria-controls="ddStyleBody">
          Style <i class="bi bi-chevron-down ms-2"></i>
        </a>
        <div class="collapse" id="ddStyleBody">
          <div class="px-2 pb-2">
            <a class="dropdown-item d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#ddAccentBody" role="button" aria-expanded="true" aria-controls="ddAccentBody">
              Accent <i class="bi bi-chevron-down ms-2"></i>
            </a>
            <div class="collapse show" id="ddAccentBody">
              <div class="px-2 pb-2">
                <?php foreach (array_keys($styleCfg->stylePalettes ?? []) as $opt): ?>
                  <?php $isActive = ($opt === $currentAccent); ?>
                  <a class="dropdown-item <?= $isActive ? 'active' : '' ?>" href="<?= site_url('ui/style?accent=' . urlencode($opt) . '&back=' . urlencode(current_url())) ?>" <?= $isActive ? 'aria-current="true"' : '' ?>>
                    <?= ucfirst(esc($opt)) ?><?= $isActive ? ' <i class=\"bi bi-check-lg ms-2\"></i>' : '' ?>
                  </a>
                <?php endforeach; ?>
              </div>
            </div>
            <div class="dropdown-divider"></div>
            <div class="px-2 small text-muted">Menu</div>
            <div class="px-2 pb-2">
              <div class="table-responsive">
                <table class="table table-borderless mb-2" style="min-width:auto;">
                  <tbody>
                    <?php
                      $palettes = $styleCfg->menuPalettes ?? [];
                      $keys = array_keys($palettes);
                      $cols = 3; $i = 0;
                      foreach ($keys as $k):
                        if ($i % $cols === 0) echo '<tr>';
                        $pal = $palettes[$k];
                        $bg = (string)($pal['bg'] ?? '#fff');
                        $tx = (string)($pal['text'] ?? '#000');
                        $active = ($k === $currentMenu) ? 'outline-success' : 'outline-secondary';
                    ?>
                      <td class="p-1" style="width:33.33%;">
                        <a href="<?= site_url('ui/style?menu=' . urlencode($k) . '&back=' . urlencode(current_url())) ?>" class="btn btn-<?= $active ?> w-100" style="padding:6px;">
                          <div class="rounded" style="height:28px; background-color: <?= esc($bg) ?>; color: <?= esc($tx) ?>; display:flex; align-items:center; justify-content:center; font-size:.8rem;">
                            <?= ucfirst(esc($k)) ?>
                          </div>
                        </a>
                      </td>
                    <?php
                        $i++;
                        if ($i % $cols === 0) echo '</tr>';
                      endforeach;
                      if ($i % $cols !== 0) { while ($i % $cols !== 0) { echo '<td class="p-1"></td>'; $i++; } echo '</tr>'; }
                    ?>
                  </tbody>
                </table>
              </div>
              <!-- Custom color picker -->
              <form action="<?= site_url('ui/style') ?>" method="get" class="px-1">
                <input type="hidden" name="menu" value="custom">
                <input type="hidden" name="back" value="<?= esc(current_url()) ?>">
                <div class="row g-2 align-items-center">
                  <div class="col-6">
                    <label class="form-label mb-1 small">Menu BG</label>
                    <input type="color" name="menu_bg" value="<?= esc($menuLP['bg'] ?? '#0f172a') ?>" class="form-control form-control-color w-100" title="Pick background color">
                  </div>
                  <div class="col-6">
                    <label class="form-label mb-1 small">Text</label>
                    <input type="color" name="menu_text" value="<?= esc($menuLP['text'] ?? '#ffffff') ?>" class="form-control form-control-color w-100" title="Pick text color">
                  </div>
                  <div class="col-12">
                    <label class="form-label mb-1 small">Mode</label>
                    <div>
                      <?php $modeLP = ($menuLP['mode'] ?? 'light'); ?>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="menu_mode" id="mg_mm_light" value="light" <?= $modeLP==='light'?'checked':'' ?>>
                        <label class="form-check-label" for="mg_mm_light">Light</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="menu_mode" id="mg_mm_dark" value="dark" <?= $modeLP==='dark'?'checked':'' ?>>
                        <label class="form-check-label" for="mg_mm_dark">Dark</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="menu_mode" id="mg_mm_auto" value="auto" <?= ($modeLP!=='light' && $modeLP!=='dark')?'checked':'' ?>>
                        <label class="form-check-label" for="mg_mm_auto">Auto</label>
                      </div>
                    </div>
                  </div>
                  <div class="col-12 mt-1">
                    <button type="submit" class="btn btn-sm btn-primary w-100">Apply Custom</button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>

        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="<?= base_url('/logout') ?>">Log Out</a>
      </div>
    </div>
  </div>
</header>
