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

  // Initials for avatar
  $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 config and current selections
  $styleCfg = config('Style');
  $sess = session();
  $currentAccent = $sess->get('style_color') ?? ($styleCfg->defaultStyle ?? 'blue');
  $currentMenu   = $sess->get('menu_color')  ?? ($styleCfg->defaultMenu  ?? 'white');
  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']);
  }
?>

<a class="nav-link p-0" href="#" id="quickMenu" role="button" 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>
  <span class="visually-hidden">User menu</span>
  <span class="dropdown-toggle ms-1" style="font-size:0; line-height:0;"> </span>
</a>
<div class="dropdown-menu dropdown-menu-end quick-menu" aria-labelledby="quickMenu" style="max-height: 70vh; overflow-y: auto; overflow-x: hidden; min-width: 260px; max-width: min(320px, calc(100vw - 16px)); right: 8px; left: auto;">
  <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($roleStr) ?><?= $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="#ddRoleMenu" role="button" aria-expanded="false" aria-controls="ddRoleMenu">
      Switch Role <i class="bi bi-chevron-down ms-2"></i>
    </a>
    <div class="collapse" id="ddRoleMenu">
      <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="#ddStyleMenu" role="button" aria-expanded="false" aria-controls="ddStyleMenu">
    Style <i class="bi bi-chevron-down ms-2"></i>
  </a>
  <div class="collapse" id="ddStyleMenu">
    <div class="px-2 pb-2">
      <a class="dropdown-item d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#ddAccentMenu" role="button" aria-expanded="true" aria-controls="ddAccentMenu">
        Accent <i class="bi bi-chevron-down ms-2"></i>
      </a>
      <div class="collapse show" id="ddAccentMenu">
        <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="mm_light" value="light" <?= $modeLP==='light'?'checked':'' ?>>
                  <label class="form-check-label" for="mm_light">Light</label>
                </div>
                <div class="form-check form-check-inline">
                  <input class="form-check-input" type="radio" name="menu_mode" id="mm_dark" value="dark" <?= $modeLP==='dark'?'checked':'' ?>>
                  <label class="form-check-label" for="mm_dark">Dark</label>
                </div>
                <div class="form-check form-check-inline">
                  <input class="form-check-input" type="radio" name="menu_mode" id="mm_auto" value="auto" <?= ($modeLP!=='light' && $modeLP!=='dark')?'checked':'' ?>>
                  <label class="form-check-label" for="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>
