<?php
if (!isset($pageTitle) || $pageTitle === '') {
  $pageTitle = 'Domix.Dev';
}
$sh = $_SESSION['dxbinder'] ?? null;
$isDxBinderLogged = is_array($sh) && (($sh['loggedin'] ?? false) === true);
$isDxBinderPath = isset($_SERVER['REQUEST_URI']) && is_string($_SERVER['REQUEST_URI']) && (strpos($_SERVER['REQUEST_URI'], '/main/dxbinder') === 0);
$isLoginPage = isset($_SERVER['REQUEST_URI']) && is_string($_SERVER['REQUEST_URI']) && (strpos($_SERVER['REQUEST_URI'], '/main/dxbinder/login') !== false);
$showDxBinderUserMenu = $isDxBinderLogged && $isDxBinderPath && !$isLoginPage;

// DXBots
$shBots = $_SESSION['dxbots'] ?? null;
$isDxBotsLogged = is_array($shBots) && (($shBots['loggedin'] ?? false) === true);
$isDxBotsPath = isset($_SERVER['REQUEST_URI']) && is_string($_SERVER['REQUEST_URI']) && (strpos($_SERVER['REQUEST_URI'], '/main/dxbots') === 0);
$isDxBotsLoginPage = isset($_SERVER['REQUEST_URI']) && is_string($_SERVER['REQUEST_URI']) && (strpos($_SERVER['REQUEST_URI'], '/main/dxbots/login') !== false);
$showDxBotsUserMenu = $isDxBotsLogged && $isDxBotsPath && !$isDxBotsLoginPage;
$userName = $isDxBinderLogged ? (string)($sh['username'] ?? '') : 'Gast';
$fractionLabel = '—';
if ($isDxBinderLogged) {
  $fractionId = (int)($sh['fraction'] ?? 0);
  $fractionName = strtoupper(trim((string)($sh['fraction_name'] ?? '')));
  
  $cfgFile = __DIR__ . '/../config/dxbinder.php';
  if (is_file($cfgFile)) {
    $cfg = require $cfgFile;
    $fractions = is_array($cfg) ? ($cfg['fractions'] ?? []) : [];
    
    if (isset($fractions[$fractionId])) {
      $fracCfg = $fractions[$fractionId];
      if (is_array($fracCfg)) {
        $hasSub = (bool)($fracCfg['has_sub_fractions'] ?? false);
        if ($hasSub && $fractionId === 1 && $fractionName !== '') {
          $fractionLabel = $fractionName;
        } else {
          $fractionLabel = (string)($fracCfg['name'] ?? 'Fraktion ' . $fractionId);
        }
      }
    }
  }
  
  if ($fractionLabel === '—') {
    $fractionLabel = 'Fraktion ' . $fractionId;
  }
}
$rangLabel = $isDxBinderLogged ? (string)($sh['rang'] ?? '') : '—';
$rangNum = 0;
if ($isDxBinderLogged) {
  $rangNum = (int)preg_replace('/[^0-9]/', '', (string)($sh['rang'] ?? '0'));
}
$adminValue = $isDxBinderLogged ? (string)($sh['admin'] ?? '0') : '0';
$logoutUrl = $isDxBinderLogged ? '/main/dxbinder/logout.php' : '/';

