<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Navigation -->
    <nav class="bg-white shadow-sm border-b border-gray-100">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex">
            <!-- Logo -->
            <router-link to="/" class="flex items-center">
              <img 
                src="/logo_lediscord.png" 
                alt="LeDiscord Logo" 
                class="h-8 w-auto mr-2"
              >
              <span class="text-2xl font-bold bg-gradient-primary bg-clip-text text-transparent">LeDiscord</span>
            </router-link>
            
            <!-- Navigation Links -->
            <div class="hidden sm:ml-8 sm:flex sm:space-x-6">
              <router-link
                v-for="item in navigation"
                :key="item.name"
                :to="item.to"
                class="inline-flex items-center px-1 pt-1 text-sm font-medium border-b-2 border-transparent transition-colors relative"
                :class="item.comingSoon 
                  ? 'text-gray-400 cursor-not-allowed opacity-60 !border-transparent' 
                  : 'text-secondary-600 hover:text-primary-600 hover:border-primary-600'"
                :active-class="item.comingSoon ? '' : '!text-primary-600 !border-primary-600'"
                @click.prevent="item.comingSoon ? null : null"
              >
                <component :is="item.icon" class="w-4 h-4 mr-2" />
                {{ item.name }}
                <span 
                  v-if="item.comingSoon" 
                  class="ml-1.5 px-1 py-0.5 text-[9px] font-medium text-white bg-purple-600 rounded"
                >
                  Soon
                </span>
              </router-link>
            </div>
          </div>

          <div class="flex items-center space-x-4">
            <!-- Notifications -->
            <button
              @click="showNotifications = !showNotifications"
              class="relative p-2 text-gray-600 hover:text-primary-600 transition-colors"
            >
              <Bell class="w-5 h-5" />
              <span
                v-if="unreadNotifications > 0"
                class="absolute -top-1 -right-1 flex items-center justify-center min-w-[18px] h-[18px] px-1 text-[10px] font-bold text-white bg-red-500 rounded-full"
              >
                {{ unreadNotifications > 99 ? '99+' : unreadNotifications }}
              </span>
            </button>

            <!-- User Menu -->
            <div class="relative">
              <button
                @click="showUserMenu = !showUserMenu"
                class="flex items-center space-x-2 text-sm font-medium text-gray-600 hover:text-primary-600 transition-colors"
              >
                <img
                  v-if="user?.avatar_url"
                  :src="getMediaUrl(user.avatar_url)"
                  :alt="user.full_name"
                  class="w-8 h-8 rounded-full object-cover"
                >
                <div v-else class="w-8 h-8 rounded-full bg-primary-100 flex items-center justify-center">
                  <User class="w-4 h-4 text-primary-600" />
                </div>
                <span class="hidden sm:block">{{ user?.full_name }}</span>
                <ChevronDown class="w-4 h-4" />
              </button>

              <!-- Dropdown -->
              <transition
                enter-active-class="transition ease-out duration-100"
                enter-from-class="transform opacity-0 scale-95"
                enter-to-class="transform opacity-100 scale-100"
                leave-active-class="transition ease-in duration-75"
                leave-from-class="transform opacity-100 scale-100"
                leave-to-class="transform opacity-0 scale-95"
              >
                <div
                  v-if="showUserMenu"
                  class="absolute right-0 mt-2 w-48 rounded-lg bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5"
                >
                  <router-link
                    to="/profile"
                    @click="showUserMenu = false"
                    class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                  >
                    Mon profil
                  </router-link>
                  <router-link
                    to="/stats"
                    @click="showUserMenu = false"
                    class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                  >
                    Statistiques
                  </router-link>
                  <router-link
                    to="/information"
                    @click="showUserMenu = false"
                    class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900"
                  >
                    Informations
                  </router-link>
                  <router-link
                    to="/my-tickets"
                    @click="showUserMenu = false"
                    class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900"
                  >
                    Mes tickets
                  </router-link>
                  <router-link
                    v-if="authStore.isAdmin"
                    to="/admin"
                    @click="showUserMenu = false"
                    class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                  >
                    Administration
                  </router-link>

                  <hr class="my-1">
                  
                  <!-- Installer l'app -->
                  <button
                    @click="handleInstallApp"
                    :disabled="isPWAInstalled || !canInstall"
                    class="block w-full text-left px-4 py-2 text-sm transition-colors"
                    :class="isPWAInstalled || !canInstall 
                      ? 'text-gray-400 cursor-not-allowed' 
                      : 'text-gray-700 hover:bg-gray-100'"
                  >
                    <div class="flex items-center">
                      <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z" />
                      </svg>
                      {{ isPWAInstalled ? 'Application installée' : 'Installer l\'app' }}
                    </div>
                  </button>

                  <hr class="my-1">
                  <button
                    @click="logout"
                    class="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                  >
                    Déconnexion
                  </button>
                </div>
              </transition>
            </div>

            <!-- Mobile menu button -->
            <div class="flex items-center sm:hidden ml-4">
              <button
                @click="isMobileMenuOpen = !isMobileMenuOpen"
                class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-inset focus:ring-primary-500"
              >
                <span class="sr-only">Open main menu</span>
                <Menu v-if="!isMobileMenuOpen" class="block h-6 w-6" aria-hidden="true" />
                <X v-else class="block h-6 w-6" aria-hidden="true" />
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Mobile menu -->
      <div class="sm:hidden border-t border-gray-200" v-show="isMobileMenuOpen">
        <div class="pt-2 pb-3 space-y-1">
          <router-link
            v-for="item in navigation"
            :key="item.name"
            :to="item.to"
            class="flex items-center px-4 py-2 text-base font-medium hover:bg-gray-50 relative"
            :class="item.comingSoon 
              ? 'text-gray-400 cursor-not-allowed opacity-60' 
              : 'text-gray-600 hover:text-primary-600'"
            active-class="!text-primary-600 bg-primary-50"
            @click.prevent="item.comingSoon ? null : null"
          >
            <component :is="item.icon" class="w-5 h-5 mr-3" />
            <span>{{ item.name }}</span>
            <span 
              v-if="item.comingSoon" 
              class="ml-auto px-1 py-0.5 text-[9px] font-medium text-white bg-purple-600 rounded"
            >
              Soon
            </span>
          </router-link>
        </div>
      </div>
    </nav>

    <!-- Main Content -->
    <main class="flex-1 bg-gray-50">
      <router-view />
    </main>

    <!-- Ticket Floating Button -->
    <TicketFloatingButton />

    <!-- Notifications Panel -->
    <transition
      enter-active-class="transition ease-out duration-200"
      enter-from-class="transform translate-x-full"
      enter-to-class="transform translate-x-0"
      leave-active-class="transition ease-in duration-150"
      leave-from-class="transform translate-x-0"
      leave-to-class="transform translate-x-full"
    >
      <div
        v-if="showNotifications"
        class="fixed right-0 top-16 h-full w-80 bg-white shadow-xl z-50 overflow-y-auto"
      >
        <div class="p-4">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold">Notifications</h3>
            <button
              @click="showNotifications = false"
              class="text-gray-400 hover:text-gray-600"
            >
              <X class="w-5 h-5" />
            </button>
          </div>
          
          <div v-if="notifications.length === 0" class="text-center py-8 text-gray-500">
            Aucune notification
          </div>
          
          <div v-else class="space-y-3">
            <div class="flex items-center justify-between mb-3">
              <span class="text-sm text-gray-600">{{ notifications.length }} notification(s)</span>
              <button
                @click="markAllRead"
                class="text-xs text-primary-600 hover:text-primary-800"
              >
                Tout marquer comme lu
              </button>
            </div>
            
            <div
              v-for="notification in notifications"
              :key="notification.id"
              @click="handleNotificationClick(notification)"
              class="p-3 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors"
              :class="{ 'bg-blue-50 border-l-4 border-blue-500': !notification.is_read }"
            >
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <h4 class="font-medium text-sm text-gray-900">{{ notification.title }}</h4>
                  <p class="text-xs text-gray-600 mt-1">{{ notification.message }}</p>
                  <p class="text-xs text-gray-400 mt-2">{{ formatDate(notification.created_at) }}</p>
                </div>
                <div v-if="!notification.is_read" class="w-2 h-2 bg-blue-500 rounded-full ml-2 flex-shrink-0"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import { format } from 'date-fns'
