<template>
  <div class="order-2 md:order-none mt-auto sm:mt-0">
    <!-- Desktop Sidebar -->
    <div
      :class="
        $route.params.id || $route.params.articleId
          ? 'hidden md:flex'
          : 'hidden md:flex'
      "
      class="flex-col max-h-screen overflow-y-auto p-2 relative border-r border-theme-900 gap-2"
    >
      <!-- Chat Section (moved to top) -->
      <div>
        <button
          :class="{ 'bg-theme-900/50': $route.path.includes('chat') }"
          @click="handleAuthClick('chat')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-chat-circle"></span>
          <div class="text-theme-300 text-xs">
            {{ t('chat', 'Chat') }}
          </div>
        </button>
      </div>

      <hr class="border-theme-900" />
      
      <!-- Crew Section (moved up) -->
      <div>
        <button
          :class="{ 'bg-theme-900/50': sectionOpen.crew }"
          @click="handleAuthClick('crew')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <div class="relative">
            <span class="ph-fill text-xl ph-users-three"></span>
            <span
              class="ph-fill text-xs ph-caret-down absolute -top-1 left-1 text-theme-500 transition-transform duration-200"
              :class="{ 'rotate-180': sectionOpen.crew }"
            ></span>
          </div>
          <div class="text-theme-300 text-xs">
            {{ t('bots', 'Bots') }}
          </div>
        </button>
        <transition name="sidebar-collapse">
          <div v-if="sectionOpen.crew && user" class="flex flex-col">
            <button
              :class="{ 'bg-theme-900/50': $route.path.includes('create') }"
              @click="safeOpenModal('create', {}, true, true)"
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-magic-wand"></span>
              <div class="text-theme-300 text-xs">
                {{ t('create_bot_sidebar', 'Create') }}
              </div>
            </button>
            <button
              :class="{ 'bg-theme-900/50': $route.path.includes('characters') }"
              @click="
                !$route.path.includes('characters')
                  ? $router.push('/characters')
                  : null
              "
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-users-three"></span>
              <div class="text-theme-300 text-xs">
                {{ t('crew', 'Crew') }}
              </div>
            </button>
            <button
              :class="{ 'bg-theme-900/50': $route.path.includes('studio') }"
              @click="
                !$route.path.includes('studio') ? $router.push('/studio') : null
              "
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-camera"></span>
              <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_studio }}</div>
            </button>
            <button
              @click="safeOpenModal('LorebookModal', {}, true, true)"
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-book-open-text"></span>
              <div class="text-theme-300 text-xs sidebar-label">
                <span class="sidebar-label-text">{{ t('lorebooks', 'Lore') }}</span>
              </div>
            </button>
            <button
              v-if="isAdmin"
              @click="safeOpenModal('AdminChangelogModal')"
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-users"></span>
              <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_change }}</div>
            </button>
            

          </div>
        </transition>
      </div>

      <hr class="border-theme-900" />

      <!-- Dashboard Section -->
      <div>
        <button
          :class="{ 'bg-theme-900/50': $route.path.includes('dashboard') }"
          @click="handleAuthClick('dashboard')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-user-circle-gear"></span>
          <div class="text-theme-300 text-xs">{{ t('you', 'You') }}</div>
        </button>
      </div>

      <!-- Store Section (Expandable) -->
      <div v-if="canAccessStore">
        <button
          :class="{ 'bg-theme-900/50': sectionOpen.store }"
          @click="toggleSection('store')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <div class="relative">
        <span class="ph-fill text-xl ph-storefront"></span>
        <span
          class="ph-fill text-xs ph-caret-down absolute -top-1 left-1 text-theme-500 transition-transform duration-200"
          :class="{ 'rotate-180': sectionOpen.store }"
        ></span>
          </div>
          <div class="text-theme-300 text-xs">{{ $root.translations.store }}</div>
        </button>
        <transition name="sidebar-collapse">
          <div v-if="sectionOpen.store && user" class="flex flex-col">
            <button
              v-if="user"
              :class="{ 'bg-theme-900/50': $route.path.includes('/store') && $route.query.tab === 'purchases' }"
              @click="goToStoreTab('purchases')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-shopping-bag-open"></span>
          <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_mine }}</div>
        </button>
        <button
          v-if="user"
          :class="{ 'bg-theme-900/50': isModalOpen('CreateStoreListingModal') }"
          @click="safeOpenModal('CreateStoreListingModal')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-plus-circle"></span>
          <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_sell }}</div>
        </button>
        <button
          :class="{ 'bg-theme-900/50': isModalOpen('StoreRequestModal') }"
          @click="user ? safeOpenModal('StoreRequestModal') : safeOpenModal('login')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-megaphone-simple"></span>
          <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_reqs }}</div>
        </button>
          </div>
        </transition>
      </div>

      <div>
        <button
          :class="{ 'bg-theme-900/50': isModalOpen('AchievementsModal') }"
          @click="user ? safeOpenModal('AchievementsModal', { initialTab: 'achievements', initialCategory: 'store' }) : safeOpenModal('login')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-trophy"></span>
          <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_lvls }}</div>
        </button>
      </div>

      <!-- Plans Section (moved after dashboard) -->
      <div
        v-if="user && (planIsZero || isAdmin)"
      >
        <button
          @click="safeOpenModal('plans')"
          class="min-w-12 h-12 transition-all relative duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span
            class="ph-fill text-xl ph-crown bg-gradient-to-r from-brand-400 via-brand-500 to-brand-600 inline-block text-transparent bg-clip-text"
          ></span>
          <div
            class="absolute left-0 top-0 w-full h-full blur-lg opacity-10 bg-brand-400"
          ></div>
          <div class="text-theme-300 text-xs">
            {{ t('plans', 'Plans') }}
          </div>
        </button>
      </div>

      <!-- Beta Section (moved after plans) -->
      <div>
        <button
          v-if="isAdmin || isBeta"
          @click="safeOpenModal('EarlyAccessOverview')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-amber-400"
        >
          <span class="ph-fill text-xl ph-flask"></span>
          <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_beta }}</div>
        </button>
      </div>

      <!-- Admin Section (moved after beta) -->
      <div v-if="isAdmin">
        <button
          @click="safeOpenModal('UserSearchModal')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-magnifying-glass"></span>
          <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_users }}</div>
        </button>


      </div>

      <hr class="border-theme-900" />

      <!-- Help Section -->
      <div>
        <button
          :class="{ 'bg-theme-900/50': sectionOpen.help }"
          @click="toggleSection('help')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <div class="relative">
            <span class="ph-fill text-xl ph-question"></span>
            <span
              class="ph-fill text-xs ph-caret-down absolute -top-1 left-1 text-theme-500 transition-transform duration-200"
              :class="{ 'rotate-180': sectionOpen.help }"
            ></span>
          </div>
          <div class="text-theme-300 text-xs">
            {{ t('help', 'Help') }}
          </div>
        </button>
        <transition name="sidebar-collapse">
          <div v-if="sectionOpen.help" class="flex flex-col">
            <button
              :class="{
                'bg-theme-900/50': $route.path.includes('documentation'),
              }"
              @click="
                !$route.path.includes('documentation')
                  ? $router.push('/documentation')
                  : null
              "
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-book"></span>
              <div class="text-theme-300 text-xs">
                {{ t('docs', 'Docs') }}
              </div>
            </button>

            <button
              :class="{ 'bg-theme-900/50': $route.path.includes('blog') }"
              @click="
                !$route.path.includes('blog')
                  ? $router.push('/blog')
                  : null
              "
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-pen-nib"></span>
              <div class="text-theme-300 text-xs">
                {{ t('blog', 'Blog') }}
              </div>
            </button>

            <button
              @click="safeOpenModal('SiteRatingModal')"
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-star"></span>
              <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_rate }}</div>
            </button>

            <button
              :class="{ 'bg-theme-900/50': $route.path.includes('legal') }"
              @click="
                !$route.path.includes('legal') ? $router.push('/legal') : null
              "
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-lock"></span>
              <div class="text-theme-300 text-xs">
                {{ t('legal', 'Legal') }}
              </div>
            </button>
            
            <button
              :class="{ 'bg-theme-900/50': $route.path.includes('privacy') }"
              @click="
                !$route.path.includes('privacy') ? $router.push('/privacy') : null
              "
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-shield-checkered"></span>
              <div class="text-theme-300 text-xs">
                {{ t('privacy', 'Privacy') }}
              </div>
            </button>

            <button
              :class="{ 'bg-theme-900/50': $route.path.includes('contact') }"
              @click="
                !$route.path.includes('contact') ? $router.push('/contact') : null
              "
              class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
            >
              <span class="ph-fill text-xl ph-envelope"></span>
              <div class="text-theme-300 text-xs">
                {{ t('contact', 'Contact') }}
              </div>
            </button>
          </div>
        </transition>
      </div>

      <hr class="border-theme-900" />

      <!-- Settings and External Links -->
      <div class="flex flex-col gap-2">
        <button
          v-if="installAvailable"
          @click="installApp"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-brand-500/20 rounded-md border border-brand-500/30 text-brand-400"
        >
          <span class="ph-fill text-xl ph-download-simple"></span>
          <div class="text-theme-300 text-xs">
            {{ t('install', 'Install') }}
          </div>
        </button>
        <button
          @click="user ? safeOpenModal('settings') : safeOpenModal('login')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-gear"></span>
          <div class="text-theme-300 text-xs">
            {{ t('config', 'Settings') }}
          </div>
        </button>
        <button
          onclick="window.open('https://discord.gg/W4mSNKSSdR', '_blank')"
          class="min-w-12 h-12 transition-all duration-200 select-none active:scale-95 hover:bg-theme-900/50 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
        >
          <span class="ph-fill text-xl ph-discord-logo"></span>
          <div class="text-theme-300 text-xs">
            {{ t('discord', 'Discord') }}
          </div>
        </button>
      </div>
    </div>

    <!-- Mobile Navigation Bar -->
    <div
      :class="$route.path.includes('chat/') ? 'hidden' : 'flex'"
      class="md:hidden items-center justify-between p-2 border-t border-theme-900 bg-theme-950 z-[60]"
    >
      <!-- Home/Logo Button (moved to first position) -->
      <button
        @click="!$route.path.includes('home') ? $router.push('/home') : null"
        :class="{ 'bg-theme-900/50': $route.path.includes('home') }"
        class="flex-1 flex flex-col items-center justify-center p-2 min-h-[44px] transition-all duration-200 select-none active:scale-95 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
      >
        <span class="ph-fill text-xl ph-house"></span>
        <div class="text-theme-300 text-xs">{{ $root.translations.home }}</div>
      </button>

      <!-- Chat Button (moved to second position) -->
      <button
        :class="{ 'bg-theme-900/50': $route.path.includes('chat') }"
        @click="handleAuthClick('chat')"
        class="flex-1 flex flex-col items-center justify-center p-2 min-h-[44px] transition-all duration-200 select-none active:scale-95 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
      >
        <span class="ph-fill text-xl ph-chat-circle"></span>
        <div class="text-theme-300 text-xs">{{ t('chat', 'Chat') }}</div>
      </button>

      <!-- Crew Button (moved to third position) -->
      <button
        @click="user ? showMobilePopup('crew') : safeOpenModal('login')"
        :class="{ 'bg-theme-900/50': activeMobileSection === 'crew' }"
        class="flex-1 flex flex-col items-center justify-center p-2 min-h-[44px] transition-all duration-200 select-none active:scale-95 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
      >
        <span class="ph-fill text-xl ph-users-three"></span>
        <div class="text-theme-300 text-xs">{{ t('bots', 'Bots') }}</div>
      </button>

      <!-- Dashboard Button (moved to fourth position) -->
      <button
        @click="handleAuthClick('dashboard')"
        :class="{ 'bg-theme-900/50': $route.path.includes('dashboard') }"
        class="flex-1 flex flex-col items-center justify-center p-2 min-h-[44px] transition-all duration-200 select-none active:scale-95 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
      >
        <span class="ph-fill text-xl ph-user-circle-gear"></span>
        <div class="text-theme-300 text-xs">{{ t('you', 'You') }}</div>
      </button>

      <!-- More Button (moved to last position) -->
      <button
        @click="showMobilePopup('more')"
        :class="{ 'bg-theme-900/50': activeMobileSection === 'more' }"
        class="flex-1 flex flex-col items-center justify-center p-2 min-h-[44px] transition-all duration-200 select-none active:scale-95 rounded-md border border-transparent hover:border-theme-800 text-theme-300"
      >
        <span class="ph-fill text-xl ph-dots-three-outline"></span>
        <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_more }}</div>
      </button>
    </div>

    <!-- Mobile Popup Overlay -->
    <transition name="sidebar-fade">
      <div
        v-if="showMobileMenu && activeMobileSection"
        @click="closeMobilePopup"
        class="fixed inset-0 bg-black bg-opacity-50 z-50 md:hidden"
      >
        <!-- Popup Content -->
        <transition name="sidebar-slide-up">
          <div
            v-if="showMobileMenu && activeMobileSection"
            @click.stop
            class="absolute bottom-16 left-0 right-0 bg-theme-950 border-t border-theme-900 p-4 rounded-t-lg max-h-[70vh] overflow-y-auto"
          >
        <div class="flex justify-between items-center mb-3">
          <h3 class="text-theme-400 text-lg font-bold">
            {{
              activeMobileSection === "crew"
                ? t('bots', 'Bots')
                : $root.translations.sidebar_more_options
            }}
          </h3>
          <button @click="closeMobilePopup" class="text-theme-400">
            <span class="ph text-xl ph-x"></span>
          </button>
        </div>

        <!-- Crew Section Content -->
        <div
          v-if="activeMobileSection === 'crew'"
          class="grid grid-cols-3 gap-y-2 gap-x-0.5"
        >
          <button
            @click="user ? safeOpenModal('create', {}, true, true) : safeOpenModal('login')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-magic-wand mb-1"></span>
            <div class="text-theme-300 text-xs text-center">
              {{ t('create_bot_sidebar', 'Create') }}
            </div>
          </button>
          <button
            @click="user ? navigateAndClose('/characters') : safeOpenModal('login')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-users-three mb-1"></span>
            <div class="text-theme-300 text-xs text-center">
              {{ t('crew', 'Crew') }}
            </div>
          </button>
          <!-- Mobile Studio Button -->
          <button
            @click="user ? (!$route.path.includes('studio') ? $router.push('/studio') : null) : safeOpenModal('login')"
            :class="{ 'bg-theme-900/50': $route.path.includes('studio') }"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-camera"></span>
            <div class="text-theme-300 text-xs">{{ $root.translations.sidebar_studio }}</div>
          </button>
          <!-- Mobile Lorebook Button -->
          <button
            @click="openModalAndClose('LorebookModal')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-book-open-text mb-1"></span>
            <div class="text-theme-300 text-xs text-center sidebar-label">
              <span class="sidebar-label-text">{{ t('lorebooks', 'Lore') }}</span>
            </div>
          </button>

        </div>

        <!-- More Options Content -->
        <div
          v-if="activeMobileSection === 'more'"
          class="grid grid-cols-3 gap-y-2 gap-x-0.5"
        >
          <button
            @click="user ? safeOpenModal('settings') : safeOpenModal('login')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-gear mb-1"></span>
            <div class="text-theme-300 text-xs text-center">
              {{ t('config', 'Settings') }}
            </div>
          </button>
          <button
            v-if="canAccessStore"
            @click="navigateAndClose('/store')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-storefront mb-1"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.store }}</div>
          </button>
          <button
            v-if="user && canAccessStore"
            @click="goToStoreTabAndClose('purchases')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-shopping-bag-open mb-1"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_purchases }}</div>
          </button>
          <button
            v-if="user && canAccessStore"
            @click="openModalAndClose('CreateStoreListingModal')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-plus-circle mb-1"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_sell }}</div>
          </button>
          <button
            v-if="canAccessStore"
            @click="user ? openModalAndClose('StoreRequestModal') : openModalAndClose('login')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-megaphone-simple mb-1"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_requests }}</div>
          </button>
          <button
            @click="user ? openModalAndClose('AchievementsModal', { initialTab: 'achievements', initialCategory: 'store' }) : openModalAndClose('login')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-trophy mb-1"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_achievements }}</div>
          </button>
          <!-- Admin Section -->

            <button
             v-if="isAdmin"
              @click="safeOpenModal('UserSearchModal')"
              class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
            >
              <span class="ph-fill text-xl ph-magnifying-glass mb-1"></span>
              <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_users }}</div>
            </button>

          <button
            @click="safeOpenModal('SiteRatingModal')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-star mb-1"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_rate }}</div>
          </button>

          <button
            v-if="user && (planIsZero || isAdmin)"
            @click="safeOpenModal('plans')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span
              class="ph-fill text-xl ph-crown mb-1 bg-gradient-to-r from-brand-400 via-brand-500 to-brand-600 inline-block text-transparent bg-clip-text"
            ></span>
            <div class="text-theme-300 text-xs text-center">
              {{ t('plans', 'Plans') }}
            </div>
          </button>

          <button
            v-if="isBeta || isAdmin"
            @click="safeOpenModal('EarlyAccessOverview')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-flask mb-1 text-amber-400"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_beta }}</div>
          </button>

          <button
            @click="toggleMobileSection('help')"
            :class="{ 'bg-theme-900/50': mobileSectionOpen.help }"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <div class="relative mb-1">
              <span class="ph-fill text-xl ph-question"></span>
              <span
                class="ph-fill text-xs ph-caret-down absolute -top-1 left-1 text-theme-500 transition-transform duration-200"
                :class="{ 'rotate-180': mobileSectionOpen.help }"
              ></span>
            </div>
            <div class="text-theme-300 text-xs text-center">
              {{ t('help', 'Help') }}
            </div>
          </button>
