<header class="w-full p-2 fixed top-0 left-0 right-0 z-30">
  <div class="max-w-7xl mx-auto flex items-center justify-between px-3">
    <div class="flex items-center gap-4">
      <!-- hamburger for mobile to toggle sidebar/drawer -->
      <button id="drawerToggle" class="md:hidden inline-flex items-center p-2 rounded-md text-white hover:bg-white/5 focus:outline-none" aria-label="Abrir menú">
        <svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
        </svg>
      </button>
      <!-- small logo + name -->
      <a href="/" class="flex items-center gap-2 mr-2">
        <div class="w-7 h-7">
                   <img src="/assets/images/logo-amayo.svg" alt="logo" class="mx-auto mb-4 rounded-full" />
        </div>
        <span class="text-white font-semibold hidden sm:inline"><%= appName %></span>
      </a>
  <!-- mini guild selector compact -->
  <div class="block">
        <div class="relative inline-block">
          <button id="miniGuildBtn" class="px-2 py-0.5 rounded-full bg-white/5 text-white text-sm flex items-center gap-2" aria-expanded="false" aria-controls="miniGuildList">
            <span id="miniGuildName" class="text-sm"><%= selectedGuildName || 'Seleccionar servidor' %></span>
            <svg class="w-3 h-3 text-white/80" viewBox="0 0 20 20" fill="none"><path d="M6 8l4 4 4-4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
          </button>
          <div id="miniGuildList" class="origin-top-left absolute top-full left-0 mt-2 w-56 bg-white/80 backdrop-blur-md rounded-lg p-1 hidden transition-transform duration-150 z-50" style="max-height:18rem; overflow:auto; background-color: rgba(12,15,18,0.92);">
      <% if (guilds && guilds.length) { %>
        <% const withBot = guilds.filter(g=> g.botInGuild === true); const withoutBot = guilds.filter(g=> g.botInGuild !== true); %>
                <% withBot.forEach(g => { %>
                  <div onclick="location.href='/dashboard/<%= g.id %>/overview'" role="button" tabindex="0" class="p-1 rounded-md hover:bg-white/5 cursor-pointer text-white guild-item flex items-center gap-3" data-id="<%= g.id %>" data-bot="1" data-invite="https://discord.com/oauth2/authorize?client_id=991062751633883136&permissions=2416176272&integration_type=0&scope=bot&guild_id=<%= g.id %>">
                    <% if (g.icon) { %>
                      <img src="https://cdn.discordapp.com/icons/<%= g.id %>/<%= g.icon %>.webp" class="w-5 h-5 rounded-full" alt="icon">
                    <% } else { %>
                      <div class="w-5 h-5 rounded-full bg-white/8 flex items-center justify-center text-xs text-white">S</div>
                    <% } %>
                    <div class="flex-1 text-sm truncate pl-1">
                      <%= g.name %>
                      <% if (g.botInGuild === true) { %>
                        <span class="ml-2 text-xs text-emerald-300">(Bot)</span>
                      <% } else { %>
                        <span class="ml-2 text-xs text-sky-300">(Invitar)</span>
                      <% } %>
                    </div>
                    <!-- invite button removed from inline list; rows without bot are dimmed and clicking them opens the invite -->
                  </div>
                <% }) %>
                <% if (withoutBot && withoutBot.length) { %>
                  <div class="border-t border-white/6 my-1"></div>
                  <% withoutBot.forEach(g => { %>
                    <div onclick="window.open('https://discord.com/oauth2/authorize?client_id=991062751633883136&permissions=2416176272&integration_type=0&scope=bot&guild_id=<%= g.id %>', '_blank', 'noopener')" role="button" tabindex="0" class="p-1 rounded-md hover:bg-white/5 cursor-pointer text-white guild-item flex items-center gap-3 opacity-60" data-id="<%= g.id %>" data-bot="0" data-invite="https://discord.com/oauth2/authorize?client_id=991062751633883136&permissions=2416176272&integration_type=0&scope=bot&guild_id=<%= g.id %>">
                      <% if (g.icon) { %>
                        <img src="https://cdn.discordapp.com/icons/<%= g.id %>/<%= g.icon %>.webp" class="w-5 h-5 rounded-full" alt="icon">
                      <% } else { %>
                        <div class="w-5 h-5 rounded-full bg-white/8 flex items-center justify-center text-xs text-white">S</div>
                      <% } %>
                      <div class="flex-1 text-sm truncate pl-1"><%= g.name %></div>
                    </div>
                  <% }) %>
                <% } %>
          <% } else { %>
            <div class="p-2 text-slate-300">No servers</div>
          <% } %>
        </div>
      </div>
    </div>
    <div class="flex items-center gap-4">
      <% if (user) { %>
        <div class="relative">
          <button id="userBtn" class="flex items-center gap-2 px-2 py-1 rounded-full hover:bg-white/5 focus:outline-none" aria-expanded="false">
            <% if (user.id && user.avatar) { %>
              <img src="https://cdn.discordapp.com/avatars/<%= user.id %>/<%= user.avatar %>.png" class="w-8 h-8 rounded-full" alt="avatar">
            <% } else { %>
              <img src="/assets/images/snap1.svg" class="w-8 h-8 rounded-full" alt="avatar">
            <% } %>
            <svg class="w-3 h-3 text-white/80 ml-1" viewBox="0 0 20 20" fill="none"><path d="M6 8l4 4 4-4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
          </button>
          <div id="userMenu" class="origin-top-right absolute right-0 mt-2 w-36 bg-white/80 backdrop-blur-md rounded-md p-2 hidden z-50" style="background-color: rgba(12,15,18,0.9);">
            <a href="/auth/logout" class="block px-3 py-2 text-sm text-rose-300 hover:bg-white/5 rounded">Log out</a>
          </div>
        </div>
        <% } else { %>
          <a href="/auth/discord" class="text-sm text-white/70 px-3 py-2 rounded-md hover:bg-white/5">Entrar</a>
        <% } %>
    </div>
  </div>