import { fr } from 'date-fns/locale'
import { getMediaUrl } from '@/utils/axios'
import {
  Home,
  Calendar,
  Image,
  Film,
  MessageSquare,
  Bell,
  User,
  ChevronDown,
  X,
  Menu,
  Dice6
} from 'lucide-vue-next'
import UserAvatar from '@/components/UserAvatar.vue'
import TicketFloatingButton from '@/components/TicketFloatingButton.vue'

const authStore = useAuthStore()
const router = useRouter()

const navigation = [
  { name: 'Accueil', to: '/', icon: Home },
  { name: 'Événements', to: '/events', icon: Calendar },
  { name: 'Albums', to: '/albums', icon: Image },
  { name: 'Vlogs', to: '/vlogs', icon: Film },
  { name: 'Publications', to: '/posts', icon: MessageSquare },
  { name: 'Jeux', to: '#', icon: Dice6, comingSoon: true }
]

const showUserMenu = ref(false)
const showNotifications = ref(false)
const isMobileMenuOpen = ref(false)
const deferredPrompt = ref(null)
const isPWAInstalled = ref(false)
const canInstall = ref(false)

const user = computed(() => authStore.user)
const notifications = computed(() => authStore.notifications)
const unreadNotifications = computed(() => authStore.unreadCount)