<button
            v-if="isAdmin"
            @click="safeOpenModal('AdminChangelogModal')"
            class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
          >
            <span class="ph-fill text-xl ph-users mb-1"></span>
            <div class="text-theme-300 text-xs text-center">{{ $root.translations.sidebar_change }}</div>
          </button>
          <button
             onclick="window.open('https://discord.gg/W4mSNKSSdR', '_blank')"
             class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
           >
             <span class="ph-fill text-xl ph-discord-logo mb-1"></span>
             <div class="text-theme-300 text-xs text-center">
               {{ t('discord', 'Discord') }}
             </div>
           </button>

           <!-- Install App (PWA) button - only shown when install is available -->
           <button
             v-if="installAvailable"
             @click="installApp"
             class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-brand-400"
           >
             <span class="ph-fill text-xl ph-download-simple mb-1"></span>
<div class="text-brand-400 text-xs text-center font-semibold">{{ $root.translations.sidebar_install_app }}</div>
           </button>

         </div>

         <!-- Help Expandable Section -->
        <transition name="sidebar-collapse">
          <div
            v-if="activeMobileSection === 'more' && mobileSectionOpen.help"
            class="mt-3 grid grid-cols-3 gap-3 border-t border-theme-900 pt-3"
          >
            <button
              @click="navigateAndClose('/documentation')"
              class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
            >
              <span class="ph-fill text-xl ph-book mb-1"></span>
              <div class="text-theme-300 text-xs text-center">
                {{ t('docs', 'Docs') }}
              </div>
            </button>
            <button
              @click="navigateAndClose('/legal')"
              class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
            >
              <span class="ph-fill text-xl ph-lock mb-1"></span>
              <div class="text-theme-300 text-xs text-center">
                {{ t('legal', 'Legal') }}
              </div>
            </button>
            <button
              @click="navigateAndClose('/privacy')"
              class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
            >
              <span class="ph-fill text-xl ph-shield-checkered mb-1"></span>
              <div class="text-theme-300 text-xs text-center">
                {{ t('privacy', 'Privacy') }}
              </div>
            </button>
            <button
              @click="navigateAndClose('/blog')"
              class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
            >
              <span class="ph-fill text-xl ph-pen-nib mb-1"></span>
              <div class="text-theme-300 text-xs text-center">
                {{ t('blog', 'Blog') }}
              </div>
            </button>
            <button
              @click="navigateAndClose('/contact')"
              class="flex flex-col items-center p-1.5 min-h-[40px] gap-0.5 transition-all duration-200 select-none active:scale-95 text-theme-300 hover:text-theme-100"
            >
              <span class="ph-fill text-xl ph-envelope mb-1"></span>
              <div class="text-theme-300 text-xs text-center">
                {{ t('contact', 'Contact') }}
              </div>
            </button>
          </div>
        </transition>
      </div>
      </transition>
    </div>
    </transition>
  </div>