</header>

<div class="hidden md:block" style="height:56px"></div>

<script>
  (function(){
    const btn = document.getElementById('miniGuildBtn');
    const list = document.getElementById('miniGuildList');
    const userBtn = document.getElementById('userBtn');
    const userMenu = document.getElementById('userMenu');
    const cardUserMenu = document.getElementById('cardUserMenu');
    const mobileGuildModal = document.getElementById('mobileGuildModal');
    const mobileUserSheet = document.getElementById('mobileUserSheet');

    function closeAllMenus() {
      try {
        if (list) list.classList.add('hidden');
        if (userMenu) userMenu.classList.add('hidden');
        if (cardUserMenu) cardUserMenu.classList.add('hidden');
        if (mobileGuildModal) mobileGuildModal.classList.add('hidden');
        if (mobileUserSheet) mobileUserSheet.classList.add('hidden');
        if (btn) btn.setAttribute('aria-expanded','false');
        if (userBtn) userBtn.setAttribute('aria-expanded','false');
      } catch(e){}
    }
    function openDropdown(el, container) {
      if (!el || !container) return;
      container.classList.remove('hidden');
      // animate in
      requestAnimationFrame(()=>{
        container.classList.remove('scale-95','opacity-0','pointer-events-none');
        container.classList.add('scale-100','opacity-100');
        el.setAttribute('aria-expanded','true');
      });
    }
    function closeDropdown(el, container) {
      if (!el || !container) return;
      container.classList.add('scale-95','opacity-0');
      container.classList.remove('scale-100','opacity-100');
      el.setAttribute('aria-expanded','false');
      // after animation, hide to prevent tab focus
      setTimeout(()=> container.classList.add('hidden','pointer-events-none'), 180);
    }
      if (btn && list) {
      // ensure the dropdown itself is scrollable when many guilds exist
      list.style.maxHeight = '20rem';
      list.style.overflowY = 'auto';
      btn.addEventListener('click', (e)=>{
        e.stopPropagation();
        const expanded = btn.getAttribute('aria-expanded') === 'true';
        if (expanded) closeDropdown(btn, list); else {
          // close other menus first
          closeAllMenus();
          openDropdown(btn, list);
          // runtime-check: for items that were not marked as having the bot, try fetching roles
          (async function refreshMissingBotFlags(){
            try{
              const items = Array.from(list.querySelectorAll('.guild-item')) || [];
              for(const el of items){
                try{
                  const botAttr = el.getAttribute('data-bot');
                  if(botAttr === '1') continue;
                  const gid = el.getAttribute('data-id');
                  if(!gid) continue;
                  const res = await fetch(`/api/dashboard/${encodeURIComponent(gid)}/roles`, { method: 'GET', headers: { 'Accept': 'application/json' } });
                  if(res && res.ok){
                    // update element to show the bot is present
                    el.setAttribute('data-bot','1');
                    el.classList.remove('opacity-60');
                    const infoSpan = el.querySelector('.text-xs');
                    if(infoSpan) infoSpan.textContent = '(Bot)';
                    const nameDiv = el.querySelector('.flex-1');
                    if(nameDiv){
                      // ensure (Bot) marker exists after name
                      let marker = nameDiv.querySelector('.bot-marker');
                      if(!marker){
                        marker = document.createElement('span');
                        marker.className = 'ml-2 text-xs text-emerald-300 bot-marker';
                        marker.textContent = '(Bot)';
                        nameDiv.appendChild(marker);
                      }
                    }
                  }
                }catch(e){ /* ignore per-item errors */ }
              }
            }catch(e){ /* ignore */ }
          })();
        }
      });
      // Use event delegation on the list so clicks on children are handled reliably
      list.addEventListener('click', (e)=>{
        let el = e.target;
        while (el && !el.dataset?.id && el !== list) el = el.parentElement;
        if (!el || el === list) return;
        const id = el.getAttribute('data-id');
        const bot = el.getAttribute('data-bot');
        const invite = el.getAttribute('data-invite');
        const isDim = el.classList && el.classList.contains('opacity-60');
        if (bot === '1') {
          closeDropdown(btn, list);
          window.location.href = `/dashboard/${id}/overview`;
          return;
        }
        // if not explicitly '1', treat as missing and open invite if available
        if ((bot === '0' || isDim) && invite) {
          window.open(invite, '_blank', 'noopener');
          closeDropdown(btn, list);
          return;
        }
      });
    }
    if (userBtn && userMenu) {
      userBtn.addEventListener('click', (e)=>{
        e.stopPropagation();
        const expanded = userBtn.getAttribute('aria-expanded') === 'true';
        if (expanded) closeDropdown(userBtn, userMenu); else {
          // ensure other menus are closed
          closeAllMenus();
          openDropdown(userBtn, userMenu);
        }
      });
    }
    // close on outside click or Escape
    document.addEventListener('click', (e)=>{
      if (btn && list && !btn.contains(e.target) && !list.contains(e.target)) closeDropdown(btn, list);
      if (userBtn && userMenu && !userBtn.contains(e.target) && !userMenu.contains(e.target)) closeDropdown(userBtn, userMenu);
    });
    document.addEventListener('keydown', (e)=>{
      if (e.key === 'Escape') {
        if (btn && list) closeDropdown(btn, list);
        if (userBtn && userMenu) closeDropdown(userBtn, userMenu);
      }
    });
  })();
