<template>
  <div id="app">
    <AppSidebar v-if="showSidebar" />

    <div class="app-main" :class="{ 'with-sidebar': showSidebar, 'sidebar-collapsed': collapsed }">
      <!-- Mobile header bar -->
      <div v-if="showSidebar" class="mobile-header">
        <button class="mobile-hamburger" @click="toggleMobile" aria-label="Open menu">
          <Menu :size="22" />
        </button>
        <span class="mobile-title">Space Booking</span>
        <div class="mobile-actions">
          <!-- Notification Bell -->
          <div class="notification-wrapper">
            <button @click="toggleNotifications" class="notification-bell" aria-label="Notifications">
              <Bell :size="20" />
              <span v-if="unreadCount > 0" class="notification-badge">{{ unreadCount }}</span>
            </button>

            <!-- Notification Dropdown -->
            <div v-if="showNotifications" class="notification-dropdown" ref="dropdownRef">
              <div class="notification-header">
                <h3>Notifications</h3>
                <button @click="closeNotifications" class="close-btn">
                  <X :size="18" />
                </button>
              </div>

              <div v-if="loading" class="notification-loading">Loading...</div>

              <div v-else-if="notifications.length === 0" class="notification-empty">
                No new notifications
              </div>

              <div v-else class="notification-list">
                <div
                  v-for="notification in notifications"
                  :key="notification.id"
                  :class="['notification-item', { unread: !notification.is_read }]"
                  @click="handleNotificationClick(notification)"
                >
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-message">{{ notification.message }}</div>
                  <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <main class="content" :class="{ 'content-full': fullBleed }">
        <router-view />
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter, useRoute } from 'vue-router'
import { notificationsApi } from '@/services/api'
import { useSidebar } from '@/composables/useSidebar'
import type { Notification } from '@/types'
import AppSidebar from '@/components/AppSidebar.vue'
import { Menu, Bell, X } from 'lucide-vue-next'

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

const isPublicRoute = computed(() => route.meta.isPublic === true)
const showSidebar = computed(() => authStore.isAuthenticated && !isPublicRoute.value)
const fullBleed = computed(() => route.meta.fullBleed === true)
const { collapsed, toggleMobile } = useSidebar()

const notifications = ref<Notification[]>([])
const showNotifications = ref(false)
const loading = ref(false)
const dropdownRef = ref<HTMLElement | null>(null)

let refreshInterval: number | null = null

const unreadCount = computed(() => {
  return notifications.value.filter((n) => !n.is_read).length
})

const fetchNotifications = async () => {
  if (!authStore.isAuthenticated) return

  try {
    loading.value = true
    notifications.value = await notificationsApi.getAll()
  } catch (error) {
    console.error('Failed to fetch notifications:', error)
  } finally {
    loading.value = false
  }
}

const toggleNotifications = () => {
  showNotifications.value = !showNotifications.value
  if (showNotifications.value) {
    fetchNotifications()
  }
}

const closeNotifications = () => {
  showNotifications.value = false
}

const handleNotificationClick = async (notification: Notification) => {
  if (!notification.is_read) {
    try {
      await notificationsApi.markAsRead(notification.id)
      notification.is_read = true
    } catch (error) {
      console.error('Failed to mark notification as read:', error)
    }
  }

  if (notification.booking_id) {
    closeNotifications()
    router.push('/history')
  }
}

