---
import Button from "@components/base/Button.astro";

const { links } = Astro.props;
---

<div
  id="menu-overlay"
  class="fixed inset-0 bg-black/60 backdrop-blur-sm z-[90] opacity-0 pointer-events-none transition-opacity duration-500"
  onclick="document.dispatchEvent(new CustomEvent('close-mobile-menu'))"
>
</div>

<!-- ИЗМЕНЕНИЕ: Ширина на всю ширину экрана -->
<aside
  id="mobile-menu"
  class="fixed inset-0 bg-[#151b26] z-[105] py-6 px-4 flex flex-col overflow-y-auto shadow-2xl"
>
  <div
    class="absolute inset-0 pointer-events-none opacity-5 bg-gradient-to-br from-white/5 to-transparent"
  >
  </div>

  <!-- Кнопка закрытия -->
  <button
    id="menu-close-btn"
    class="absolute top-4 right-4 w-10 h-10 rounded-full border border-white/20 flex items-center justify-center hover:bg-white/10 transition-colors z-50 cursor-pointer"
    aria-label="Закрыть меню"
    onclick="document.dispatchEvent(new CustomEvent('close-mobile-menu'))"
  >
    <svg
      class="w-6 h-6 text-white"
      fill="none"
      stroke="currentColor"
      viewBox="0 0 24 24"
    >
      <path
        stroke-linecap="round"
        stroke-linejoin="round"
        stroke-width="2"
        d="M6 18L18 6M6 6l12 12"
      />
    </svg>
  </button>

  <!-- Логотип -->
  <div class="mobile-link mb-10 mt-2 relative z-10 flex items-center justify-center">
    <span
      class="text-xl md:text-2xl font-black tracking-tighter text-white uppercase leading-none"
    >
      ADVOKAT<span class="text-[#bf9b58]">086</span>
    </span>
  </div>

  <!-- Навигация -->
  <nav class="relative z-10 flex flex-col items-center space-y-4 w-full flex-1">
    {
      links.map((link: any, index: number) =>
        link.children ? (
          <div
            class="mobile-link w-full flex flex-col items-center"
            style={`--delay: ${0.2 + index * 0.08}s`}
          >
            <button
              class={`mobile-submenu-toggle text-lg md:text-xl font-bold uppercase tracking-wide transition-colors text-center flex items-center gap-2 ${link.active ? "text-[#bf9b58]" : "text-white hover:text-[#bf9b58]"}`}
              data-index={index}
            >
              {link.name}
              <svg
                class="w-4 h-4 transition-transform duration-300 arrow-icon"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M19 9l-7 7-7-7"
                />
              </svg>
            </button>

            <div
              class="mobile-submenu hidden mt-3 w-full space-y-2 overflow-hidden"
              data-index={index}
            >
              {link.children.map((child: any) => (
                <a
                  href={child.href}
                  class="block text-center text-sm font-medium uppercase tracking-wide text-gray-300 hover:text-[#bf9b58] transition-colors py-1"
                  onclick="document.dispatchEvent(new CustomEvent('close-mobile-menu'))"
                >
                  <span class="mr-2">{child.icon}</span>
                  {child.name}
                </a>
              ))}
              <a
                href={link.href}
                class="block text-center text-xs font-bold uppercase tracking-wide text-[#bf9b58] hover:text-white transition-colors mt-2 py-1"
                onclick="document.dispatchEvent(new CustomEvent('close-mobile-menu'))"
              >
                Все услуги →
              </a>
            </div>
          </div>
        ) : (
          <a
            href={link.href}
            class="mobile-link text-lg md:text-xl font-bold uppercase tracking-wide transition-colors text-center"
            class:list={[
              link.active
                ? "text-[#bf9b58]"
                : "text-white hover:text-[#bf9b58]",
            ]}
            style={`--delay: ${0.2 + index * 0.08}s`}
            onclick="document.dispatchEvent(new CustomEvent('close-mobile-menu'))"
          >
            {link.name}
          </a>
        ),
      )
    }
  </nav>

  <!-- Авторизация - управляется через JS -->
  <div
    id="mobile-auth-block"
    class="mobile-link w-full mt-8 flex justify-center gap-6 relative z-10 hidden"
    style="--delay: 0.6s"
  >
    <a
      href="/profile"
      class="w-10 h-10 rounded-full bg-[#bf9b58]/20 border border-[#bf9b58]/50 flex items-center justify-center hover:bg-[#bf9b58]/30 transition-colors"
    >
      <svg
        class="w-5 h-5 text-[#bf9b58]"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
        />
      </svg>
    </a>
    <button
      id="mobile-logout-btn"
      class="w-10 h-10 rounded-full border border-red-500/30 flex items-center justify-center hover:bg-red-500/10 transition-colors"
    >
      <svg
        class="w-5 h-5 text-red-400"
        fill="none"
        stroke="currentColor"
        viewBox="0 0 24 24"
      >
        <path
          stroke-linecap="round"
          stroke-linejoin="round"
          stroke-width="2"
          d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
        />
      </svg>
    </button>
  </div>

  <!-- Нижний блок -->
  <div
    class="relative z-10 w-full mt-auto pt-6 mobile-link"
    style="--delay: 0.7s"
  >
    <div class="h-[1px] bg-white/10 w-full mb-4"></div>
    <div id="mobile-guest-block" class="flex justify-center hidden">
      <div class="flex flex-col items-center gap-1">
        <p class="text-xs font-bold text-[#bf9b58] uppercase tracking-[0.2em]">
          Срочная связь
        </p>
        <a
          href="tel:+79222538375"
          class="text-base font-bold text-white hover:text-[#bf9b58] transition-colors"
        >
          +7 (922) 253-83-75
        </a>
      </div>
    </div>
  </div>