</script>

<script>
  // Bind the mobile CTA (if present) to open the mobile guild modal
  document.addEventListener('DOMContentLoaded', () => {
    const openBtn = document.getElementById('openMobileGuildList');
    const mobileGuildModal = document.getElementById('mobileGuildModal');
    if (openBtn && mobileGuildModal) {
      openBtn.addEventListener('click', (e) => {
        e.preventDefault();
        mobileGuildModal.classList.remove('hidden');
      });
    }
    // floating touch CTA logic
    const floatBtn = document.getElementById('floatingTouchGuildBtn');
    try {
      const isTouch = (navigator.maxTouchPoints && navigator.maxTouchPoints > 0) || ('ontouchstart' in window);
      const w = window.innerWidth || document.documentElement.clientWidth;
      const h = window.innerHeight || document.documentElement.clientHeight;
      const isSmallViewport = (h <= 800) || (w/h > 1.6);
      if (floatBtn && (isTouch || isSmallViewport)) {
        floatBtn.classList.remove('hidden');
        floatBtn.addEventListener('click', (e) => { e.preventDefault(); mobileGuildModal?.classList.remove('hidden'); });
      }
    } catch(e){}
  });
</script>

<!-- Mobile modals -->
<div id="mobileGuildModal" class="fixed inset-0 bg-black/60 hidden z-50">
  <div class="fixed inset-x-0 bottom-0 bg-[#1f2933] rounded-t-xl p-4 max-h-[80vh] overflow-auto" style="margin:0;">
    <div class="flex items-center justify-between mb-3">
      <h3 class="text-white font-medium">Servers</h3>
      <button id="mobileGuildClose" class="text-white/70">Cerrar</button>
    </div>
    <div id="mobileGuildList" class="space-y-2">
      <% if (guilds && guilds.length) { %>
        <% const withBot = guilds.filter(g=> g.botInGuild === true); const withoutBot = guilds.filter(g=> g.botInGuild !== true); %>
        <% withBot.forEach(g => { %>
          <div onclick="location.href='/dashboard/<%= g.id %>/overview'" role="button" tabindex="0" class="flex items-center gap-3 p-2 rounded-md hover:bg-white/5 cursor-pointer" data-id="<%= g.id %>" data-bot="1" data-invite="https://discord.com/oauth2/authorize?client_id=991062751633883136&permissions=2416176272&integration_type=0&scope=bot&guild_id=<%= g.id %>">
            <% if (g.icon) { %>
              <img src="https://cdn.discordapp.com/icons/<%= g.id %>/<%= g.icon %>.webp" class="w-8 h-8 rounded-full" alt="icon">
            <% } else { %>
              <div class="w-8 h-8 rounded-full bg-white/8"></div>
            <% } %>
                      <div class="text-white"><%= g.name %>
                        <% if (g.botInGuild === true) { %>
                          <span class="ml-2 text-xs text-emerald-300">(Bot)</span>
                        <% } else { %>
                          <span class="ml-2 text-xs text-sky-300">(Invitar)</span>
                        <% } %>
                      </div>
          </div>
        <% }) %>
        <% if (withoutBot && withoutBot.length) { %>
          <div class="border-t border-white/6 mt-2 pt-2"></div>
          <% withoutBot.forEach(g => { %>
            <div onclick="window.open('https://discord.com/oauth2/authorize?client_id=991062751633883136&permissions=2416176272&integration_type=0&scope=bot&guild_id=<%= g.id %>', '_blank', 'noopener')" role="button" tabindex="0" class="flex items-center gap-3 p-2 rounded-md hover:bg-white/5 cursor-pointer opacity-60" data-id="<%= g.id %>" data-bot="0" data-invite="https://discord.com/oauth2/authorize?client_id=991062751633883136&permissions=2416176272&integration_type=0&scope=bot&guild_id=<%= g.id %>">
              <% if (g.icon) { %>
                <img src="https://cdn.discordapp.com/icons/<%= g.id %>/<%= g.icon %>.webp" class="w-8 h-8 rounded-full" alt="icon">
              <% } else { %>
                <div class="w-8 h-8 rounded-full bg-white/8"></div>
              <% } %>
              <div class="text-white"><%= g.name %></div>
            </div>
          <% }) %>
        <% } %>
      <% } else { %>
        <div class="text-slate-300">No servers</div>
      <% } %>
    </div>
  </div>