const formatTime = (dateStr: string): string => {
  const date = new Date(dateStr)
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 1) return 'Just now'
  if (diffMins < 60) return `${diffMins} minute${diffMins > 1 ? 's' : ''} ago`
  if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? 's' : ''} ago`
  if (diffDays < 7) return `${diffDays} day${diffDays > 1 ? 's' : ''} ago`
  return date.toLocaleDateString()
}

const handleClickOutside = (event: MouseEvent) => {
  const target = event.target as HTMLElement
  if (
    dropdownRef.value &&
    !dropdownRef.value.contains(target) &&
    !target.closest('.notification-bell')
  ) {
    closeNotifications()
  }
}

onMounted(() => {
  fetchNotifications()
  refreshInterval = window.setInterval(fetchNotifications, 30000)
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
/* Layout */
.app-main {
  min-height: 100vh;
  transition: margin-left var(--transition-normal);
}

.app-main.with-sidebar {
  margin-left: var(--sidebar-width);
}

.app-main.with-sidebar.sidebar-collapsed {
  margin-left: var(--sidebar-collapsed-width);
}

.content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1.5rem;
}

/* Full-bleed pages (e.g. landing) manage their own width/padding */
.content-full {
  max-width: none;
  margin: 0;
  padding: 0;
}

/* Mobile header */
.mobile-header {
  display: none;
  position: sticky;
  top: 0;
  z-index: 50;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  background: var(--color-surface);
  border-bottom: 1px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.mobile-hamburger {
  background: transparent;
  border: none;
  color: var(--color-text-primary);
  cursor: pointer;
  padding: 0.4rem;
  border-radius: var(--radius-sm);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background var(--transition-fast);
}

.mobile-hamburger:hover {
  background: var(--color-bg-secondary);
}

.mobile-title {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--color-text-primary);
  flex: 1;
}

.mobile-actions {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

/* Notifications */
.notification-wrapper {
  position: relative;
}

.notification-bell {
  background: transparent;
  border: none;
  color: var(--color-text-secondary);
  cursor: pointer;
  padding: 0.4rem;
  border-radius: var(--radius-sm);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-fast);
}

.notification-bell:hover {
  background: var(--color-bg-secondary);
  color: var(--color-text-primary);
}

.notification-badge {
  position: absolute;
  top: 0;
  right: 0;
  background: var(--color-danger);
  color: white;
  border-radius: 10px;
  padding: 1px 5px;
  font-size: 0.65rem;
  font-weight: bold;
  min-width: 16px;
  text-align: center;
  line-height: 1.3;
}

.notification-dropdown {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  background: var(--color-surface);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-lg);
  border: 1px solid var(--color-border);
  width: 360px;
  max-height: 420px;
  overflow: hidden;
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.25rem;
  border-bottom: 1px solid var(--color-border-light);
}

.notification-header h3 {
  margin: 0;
  font-size: 1rem;
  color: var(--color-text-primary);
}

.close-btn {
  background: none;
  border: none;
  color: var(--color-text-muted);
  cursor: pointer;
  padding: 0.25rem;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--radius-sm);
  transition: all var(--transition-fast);
}

.close-btn:hover {
  background: var(--color-bg-secondary);
  color: var(--color-text-primary);
}

.notification-loading,
.notification-empty {
  padding: 2rem;
  text-align: center;
  color: var(--color-text-muted);
}

.notification-list {
  overflow-y: auto;
  max-height: 340px;
}

.notification-item {
  padding: 1rem 1.25rem;
  border-bottom: 1px solid var(--color-border-light);
  cursor: pointer;
  transition: background var(--transition-fast);
}

.notification-item:hover {
  background: var(--color-surface-hover);
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-item.unread {
  background: var(--color-accent-light);
  border-left: 3px solid var(--color-accent);
}

.notification-item.unread:hover {
  background: var(--color-surface-hover);
}

.notification-title {
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 0.25rem;
  font-size: 0.9rem;
}

.notification-item.unread .notification-title {
  font-weight: 700;
}

.notification-message {
  color: var(--color-text-secondary);
  font-size: 0.85rem;
  margin-bottom: 0.5rem;
  line-height: 1.4;
}

.notification-time {
  color: var(--color-text-muted);
  font-size: 0.75rem;
}

/* Responsive */
@media (max-width: 768px) {
  .app-main.with-sidebar {
    margin-left: 0;
  }

  .app-main.with-sidebar.sidebar-collapsed {
    margin-left: 0;
  }

  .mobile-header {
    display: flex;
  }

  .content {
    padding: 1.25rem 1rem;
  }

  .notification-dropdown {
    position: fixed;
    left: 1rem;
    right: 1rem;
    top: 60px;
    width: auto;
  }
}
</style>