</template>

<script>
export default {
  data() {
    return {
      sectionOpen: {
        plans: false,
        chat: false,
        create: false,
        help: false,
        crew: false,
        dashboard: false,
        legal: false,
        settings: false,
      },
      showMobileMenu: false,
      activeMobileSection: null,
      mobileSectionOpen: {
        help: false,
      },
    };
  },
  computed: {
    // Safe computed property for user - handles cache/initialization issues
    user() {
      try {
        return this.$root?.user || null;
      } catch (e) {
        return null;
      }
    },
    // Safe computed property for checking if user is admin
    isAdmin() {
      try {
        return this.user?.role === 'admin';
      } catch (e) {
        return false;
      }
    },
    // Safe computed property for checking if user is beta
    isBeta() {
      try {
        return this.user?.role === 'beta';
      } catch (e) {
        return false;
      }
    },
    // Safe computed property for store access
    canAccessStore() {
      try {
        if (this.$root && typeof this.$root.canAccessStore === 'function') {
          return this.$root.canAccessStore();
        }
        // Fallback: check user role directly
        const role = String(this.user?.role || "").toLowerCase();
        return role === "beta" || role === "admin";
      } catch (e) {
        return false;
      }
    },
    // Safe computed property for checking if plan is 0 (free)
    planIsZero() {
      try {
        if (this.$root && typeof this.$root.get_plan === 'function') {
          return this.$root.get_plan() === 0;
        }
        return false;
      } catch (e) {
        return false;
      }
    },
    // PWA install availability - checks global window.isPwaInstallable
    installAvailable() {
      try {
        return typeof window.isPwaInstallable === 'function' && window.isPwaInstallable();
      } catch (e) {
        return false;
      }
    },
  },
  mounted() {
    // Listen for install availability changes
    window.addEventListener('pwa-install-ready', this._onInstallReady);
    window.addEventListener('appinstalled', this._onInstalled);
    window.addEventListener('pwa-installed', this._onInstalled);
  },
  beforeUnmount() {
    window.removeEventListener('pwa-install-ready', this._onInstallReady);
    window.removeEventListener('appinstalled', this._onInstalled);
    window.removeEventListener('pwa-installed', this._onInstalled);
  },
  methods: {
    // Safe translation accessor with fallback
    t(key, fallback = '') {
      try {
        if (this.$root?.translations && this.$root.translations[key]) {
          return this.$root.translations[key];
        }
        return fallback || key;
      } catch (e) {
        return fallback || key;
      }
    },
    // Safe openModal wrapper
    safeOpenModal(modalName, data = null, arg1 = null, arg2 = null) {
      try {
        if (this.$root && typeof this.$root.openModal === 'function') {
          if (arg1 !== null || arg2 !== null) {
            this.$root.openModal(modalName, data, arg1, arg2);
          } else {
            this.$root.openModal(modalName, data);
          }
        }
      } catch (e) {
        console.warn('openModal failed:', e);
      }
    },
    // Handle auth-required click actions
    handleAuthClick(action) {
      try {
        if (this.user) {
          switch (action) {
            case 'chat':
              if (!this.$route.path.includes('chat')) {
                this.$router.push('/chat');
              }
              break;
            case 'crew':
              this.toggleSection('crew');
              break;
            case 'dashboard':
              if (!this.$route.path.includes('dashboard')) {
                this.$router.push('/dashboard');
              }
              break;
          }
        } else {
          this.safeOpenModal('login');
        }
      } catch (e) {
        console.warn('handleAuthClick failed:', e);
      }
    },
    toggleSection(section) {
      this.sectionOpen[section] = !this.sectionOpen[section];
    },
    showMobilePopup(section) {
      this.activeMobileSection = section;
      this.showMobileMenu = true;
    },
    closeMobilePopup() {
      this.showMobileMenu = false;
      setTimeout(() => {
        this.activeMobileSection = null;
      }, 300);
    },
    toggleMobileSection(section) {
      this.mobileSectionOpen[section] = !this.mobileSectionOpen[section];
    },
    navigateAndClose(path) {
      if (!this.$route.path.includes(path.substring(1))) {
        this.$router.push(path);
      }
      this.closeMobilePopup();
    },
    goToStoreTab(tab) {
      try {
        if (this.$root && typeof this.$root.requireStoreAccess === 'function') {
          if (!this.$root.requireStoreAccess({ promptLogin: !this.user })) {
            return;
          }
        } else {
          // Fallback: check access manually
          if (!this.canAccessStore) {
            return;
          }
        }

        this.$router.push({
          path: "/store",
          query: {
            tab,
          },
        });
      } catch (e) {
        console.warn('goToStoreTab failed:', e);
      }
    },
    goToStoreTabAndClose(tab) {
      this.goToStoreTab(tab);
      this.closeMobilePopup();
    },
    openModalAndClose(modalName, data = null) {
      this.safeOpenModal(modalName, data);
      this.closeMobilePopup();
    },
    isModalOpen(modalName) {
      try {
        return Array.isArray(this.$root?.activeModals)
          ? this.$root.activeModals.some((modal) => modal.modalName === modalName)
          : false;
      } catch (e) {
        return false;
      }
    },
    // PWA Install helper
    installApp() {
      if (typeof window.triggerPwaInstall === 'function') {
        window.triggerPwaInstall().then(function(accepted) {
          if (accepted && typeof window.lightHaptic === 'function') {
            window.successHaptic();
          }
        });
      }
    },
    // Called when install becomes available
    _onInstallReady() {
      this.$forceUpdate();
    },
    // Called when app is installed
    _onInstalled() {
      this.$forceUpdate();
    },
  },
};
</script>