</div>

<div id="mobileUserSheet" class="fixed inset-0 bg-black/60 hidden z-50">
  <div class="fixed inset-x-0 bottom-0 bg-[#1f2933] rounded-t-xl p-4 max-h-[80vh] overflow-auto">
  <h3 class="text-white font-medium mb-3">User settings</h3>
  <a href="/dashboard/select-guild" class="block py-2 text-white">Servers</a>
  <a href="/auth/logout" class="block py-2 text-rose-300">Log out</a>
  <div class="text-right mt-2"><button id="mobileUserClose" class="text-white/70">Cerrar</button></div>
  </div>
</div>

<script>
  (function(){
    const mobileGuildModal = document.getElementById('mobileGuildModal');
    const mobileGuildClose = document.getElementById('mobileGuildClose');
    const mobileUserSheet = document.getElementById('mobileUserSheet');
    const mobileUserClose = document.getElementById('mobileUserClose');
    // ensure modals live under document.body so fixed positioning is relative to viewport
    try {
      if (mobileGuildModal && mobileGuildModal.parentElement !== document.body) {
        document.body.appendChild(mobileGuildModal);
      }
      if (mobileUserSheet && mobileUserSheet.parentElement !== document.body) {
        document.body.appendChild(mobileUserSheet);
      }
      if (mobileGuildModal) mobileGuildModal.style.position = 'fixed';
      if (mobileUserSheet) mobileUserSheet.style.position = 'fixed';
    } catch(e){}
    function isMobile(){ return window.innerWidth < 768; }
    // override mini guild click on mobile
    const miniBtn = document.getElementById('miniGuildBtn');
    const miniList = document.getElementById('miniGuildList');
    if (miniBtn) {
      miniBtn.addEventListener('click', (e)=>{
        if (isMobile()) {
          e.stopPropagation();
          // close other menus before opening the mobile guild modal
          closeAllMenus();
          mobileGuildModal.classList.remove('hidden');
        }
      });
    }
    mobileGuildClose?.addEventListener('click', ()=> mobileGuildModal.classList.add('hidden'));
    mobileGuildModal?.addEventListener('click',(e)=>{ if (e.target === mobileGuildModal) mobileGuildModal.classList.add('hidden'); });
    // clicking mobile guild item
    document.getElementById('mobileGuildList')?.addEventListener('click', (e)=>{
      let el = e.target;
      while (el && !el.dataset?.id) el = el.parentElement;
      if (el && el.dataset && el.dataset.id) {
  const bot = el.getAttribute('data-bot');
  const invite = el.getAttribute('data-invite');
  const isDim = el.classList && el.classList.contains('opacity-60');
  if (bot === '1') { window.location.href = `/dashboard/${el.dataset.id}/overview`; return; }
  if ((bot === '0' || isDim) && invite) { window.open(invite, '_blank', 'noopener'); return; }
      }
    });

    // user menu mobile
    const userBtnMobile = document.getElementById('userBtn');
  if (userBtnMobile) userBtnMobile.addEventListener('click', (e)=>{ if (isMobile()) { e.stopPropagation(); closeAllMenus(); mobileUserSheet.classList.remove('hidden'); } });
    mobileUserClose?.addEventListener('click', ()=> mobileUserSheet.classList.add('hidden'));
    mobileUserSheet?.addEventListener('click',(e)=>{ if (e.target === mobileUserSheet) mobileUserSheet.classList.add('hidden'); });
  })();
</script>