if (!isset($avatarUrl) || $avatarUrl === '') {
  $cfgFile = __DIR__ . '/../config/dxbinder.php';
  if ($showDxBinderUserMenu && is_file($cfgFile)) {
    $cfg = require $cfgFile;
    $avatars = is_array($cfg) ? ($cfg['avatars'] ?? null) : null;
    $fractions = is_array($avatars) ? ($avatars['fractions'] ?? null) : null;

    $fractionId = (int)($sh['fraction'] ?? 0);
    $subName = strtoupper(trim((string)($sh['fraction_name'] ?? '')));

    if (is_array($fractions) && isset($fractions[$fractionId])) {
      $entry = $fractions[$fractionId];
      if (is_array($entry)) {
        $sub = $entry['sub'] ?? null;
        if (is_array($sub) && $subName !== '' && isset($sub[$subName]) && is_string($sub[$subName]) && $sub[$subName] !== '') {
          $avatarUrl = $sub[$subName];
        } else {
          $def = $entry['default'] ?? '';
          if (is_string($def) && $def !== '') $avatarUrl = $def;
        }
      } elseif (is_string($entry) && $entry !== '') {
        $avatarUrl = $entry;
      }
    }

    if ((!isset($avatarUrl) || $avatarUrl === '') && is_array($avatars) && isset($avatars['default']) && is_string($avatars['default'])) {
      $avatarUrl = $avatars['default'];
    }
  }

  if (!isset($avatarUrl) || $avatarUrl === '') {
    $avatarUrl = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop stop-color="%238b7bff"/><stop offset="1" stop-color="%233aa6ff"/></linearGradient></defs><rect width="64" height="64" rx="32" fill="url(%23g)"/><text x="32" y="40" font-family="Arial" font-size="28" text-anchor="middle" fill="white">D</text></svg>';
  }
}
?>
<!doctype html>
<html lang="de">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="color-scheme" content="dark light" />
    <title><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></title>
    <link rel="icon" type="image/png" sizes="16x16" href="/main/assets/images/newfavicon.png" />
    <link rel="icon" type="image/png" sizes="32x32" href="/main/assets/images/newfavicon.png" />
    <link rel="icon" type="image/png" sizes="64x64" href="/main/assets/images/newfavicon.png" />
    <link rel="shortcut icon" type="image/png" href="/main/assets/images/newfavicon.png" />
    <link rel="apple-touch-icon" sizes="180x180" href="/main/assets/images/newfavicon.png" />
    <link rel="icon" type="image/png" sizes="192x192" href="/main/assets/images/newfavicon.png" />
    <link rel="icon" type="image/png" sizes="512x512" href="/main/assets/images/newfavicon.png" />
    <link rel="stylesheet" href="/main/assets/css/site.css?v=<?= @filemtime(__DIR__ . '/../assets/css/site.css') ?: '1' ?>" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
    <script>
      (function () {
        var saved = localStorage.getItem("domix_theme");
        var theme = saved === "light" ? "light" : "dark";
        document.documentElement.setAttribute("data-theme", theme);
      })();
    </script>
    <script>
      (function() {
        document.addEventListener('DOMContentLoaded', function() {
          const allNavDds = document.querySelectorAll('.nav');
          if (!allNavDds.length) return;
          
          const nav = allNavDds[0];
          
          const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
          const mobileMenuOverlay = document.createElement('div');
          mobileMenuOverlay.className = 'mobile-menu-overlay';
          document.body.appendChild(mobileMenuOverlay);

          if (mobileMenuToggle && nav) {
            const actions = document.querySelector('.actions');
            const mobileMenuClose = document.querySelector('.mobile-menu-close');
            
            function openMobileMenu() {
              nav.classList.add('mobile-open');
              mobileMenuOverlay.classList.add('active');
              mobileMenuToggle.setAttribute('aria-expanded', 'true');
              document.body.style.overflow = 'hidden';
              if (actions) {
                actions.style.display = 'none';
              }
              if (mobileMenuClose) {
                mobileMenuClose.style.display = 'flex';
              }
            }

            function closeMobileMenu() {
              nav.classList.remove('mobile-open');
              mobileMenuOverlay.classList.remove('active');
              mobileMenuToggle.setAttribute('aria-expanded', 'false');
              document.body.style.overflow = '';
              if (actions) {
                actions.style.display = '';
              }
              if (mobileMenuClose) {
                mobileMenuClose.style.display = 'none';
              }
            }
            
            if (mobileMenuClose) {
              mobileMenuClose.addEventListener('click', closeMobileMenu);
              mobileMenuClose.addEventListener('touchend', function(e) {
                e.preventDefault();
                closeMobileMenu();
              });
            }

            function toggleMobileMenu(e) {
              if (e) {
                e.preventDefault();
                e.stopPropagation();
              }
              const isOpen = nav.classList.contains('mobile-open');
              if (isOpen) {
                closeMobileMenu();
              } else {
                openMobileMenu();
              }
            }

            mobileMenuToggle.addEventListener('click', toggleMobileMenu);
            mobileMenuToggle.addEventListener('touchend', function(e) {
              e.preventDefault();
              toggleMobileMenu(e);
            });

            mobileMenuOverlay.addEventListener('click', function(e) {
              if (!e.target.closest('.nav')) {
                closeMobileMenu();
              }
            });

            nav.addEventListener('click', function(e) {
              e.stopPropagation();
              if (e.target.closest('a') && !e.target.closest('.nav-dd-trigger')) {
                closeMobileMenu();
              }
            });

            document.addEventListener('keydown', function(e) {
              if (e.key === 'Escape' && nav.classList.contains('mobile-open')) {
                closeMobileMenu();
              }
            });
          }
          const allDropdowns = nav.querySelectorAll('.nav-dd');
          
          let lastMouseX = 0;
          let lastMouseY = 0;
          let checkRunning = false;
          
          function checkMouseOutsideDropdowns() {
            let hasOpenDropdown = false;
            
            allDropdowns.forEach(function(dropdown) {
              if (!dropdown.classList.contains('open')) return;
              
              hasOpenDropdown = true;
              const rect = dropdown.getBoundingClientRect();
              const menu = dropdown.querySelector('.nav-dd-menu');
              const menuRect = menu ? menu.getBoundingClientRect() : null;
              
              // Prüfe sowohl Trigger als auch Menü
              const isInTrigger = lastMouseX >= rect.left && 
                                  lastMouseX <= rect.right && 
                                  lastMouseY >= rect.top && 
                                  lastMouseY <= rect.bottom;
              
              const isInMenu = menuRect && 
                              lastMouseX >= menuRect.left && 
                              lastMouseX <= menuRect.right && 
                              lastMouseY >= menuRect.top && 
                              lastMouseY <= menuRect.bottom;
              
              // Prüfe auch die Lücke zwischen Trigger und Menü (::after Element)
              const isInGap = menuRect && 
                             lastMouseX >= Math.min(rect.left, menuRect.left) && 
                             lastMouseX <= Math.max(rect.right, menuRect.right) && 
                             lastMouseY >= rect.bottom && 
                             lastMouseY <= menuRect.top;
              
              if (!isInTrigger && !isInMenu && !isInGap) {
                dropdown.classList.remove('open');
                const trigger = dropdown.querySelector('.nav-dd-trigger');
                if (trigger) {
                  trigger.setAttribute('aria-expanded', 'false');
                }
              }
            });
            
            if (hasOpenDropdown) {
              requestAnimationFrame(checkMouseOutsideDropdowns);
            } else {
              checkRunning = false;
            }
          }
          
          document.addEventListener('mousemove', function(e) {
            lastMouseX = e.clientX;
            lastMouseY = e.clientY;
            
            // Nur auf Mobile oder wenn Navigation im Mobile-Modus ist
            if (window.innerWidth <= 768 || nav.classList.contains('mobile-open')) {
              if (!checkRunning) {
                checkRunning = true;
                checkMouseOutsideDropdowns();
              }
            }
          });
          
          document.addEventListener('click', function(e) {
            lastMouseX = e.clientX;
            lastMouseY = e.clientY;
            
            // Nur auf Mobile oder wenn Navigation im Mobile-Modus ist
            if (window.innerWidth <= 768 || nav.classList.contains('mobile-open')) {
              if (!checkRunning) {
                checkRunning = true;
                checkMouseOutsideDropdowns();
              }
            }
          });
          
          function isMobileView() {
            return window.innerWidth <= 768;
          }
          
          allDropdowns.forEach(function(dropdown) {
            const trigger = dropdown.querySelector('.nav-dd-trigger');
            if (!trigger) return;

            function closeDropdown() {
              dropdown.classList.remove('open');
              trigger.setAttribute('aria-expanded', 'false');
            }

            function openDropdown() {
              allDropdowns.forEach(function(otherDropdown) {
                if (otherDropdown !== dropdown) {
                  otherDropdown.classList.remove('open');
                  const otherTrigger = otherDropdown.querySelector('.nav-dd-trigger');
                  if (otherTrigger) {
                    otherTrigger.setAttribute('aria-expanded', 'false');
                  }
                }
              });

              dropdown.classList.add('open');
              trigger.setAttribute('aria-expanded', 'true');
            }

            function toggleDropdown(e) {
              if (e) {
                e.preventDefault();
                e.stopPropagation();
              }
              const isOpen = dropdown.classList.contains('open');
              if (isOpen) {
                closeDropdown();
              } else {
                openDropdown();
              }
            }

            let lastInteractionTime = 0;
            let lastInteractionType = null;

            function isMobileSize() {
              return window.innerWidth <= 768 || nav.classList.contains('mobile-open');
            }

            function handleInteraction(e, type) {
              const now = Date.now();
              const isMobile = isMobileSize();

              if (type === 'click' && lastInteractionType === 'touch' && (now - lastInteractionTime) < 300) {
                e.preventDefault();
                e.stopPropagation();
                return;
              }

              lastInteractionTime = now;
              lastInteractionType = type;

              if (isMobile) {
                if (e) {
                  e.preventDefault();
                  e.stopPropagation();
                }
                toggleDropdown(e);
              }
            }

            trigger.addEventListener('touchend', function(e) {
              if (isMobileSize()) {
                handleInteraction(e, 'touch');
              }
            });

            trigger.addEventListener('click', function(e) {
              e.preventDefault();
              e.stopPropagation();
              if (isMobileSize()) {
                handleInteraction(e, 'click');
              }
            }, true);

            // Desktop: Hover-Verhalten
            let hoverTimeout = null;
            
            function clearHoverTimeout() {
              if (hoverTimeout) {
                clearTimeout(hoverTimeout);
                hoverTimeout = null;
              }
            }
            
            function handleDropdownEnter() {
              clearHoverTimeout();
              if (window.innerWidth > 768 && !nav.classList.contains('mobile-open')) {
                openDropdown();
              }
            }
            
            function handleDropdownLeave(e) {
              clearHoverTimeout();
              
              if (window.innerWidth <= 768 || nav.classList.contains('mobile-open')) {
                return;
              }
              
              // Prüfe, ob die Maus zu einem Kind-Element geht
              const relatedTarget = e.relatedTarget;
              if (relatedTarget && dropdown.contains(relatedTarget)) {
                return;
              }
              
              // Verzögerung, damit die Maus Zeit hat, das Menü zu erreichen
              hoverTimeout = setTimeout(function() {
                // Finale Prüfung: Ist die Maus wirklich außerhalb?
                const rect = dropdown.getBoundingClientRect();
                const menu = dropdown.querySelector('.nav-dd-menu');
                const menuRect = menu ? menu.getBoundingClientRect() : null;
                
                const isInDropdown = lastMouseX >= rect.left && 
                                     lastMouseX <= rect.right && 
                                     lastMouseY >= rect.top && 
                                     lastMouseY <= rect.bottom;
                
                const isInMenu = menuRect && 
                                 lastMouseX >= menuRect.left && 
                                 lastMouseX <= menuRect.right && 
                                 lastMouseY >= menuRect.top && 
                                 lastMouseY <= menuRect.bottom;
                
                if (!isInDropdown && !isInMenu) {
                  closeDropdown();
                }
                hoverTimeout = null;
              }, 200);
            }
            
            // Mouseenter Events
            trigger.addEventListener('mouseenter', handleDropdownEnter);
            dropdown.addEventListener('mouseenter', handleDropdownEnter);
            
            const menu = dropdown.querySelector('.nav-dd-menu');
            if (menu) {
              menu.addEventListener('mouseenter', handleDropdownEnter);
              menu.addEventListener('mouseleave', handleDropdownLeave);
            }
            
            // Mouseleave nur auf dem Dropdown-Container
            dropdown.addEventListener('mouseleave', handleDropdownLeave);
          });
          
          const devMenu = document.querySelector('.nav-dd-dev');
          if (devMenu) {
            const submenuTriggers = devMenu.querySelectorAll('.nav-dd-submenu-trigger');
            
            submenuTriggers.forEach(function(trigger) {
              const submenu = trigger.closest('.nav-dd-submenu');
              if (!submenu) return;
              
              function toggleSubmenu(e) {
                if (e) {
                  e.preventDefault();
                  e.stopPropagation();
                }
                
                const isOpen = submenu.classList.contains('is-open');
                
                submenuTriggers.forEach(function(otherTrigger) {
                  const otherSubmenu = otherTrigger.closest('.nav-dd-submenu');
                  if (otherSubmenu && otherSubmenu !== submenu) {
                    otherSubmenu.classList.remove('is-open');
                    otherTrigger.setAttribute('aria-expanded', 'false');
                  }
                });
                
                if (isOpen) {
                  submenu.classList.remove('is-open');
                  trigger.setAttribute('aria-expanded', 'false');
                } else {
                  submenu.classList.add('is-open');
                  trigger.setAttribute('aria-expanded', 'true');
                }
              }
              
              trigger.addEventListener('click', toggleSubmenu);
              trigger.addEventListener('touchend', function(e) {
                e.preventDefault();
                toggleSubmenu(e);
              });
            });
          }
          
          document.addEventListener('click', function(e) {
            if (!e.target.closest('.nav-dd')) {
              allDropdowns.forEach(function(dropdown) {
                dropdown.classList.remove('open');
                const trigger = dropdown.querySelector('.nav-dd-trigger');
                if (trigger) {
                  trigger.setAttribute('aria-expanded', 'false');
                }
              });
            }
          });
        });
      })();
    </script>
  </head>
  <body<?php if (isset($noScroll) && $noScroll): ?> style="overflow: hidden; height: 100vh;"<?php endif; ?>>
    <header class="topbar">
      <div class="container">
        <div class="topbar-inner">
          <a class="brand brand-dxbinder" href="<?= $isDxBinderPath ? 'https://domix.dev' : 'https://domix.dev' ?>" aria-label="Domix.Dev">
            <img src="/main/assets/images/dxbanner.png" alt="Domix.Dev" class="brand-banner" />
            <div class="brand-info">
              <span class="brand-name"></span>
                <?php
                $brandText = 'Dashboard';

                if (str_contains($_SERVER['REQUEST_URI'], '/dxbinder')) {
                    $brandText = 'dxBinder';
                } elseif (str_contains($_SERVER['REQUEST_URI'], '/dxbots')) {
                    $brandText = 'dxBots';
                }
                ?>

                <span class="brand-sub"><?= $brandText ?></span>
            </div>
          </a>
          <button class="mobile-menu-toggle" type="button" aria-label="Menü öffnen" aria-expanded="false">
            <span class="mobile-menu-icon">
              <span></span>
              <span></span>
              <span></span>
            </span>
          </button>
          <button class="mobile-menu-close" type="button" aria-label="Menü schließen" style="display: none;">
            <svg viewBox="0 0 24 24" fill="none" width="24" height="24">
              <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
          <nav class="nav" aria-label="Navigation">
            <?php if ($showDxBotsUserMenu): ?>
              <?php
                $botsNavCfg = [];
                try {
                  $botsNavCfg = require __DIR__ . '/../config/dxbots.php';
                } catch (Throwable $e) {
                  $botsNavCfg = [];
                }
                $botsNavItems = is_array($botsNavCfg) && isset($botsNavCfg['nav']['items']) && is_array($botsNavCfg['nav']['items']) ? $botsNavCfg['nav']['items'] : [];

                foreach ($botsNavItems as $bit) {
                  if (!is_array($bit)) continue;
                  $bLabel = (string)($bit['label'] ?? '');
                  $bHref = (string)($bit['href'] ?? '#');
                  $bIcon = (string)($bit['icon'] ?? '');
                  if ($bLabel === '') continue;
                  ?>
                  <a href="<?= htmlspecialchars($bHref, ENT_QUOTES, 'UTF-8') ?>">
                    <span class="nav-icon" aria-hidden="true"><?php if ($bIcon !== ''): ?><i class="<?= htmlspecialchars($bIcon, ENT_QUOTES, 'UTF-8') ?>"></i><?php endif; ?></span>
                    <span><?= htmlspecialchars($bLabel, ENT_QUOTES, 'UTF-8') ?></span>
                  </a>
                  <?php
                }

                if ($showDxBotsUserMenu && isset($shBots['discord_id']) && $shBots['discord_id'] === '647563895447355414') {
                  ?>
                  <a href="/main/dxbots/acp/overview">
                    <span class="nav-icon" aria-hidden="true"><i class="fas fa-shield"></i></span>
                    <span>ACP</span>
                  </a>
                  <?php
                }
              ?>
            <?php elseif ($showDxBinderUserMenu): ?>
              <?php
                $navCfg = [];
                try {
                  $navCfg = require __DIR__ . '/../config/dxbinder.php';
                } catch (Throwable $e) {
                  $navCfg = [];
                }

                $fractionId = (int)($sh['fraction'] ?? 0);
                $navItems = is_array($navCfg) && isset($navCfg['nav']['items']) && is_array($navCfg['nav']['items']) ? $navCfg['nav']['items'] : [];

                $allow = function (array $it) use ($rangNum, $fractionId): bool {
                  $min = (int)($it['min_rang'] ?? 0);
                  if ($rangNum < $min) return false;
                  $fractions = $it['fractions'] ?? [];
                  if (is_array($fractions) && count($fractions) > 0) {
                    $ok = false;
                    foreach ($fractions as $f) {
                      if ((int)$f === $fractionId) { $ok = true; break; }
                    }
                    if (!$ok) return false;
                  }
                  return true;
                };

                foreach ($navItems as $it) {
                  if (!is_array($it)) continue;
                  if (!$allow($it)) continue;
                  $type = (string)($it['type'] ?? 'link');
                  $label = (string)($it['label'] ?? '');
                  $href = (string)($it['href'] ?? '#');
                  $icon = (string)($it['icon'] ?? '');
                  if ($label === '') continue;

                  if ($type === 'dropdown') {
                    $sub = isset($it['items']) && is_array($it['items']) ? $it['items'] : [];
                    if ($label === 'Developer' && isset($it['items']) && $it['items'] === 'dev_items') {
                      $sub = [];
                      $fractions = is_array($navCfg) && isset($navCfg['fractions']) && is_array($navCfg['fractions']) ? $navCfg['fractions'] : [];
                      $fractionIcons = [
                        1 => 'fas fa-shield-halved',
                        2 => 'fas fa-gavel',
                        3 => 'fas fa-heart-pulse',
                        4 => 'fas fa-fire',
                        5 => 'fas fa-newspaper',
                        6 => 'fas fa-building',
                        7 => 'fas fa-bolt',
                        100 => 'fas fa-user',
                      ];
                      foreach ($fractions as $fid => $fcfg) {
                        if (!is_array($fcfg) || !isset($fcfg['name'])) continue;
                        $fName = (string)$fcfg['name'];
                        $fIcon = $fractionIcons[$fid] ?? 'fas fa-users';
                        $hasSubFractions = (bool)($fcfg['has_sub_fractions'] ?? false);
                        
                        if ($fid === 1 && $hasSubFractions && isset($fcfg['sub_fractions']) && is_array($fcfg['sub_fractions'])) {
                          foreach ($fcfg['sub_fractions'] as $subFrac) {
                            $subFracName = (string)$subFrac;
                            $sub[] = [
                              'type' => 'submenu',
                              'label' => $subFracName,
                              'icon' => $fIcon,
                              'fraction_id' => $fid,
                              'fraction_name' => $subFracName,
                              'items' => [
                                ['type' => 'link', 'label' => 'Whitelist', 'href' => '/main/dxbinder/admin/whitelist?dev=1&fraction=1&fraction_name=' . urlencode($subFracName), 'icon' => 'fas fa-users', 'min_rang' => 12, 'fractions' => []],
                                ['type' => 'link', 'label' => 'Logins', 'href' => '/main/dxbinder/logs?dev=1&fraction=1&fraction_name=' . urlencode($subFracName) . '&log=logins', 'icon' => 'fas fa-sign-in-alt', 'min_rang' => 12, 'fractions' => []],
                                ['type' => 'link', 'label' => 'Zugang erstellt', 'href' => '/main/dxbinder/logs?dev=1&fraction=1&fraction_name=' . urlencode($subFracName) . '&log=zugang-erstellt', 'icon' => 'fas fa-user-plus', 'min_rang' => 12, 'fractions' => []],
                                ['type' => 'link', 'label' => 'Zugang bearbeitet', 'href' => '/main/dxbinder/logs?dev=1&fraction=1&fraction_name=' . urlencode($subFracName) . '&log=zugang-bearbeitet', 'icon' => 'fas fa-user-edit', 'min_rang' => 12, 'fractions' => []],
                                ['type' => 'link', 'label' => 'Zugang entfernt', 'href' => '/main/dxbinder/logs?dev=1&fraction=1&fraction_name=' . urlencode($subFracName) . '&log=zugang-entfernt', 'icon' => 'fas fa-user-times', 'min_rang' => 12, 'fractions' => []],
                                ['type' => 'link', 'label' => 'Statistiken', 'href' => '/main/dxbinder/logs?dev=1&fraction=1&fraction_name=' . urlencode($subFracName) . '&log=statistiken', 'icon' => 'fas fa-chart-bar', 'min_rang' => 12, 'fractions' => []],
                                ['type' => 'link', 'label' => 'Sonstiges', 'href' => '/main/dxbinder/logs?dev=1&fraction=1&fraction_name=' . urlencode($subFracName) . '&log=sonstiges', 'icon' => 'fas fa-ellipsis', 'min_rang' => 12, 'fractions' => []],
                              ],
                            ];
                          }
                        } else {
                          $sub[] = [
                            'type' => 'submenu',
                            'label' => $fName,
                            'icon' => $fIcon,
                            'fraction_id' => $fid,
                            'items' => [
                              ['type' => 'link', 'label' => 'Whitelist', 'href' => '/main/dxbinder/admin/whitelist?dev=1&fraction=' . $fid, 'icon' => 'fas fa-users', 'min_rang' => 12, 'fractions' => []],
                              ['type' => 'link', 'label' => 'Logins', 'href' => '/main/dxbinder/logs?dev=1&fraction=' . $fid . '&log=logins', 'icon' => 'fas fa-sign-in-alt', 'min_rang' => 12, 'fractions' => []],
                              ['type' => 'link', 'label' => 'Zugang erstellt', 'href' => '/main/dxbinder/logs?dev=1&fraction=' . $fid . '&log=zugang-erstellt', 'icon' => 'fas fa-user-plus', 'min_rang' => 12, 'fractions' => []],
                              ['type' => 'link', 'label' => 'Zugang bearbeitet', 'href' => '/main/dxbinder/logs?dev=1&fraction=' . $fid . '&log=zugang-bearbeitet', 'icon' => 'fas fa-user-edit', 'min_rang' => 12, 'fractions' => []],
                              ['type' => 'link', 'label' => 'Zugang entfernt', 'href' => '/main/dxbinder/logs?dev=1&fraction=' . $fid . '&log=zugang-entfernt', 'icon' => 'fas fa-user-times', 'min_rang' => 12, 'fractions' => []],
                              ['type' => 'link', 'label' => 'Statistiken', 'href' => '/main/dxbinder/logs?dev=1&fraction=' . $fid . '&log=statistiken', 'icon' => 'fas fa-chart-bar', 'min_rang' => 12, 'fractions' => []],
                              ['type' => 'link', 'label' => 'Sonstiges', 'href' => '/main/dxbinder/logs?dev=1&fraction=' . $fid . '&log=sonstiges', 'icon' => 'fas fa-ellipsis', 'min_rang' => 12, 'fractions' => []],
                            ],
                          ];
                        }
                      }
                    }
                    $subOut = [];
                    foreach ($sub as $s) {
                      if (!is_array($s)) continue;
                      $sType = (string)($s['type'] ?? 'link');
                      if ($sType === 'submenu') {
                        $sLabel = (string)($s['label'] ?? '');
                        $sIcon = (string)($s['icon'] ?? '');
                        $sItems = isset($s['items']) && is_array($s['items']) ? $s['items'] : [];
                        $sSubOut = [];
                        foreach ($sItems as $ss) {
                          if (!is_array($ss)) continue;
                          if (!$allow($ss)) continue;
                          $ssLabel = (string)($ss['label'] ?? '');
                          $ssHref = (string)($ss['href'] ?? '#');
                          $ssIcon = (string)($ss['icon'] ?? '');
                          if ($ssLabel === '') continue;
                          $sSubOut[] = ['type' => 'link', 'label' => $ssLabel, 'href' => $ssHref, 'icon' => $ssIcon];
                        }
                        if ($sLabel !== '' && count($sSubOut) > 0) {
                          $subOut[] = ['type' => 'submenu', 'label' => $sLabel, 'icon' => $sIcon, 'fraction_id' => (int)($s['fraction_id'] ?? 0), 'fraction_name' => (string)($s['fraction_name'] ?? ''), 'items' => $sSubOut];
                        }
                        continue;
                      }
                      if ($sType === 'label') {
                        $sLabel = (string)($s['label'] ?? '');
                        if ($sLabel !== '') {
                          $subOut[] = ['type' => 'label', 'label' => $sLabel];
                        }
                        continue;
                      }
                      if (!$allow($s)) continue;
                      $sLabel = (string)($s['label'] ?? '');
                      $sHref = (string)($s['href'] ?? '#');
                      $sIcon = (string)($s['icon'] ?? '');
                      if ($sLabel === '') continue;
                      $subOut[] = ['type' => 'link', 'label' => $sLabel, 'href' => $sHref, 'icon' => $sIcon];
                    }
                    if (count($subOut) === 0) continue;
                    ?>
                    <div class="nav-dd<?= $label === 'Developer' ? ' nav-dd-dev' : '' ?>">
                      <button class="nav-dd-trigger" type="button" aria-haspopup="true" aria-expanded="false">
                        <span class="nav-icon" aria-hidden="true"><?php if ($icon !== ''): ?><i class="<?= htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') ?>"></i><?php endif; ?></span>
                        <span><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></span>
                        <span class="nav-caret" aria-hidden="true">
                          <svg viewBox="0 0 24 24" fill="none">
                            <path d="M7 10l5 5 5-5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                          </svg>
                        </span>
                      </button>
                      <div class="nav-dd-menu" role="menu" aria-label="<?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?>">
                        <?php foreach ($subOut as $s): ?>
                          <?php if (($s['type'] ?? 'link') === 'submenu'): ?>
                            <div class="nav-dd-submenu" data-fraction-id="<?= (int)($s['fraction_id'] ?? 0) ?>" data-fraction-name="<?= htmlspecialchars($s['fraction_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>">
                              <button class="nav-dd-submenu-trigger" type="button" aria-expanded="false">
                                <span>
                                  <?php if (($s['icon'] ?? '') !== ''): ?><i class="<?= htmlspecialchars($s['icon'], ENT_QUOTES, 'UTF-8') ?>"></i><?php endif; ?>
                                  <span><?= htmlspecialchars($s['label'], ENT_QUOTES, 'UTF-8') ?></span>
                                </span>
                                <span class="nav-dd-submenu-caret" aria-hidden="true">
                                  <svg viewBox="0 0 24 24" fill="none">
                                    <path d="M7 10l5 5 5-5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                                  </svg>
                                </span>
                              </button>
                              <div class="nav-dd-submenu-items">
                                <?php foreach ($s['items'] as $ss): ?>
                                  <?php
                                  $ssHref = (string)($ss['href'] ?? '#');
                                  $isExternal = strpos($ssHref, 'http://') === 0 || strpos($ssHref, 'https://') === 0;
                                  $targetAttr = $isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
                                  ?>
                                  <a class="nav-dd-item" href="<?= htmlspecialchars($ssHref, ENT_QUOTES, 'UTF-8') ?>" role="menuitem"<?= $targetAttr ?>>
                                    <?php if (($ss['icon'] ?? '') !== ''): ?><i class="<?= htmlspecialchars($ss['icon'], ENT_QUOTES, 'UTF-8') ?>"></i><?php endif; ?>
                                    <span><?= htmlspecialchars($ss['label'], ENT_QUOTES, 'UTF-8') ?></span>
                                  </a>
                                <?php endforeach; ?>
                              </div>
                            </div>
                          <?php elseif (($s['type'] ?? 'link') === 'label'): ?>
                            <div class="nav-dd-label"><?= htmlspecialchars($s['label'], ENT_QUOTES, 'UTF-8') ?></div>
                          <?php else: ?>
                            <?php
                            $sHref = (string)($s['href'] ?? '#');
                            $isExternal = strpos($sHref, 'http://') === 0 || strpos($sHref, 'https://') === 0;
                            $targetAttr = $isExternal ? ' target="_blank" rel="noopener noreferrer"' : '';
                            ?>
                            <a class="nav-dd-item" href="<?= htmlspecialchars($sHref, ENT_QUOTES, 'UTF-8') ?>" role="menuitem"<?= $targetAttr ?>>
                              <?php if (($s['icon'] ?? '') !== ''): ?><i class="<?= htmlspecialchars($s['icon'], ENT_QUOTES, 'UTF-8') ?>"></i><?php endif; ?>
                              <span><?= htmlspecialchars($s['label'], ENT_QUOTES, 'UTF-8') ?></span>
                            </a>
                          <?php endif; ?>
                        <?php endforeach; ?>
                      </div>
                    </div>
                    <?php
                  } else {
                    ?>
                    <a href="<?= htmlspecialchars($href, ENT_QUOTES, 'UTF-8') ?>">
                      <span class="nav-icon" aria-hidden="true"><?php if ($icon !== ''): ?><i class="<?= htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') ?>"></i><?php endif; ?></span>
                      <span><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></span>
                    </a>
                    <?php
                  }
                }
              ?>
            <?php else: ?>
              <a href="https://domix.dev">
                <span class="nav-icon" aria-hidden="true">
                  <svg viewBox="0 0 24 24" fill="none">
                    <path d="M10.5 20h3V14h4v6h3V10.2L12 3 3.5 10.2V20h3v-6h4v6Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
                  </svg>
                </span>
                <span>Startseite</span>
              </a>
              <div class="nav-dd">
                <a class="nav-dd-trigger" href="/main/projekte" aria-haspopup="true" aria-expanded="false">
                  <span class="nav-icon" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none">
                      <path d="M7 7h10v10H7V7Z" stroke="currentColor" stroke-width="1.6" />
                      <path d="M4 10V6a2 2 0 0 1 2-2h4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
                      <path d="M20 14v4a2 2 0 0 1-2 2h-4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
                    </svg>
                  </span>
                  <span>Projekte</span>
                  <span class="nav-caret" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none">
                      <path d="M7 10l5 5 5-5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </span>
                </a>
                <div class="nav-dd-menu" role="menu" aria-label="Projekte">
                  <a class="nav-dd-item" href="/main/dxbinder" role="menuitem"><i class="fa-solid fa-d"></i><span>dxBinder</span></a>
                  <a class="nav-dd-item" href="/main/dxbots/login" role="menuitem"><i class="fab fa-discord"></i><span>dxBots</span></a>
                </div>
              </div>
              <div class="nav-dd">
                <a class="nav-dd-trigger" href="/main/tools" aria-haspopup="true" aria-expanded="false">
                  <span class="nav-icon" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none">
                      <path d="M14.5 6.5a4.5 4.5 0 0 0-6 6L4 17v3h3l4.5-4.5a4.5 4.5 0 0 0 6-6Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
                    </svg>
                  </span>
                  <span>Tools</span>
                  <span class="nav-caret" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none">
                      <path d="M7 10l5 5 5-5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </span>
                </a>
                <div class="nav-dd-menu" role="menu" aria-label="Tools">
                  <div class="nav-dd-label">Platzhalter</div>
                  <a class="nav-dd-item" href="/main/tools" role="menuitem"><i class="fas fa-wand-magic-sparkles"></i><span>Tool #1</span></a>
                  <a class="nav-dd-item" href="/main/tools" role="menuitem"><i class="fas fa-screwdriver-wrench"></i><span>Tool #2</span></a>
                  <a class="nav-dd-item" href="/main/tools" role="menuitem"><i class="fas fa-bolt"></i><span>Tool #3</span></a>
                </div>
              </div>
              <a href="/main/docs">
                <span class="nav-icon" aria-hidden="true">
                  <svg viewBox="0 0 24 24" fill="none">
                    <path d="M7 4h8l2 2v14H7V4Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/>
                    <path d="M9 10h6M9 13h6M9 16h5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
                  </svg>
                </span>
                <span>Docs</span>
              </a>

              <a href="/main/status">
                <span class="nav-icon" aria-hidden="true">
                  <svg viewBox="0 0 24 24" fill="none">
                    <path d="M6 20V10M12 20V4M18 20v-7" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
                  </svg>
                </span>
                <span>Status</span>
              </a>

              <div class="nav-dd">

                <div class="nav-dd-menu" role="menu" aria-label="Status">
                  <div class="nav-dd-label">Platzhalter</div>
                  <a class="nav-dd-item" href="/main/status" role="menuitem"><i class="fas fa-signal"></i><span>Service Status</span></a>
                  <a class="nav-dd-item" href="/main/status" role="menuitem"><i class="fas fa-list"></i><span>Changelog</span></a>
                </div>
              </div>
            <?php endif; ?>
          </nav>

          <div class="actions">
            <?php if (!$isDxBinderPath && !$isDxBotsPath): ?>
            <a href="/main/support" class="support-btn">
              <i class="fab fa-discord"></i>
              <span>Support</span>
            </a>
            <?php endif; ?>
            <?php if ($showDxBotsUserMenu): ?>
              <?php
                $botsDiscordId = (string)($shBots['discord_id'] ?? '');
                $botsAvatar = $shBots['avatar'] ?? null;
                $botsGlobalName = (string)($shBots['global_name'] ?? $shBots['username'] ?? '');
                $botsUsername = (string)($shBots['username'] ?? '');
                if (function_exists('dxbots_get_avatar_url')) {
                  $botsAvatarUrl = dxbots_get_avatar_url($botsDiscordId, $botsAvatar);
                } else {
                  $botsAvatarUrl = $botsAvatar ? "https://cdn.discordapp.com/avatars/{$botsDiscordId}/{$botsAvatar}.png" : "https://cdn.discordapp.com/embed/avatars/0.png";
                }
              ?>
              <?php $botsEmail = (string)($shBots['email'] ?? ''); ?>
              <div class="nav-dd user-dd">
                <button class="nav-dd-trigger user-trigger" type="button" aria-haspopup="true" aria-expanded="false" aria-label="Benutzermenü">
                  <span class="avatar" aria-hidden="true">
                    <img src="<?= htmlspecialchars($botsAvatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="" style="border-radius: 50%;" />
                  </span>
                  <span class="user-name"><?= htmlspecialchars($botsGlobalName, ENT_QUOTES, 'UTF-8') ?></span>
                  <span class="nav-caret" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none">
                      <path d="M7 10l5 5 5-5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </span>
                </button>

                <div class="nav-dd-menu user-menu" role="menu" aria-label="Benutzer">
                  <div class="user-head">
                    <div class="user-label"> Eingeloggt als</div>
                    <div class="user-displayname">ㅤ<?= htmlspecialchars($botsGlobalName, ENT_QUOTES, 'UTF-8') ?></div>
                    <?php if ($botsEmail !== ''): ?>
                      <div class="user-email"><?= htmlspecialchars($botsEmail, ENT_QUOTES, 'UTF-8') ?></div>
                    <?php endif; ?>
                  </div>
                  <div class="user-divider"></div>
                  <a class="nav-dd-item" href="/main/dxbots/logout" role="menuitem">
                    <i class="fa-solid fa-right-from-bracket"></i><span>Ausloggen</span>
                  </a>
                </div>
              </div>
            <?php elseif ($showDxBinderUserMenu): ?>
              <?php $isGuest = (int)($sh['fraction'] ?? 0) === 100; ?>
              <div class="nav-dd user-dd">
                <button class="nav-dd-trigger user-trigger" type="button" aria-haspopup="true" aria-expanded="false" aria-label="Benutzermenü">
                  <span class="avatar" aria-hidden="true">
                    <img src="<?= htmlspecialchars((string)$avatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="" />
                  </span>
                  <span class="nav-caret" aria-hidden="true">
                    <svg viewBox="0 0 24 24" fill="none">
                      <path d="M7 10l5 5 5-5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </span>
                </button>

                <div class="nav-dd-menu user-menu" role="menu" aria-label="Benutzer">
                  <?php if ($isGuest): ?>
                    <div class="user-head">
                      <div class="user-hello">Nicht eingeloggt</div>
                      <div class="user-sub">Du bist als Gast unterwegs</div>
                    </div>

                    <a class="nav-dd-item" href="<?= htmlspecialchars($logoutUrl, ENT_QUOTES, 'UTF-8') ?>" role="menuitem">
                      <i class="fa-solid fa-right-from-bracket"></i><span>Session beenden</span>
                    </a>
                  <?php else: ?>
                    <div class="user-head">
                      <div class="user-hello">Willkommen, <b><?= htmlspecialchars($userName, ENT_QUOTES, 'UTF-8') ?></b></div>
                      <div class="user-sub">Fraktion:
                        <?= htmlspecialchars($fractionLabel, ENT_QUOTES, 'UTF-8') ?> (Rang: <?= htmlspecialchars($rangLabel, ENT_QUOTES, 'UTF-8') ?>)
                      </div>
                      <div class="user-sub">Administrator: <?= htmlspecialchars($adminValue, ENT_QUOTES, 'UTF-8') ?></div>
                    </div>

                    <a class="nav-dd-item" href="/main/dxbinder/settings" role="menuitem">
                      <i class="fa-solid fa-gear"></i><span>Einstellungen</span>
                    </a>

                    <div class="user-divider"></div>

                    <a class="nav-dd-item" href="<?= htmlspecialchars($logoutUrl, ENT_QUOTES, 'UTF-8') ?>" role="menuitem">
                      <i class="fa-solid fa-right-from-bracket"></i><span>Logout</span>
                    </a>
                  <?php endif; ?>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </header>