function formatDate(date) {
  return format(new Date(date), 'dd MMM à HH:mm', { locale: fr })
}

async function logout() {
  showUserMenu.value = false
  await authStore.logout()
}

async function fetchNotifications() {
  const result = await authStore.fetchNotifications()
  // Les notifications sont maintenant mises à jour automatiquement via le polling
}

async function markAllRead() {
  await authStore.markAllNotificationsRead()
}

async function handleNotificationClick(notification) {
  if (!notification.is_read) {
    await authStore.markNotificationRead(notification.id)
  }
  
  if (notification.link) {
    router.push(notification.link)
  }
  
  showNotifications.value = false
}

// PWA Installation logic
function checkPWAInstalled() {
  // Vérifier si l'app est déjà installée (mode standalone)
  isPWAInstalled.value = window.matchMedia('(display-mode: standalone)').matches || 
                         window.navigator.standalone === true ||
                         document.referrer.includes('android-app://')
}

function handleBeforeInstallPrompt(e) {
  // Empêcher le prompt par défaut
  e.preventDefault()
  // Stocker l'événement pour l'utiliser plus tard
  deferredPrompt.value = e
  canInstall.value = true
}

async function handleInstallApp() {
  if (!deferredPrompt.value || isPWAInstalled.value) {
    return
  }

  try {
    showUserMenu.value = false
    
    // Afficher le prompt d'installation
    deferredPrompt.value.prompt()
    
    // Attendre la réponse de l'utilisateur
    const { outcome } = await deferredPrompt.value.userChoice
    
    if (outcome === 'accepted') {
      console.log('✅ PWA installée avec succès')
      isPWAInstalled.value = true
    } else {
      console.log('❌ Installation PWA annulée')
    }
    
    // Réinitialiser
    deferredPrompt.value = null
    canInstall.value = false
  } catch (error) {
    console.error('Erreur lors de l\'installation:', error)
  }
}

onMounted(async () => {
  await authStore.fetchCurrentUser()
  
  if (authStore.isAuthenticated) {
    await fetchNotifications()
    await authStore.fetchUnreadCount()
    
    // Démarrer le polling des notifications
    const notificationService = (await import('@/services/notificationService')).default
    notificationService.startPolling()
    notificationService.setupServiceWorkerListener()
    
    // Demander la permission pour les notifications push
    await notificationService.requestNotificationPermission()
  }
  
  // Vérifier si PWA est installée
  checkPWAInstalled()
  
  // Écouter l'événement beforeinstallprompt
  window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
  
  // Écouter les changements de display mode
  window.matchMedia('(display-mode: standalone)').addEventListener('change', checkPWAInstalled)
})

onBeforeUnmount(async () => {
  window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt)
  
  // Arrêter le polling des notifications
  const notificationService = (await import('@/services/notificationService')).default
  notificationService.stopPolling()
})
</script>