</aside>

<style>
  #mobile-menu {
    transform: translateX(-100%);
    transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
  }
  :global(body.menu-open) #mobile-menu {
    transform: translateX(0);
  }
  :global(body.menu-open) #menu-overlay {
    opacity: 1;
    pointer-events: auto;
  }
  .mobile-link {
    opacity: 0;
    transform: translateY(20px);
    transition:
      opacity 0.4s ease-out,
      transform 0.4s ease-out;
    transition-delay: var(--delay);
  }
  :global(body.menu-open) .mobile-link {
    opacity: 1;
    transform: translateY(0);
  }
  .arrow-icon.rotated {
    transform: rotate(180deg);
  }
  #menu-close-btn {
    opacity: 0;
    transition: opacity 0.3s ease-out;
    transition-delay: 0.3s;
  }
  :global(body.menu-open) #menu-close-btn {
    opacity: 1;
  }
</style>

<script>
  const setupSubmenus = () => {
    const toggles = document.querySelectorAll(".mobile-submenu-toggle");
    toggles.forEach((toggle) => {
      toggle.addEventListener("click", (e) => {
        e.preventDefault();
        const index = toggle.getAttribute("data-index");
        const submenu = document.querySelector(
          `.mobile-submenu[data-index="${index}"]`,
        );
        const arrow = toggle.querySelector(".arrow-icon");

        if (submenu) {
          const isHidden = submenu.classList.contains("hidden");
          document
            .querySelectorAll(".mobile-submenu")
            .forEach((el) => el.classList.add("hidden"));
          document
            .querySelectorAll(".arrow-icon")
            .forEach((el) => el.classList.remove("rotated"));

          if (isHidden) {
            submenu.classList.remove("hidden");
            arrow?.classList.add("rotated");
          }
        }
      });
    });
  };

  const setupLogout = () => {
    const btn = document.getElementById("mobile-logout-btn");
    if (btn) {
      btn.classList.add("cursor-pointer");
      btn.addEventListener("click", async () => {
        console.log('[MobileMenu] Выход из системы');
        
        try {
          const response = await fetch('/api/auth/logout', {
            method: 'POST',
            credentials: 'include',
          });
          
          if (response.ok) {
            // Удаляем куку на клиенте
            document.cookie = 'pb_auth=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
            // Перенаправляем на главную
            window.location.href = '/';
          }
        } catch (error) {
          console.error('[MobileMenu] Ошибка при выходе:', error);
        }
      });
    }
  };
  
  // Проверка авторизации
  const checkAuth = async () => {
    const mobileAuthBlock = document.getElementById("mobile-auth-block");
    const mobileGuestBlock = document.getElementById("mobile-guest-block");
    
    if (!mobileAuthBlock || !mobileGuestBlock) return;
    
    try {
      const response = await fetch('/api/auth/me', {
        method: 'GET',
        credentials: 'include',
      });
      
      const data = await response.json();
      
      if (data.authenticated) {
        // Пользователь авторизован
        mobileAuthBlock.classList.remove("hidden");
        mobileAuthBlock.classList.add("flex");
        mobileGuestBlock.classList.add("hidden");
        mobileGuestBlock.classList.remove("flex");
      } else {
        // Пользователь не авторизован
        mobileAuthBlock.classList.add("hidden");
        mobileAuthBlock.classList.remove("flex");
        mobileGuestBlock.classList.remove("hidden");
        mobileGuestBlock.classList.add("flex");
      }
    } catch (error) {
      console.error('[MobileMenu] Ошибка проверки авторизации:', error);
    }
  };
  
  // Вызываем проверку авторизации
  checkAuth();

  setupSubmenus();
  setupLogout();
  document.addEventListener("astro:after-swap", () => {
    setupSubmenus();
    setupLogout();
    checkAuth();
  });
</script>