<style scoped>
/* Simple expand/collapse animation for sidebar sections */
.sidebar-collapse-enter-active,
.sidebar-collapse-leave-active {
  overflow: hidden;
  transition: max-height 0.2s ease, opacity 0.2s ease;
}

/* Mobile popup overlay fade */
.sidebar-fade-enter-active,
.sidebar-fade-leave-active {
  transition: opacity 0.2s ease;
}
.sidebar-fade-enter-from,
.sidebar-fade-leave-to {
  opacity: 0;
}

/* Mobile popup content slide-up */
.sidebar-slide-up-enter-active,
.sidebar-slide-up-leave-active {
  transition: transform 0.25s ease, opacity 0.25s ease;
}
.sidebar-slide-up-enter-from,
.sidebar-slide-up-leave-to {
  transform: translateY(20px);
  opacity: 0;
}

.sidebar-collapse-enter-from,
.sidebar-collapse-leave-to {
  max-height: 0;
  opacity: 0;
}

.sidebar-collapse-enter-to,
.sidebar-collapse-leave-from {
  max-height: 1000px;
  opacity: 1;
}

/* Train-display marquee for overflowing sidebar labels */
.sidebar-label {
  overflow: hidden;
  max-width: 100%;
  white-space: nowrap;
}

.sidebar-label-text {
  display: inline-block;
  animation: train-scroll 4s ease-in-out infinite;
}

.sidebar-label:not(:hover) .sidebar-label-text {
  animation-play-state: running;
}

@keyframes train-scroll {
  0%, 25% {
    transform: translateX(0);
  }
  50%, 75% {
    transform: translateX(min(0px, calc(-100% + 48px)));
  }
  100% {
    transform: translateX(0);
  }
}

/* Only animate when text actually overflows */
.sidebar-label-text:not(.overflows) {
  animation: none;
}
</style>