<template>
  <Teleport to="body">
    <div v-if="visibleNotifications.length > 0" class="notification-container" :class="{ 'mobile': isMobile }"
      role="region" aria-label="Notifications" aria-live="polite">
      <TransitionGroup name="notification" tag="div" class="notifications-list">
        <div v-for="notification in visibleNotifications" :key="notification.id" class="notification-item" :class="[
          `notification-${notification.type}`,
          {
            'notification-persistent': notification.persistent,
            'notification-interactive': notification.actions && notification.actions.length > 0,
            'notification-with-progress': notification.showProgress
          }
        ]" :data-notification-id="notification.id" @mouseenter="pauseTimer(notification.id)"
          @mouseleave="resumeTimer(notification.id)">
          <!-- Notification Content -->
          <div class="notification-content">
            <!-- Icon with Smart Styling -->
            <div class="notification-icon" :class="`icon-${notification.type}`">
              <BaseIcon :name="getNotificationIcon(notification.type)" class="icon-component" :class="{
                'icon-animated': notification.animated !== false && notification.type !== 'loading'
              }" />
            </div>

            <!-- Message Content -->
            <div class="notification-message">
              <div class="message-main">
                <h4 v-if="notification.title" class="notification-title">
                  {{ notification.title }}
                </h4>
                <p class="notification-text">{{ notification.message }}</p>

                <!-- Rich Content Support -->
                <div v-if="notification.details" class="notification-details">
                  <button class="details-toggle" @click="toggleDetails(notification.id)"
                    :aria-expanded="expandedDetails.has(notification.id)">
                    {{ expandedDetails.has(notification.id) ? 'Less' : 'More' }}
                    <span class="material-icons">
                      {{ expandedDetails.has(notification.id) ? 'expand_less' : 'expand_more' }}
                    </span>
                  </button>

                  <Transition name="details-expand">
                    <div v-if="expandedDetails.has(notification.id)" class="details-content">
                      {{ notification.details }}
                    </div>
                  </Transition>
                </div>
              </div>

              <!-- Progress Indicator (for uploads, etc.) -->
              <div v-if="notification.showProgress" class="notification-progress">
                <div class="progress-bar">
                  <div class="progress-fill" :style="{ width: `${notification.progress || 0}%` }"></div>
                </div>
                <span class="progress-text">{{ notification.progress || 0 }}%</span>
              </div>

              <!-- Action Buttons -->
              <div v-if="notification.actions" class="notification-actions">
                <button v-for="action in notification.actions" :key="action.id" class="action-button"
                  :class="[`action-${action.style || 'primary'}`, { 'action-loading': action.loading }]"
                  @click="handleAction(notification.id, action)" :disabled="action.loading">
                  <span v-if="action.loading" class="material-icons spinning">sync</span>
                  <span v-else-if="action.icon" class="material-icons">{{ action.icon }}</span>
                  {{ action.label }}
                </button>
              </div>
            </div>

            <!-- Dismiss Button (if not persistent) -->
            <button v-if="!notification.persistent" class="notification-dismiss"
              @click="dismissNotification(notification.id)"
              :aria-label="t('notifications.dismiss', 'Dismiss notification')">
              <span class="material-icons">close</span>
            </button>
          </div>

          <!-- Auto-dismiss Timer (visual) -->
          <div v-if="!notification.persistent && notification.duration" class="notification-timer" :style="{
            animationDuration: `${notification.duration}ms`,
            animationPlayState: timerStates.get(notification.id) || 'running'
          }"></div>
        </div>
      </TransitionGroup>

      <!-- Notification Stack Indicator -->
      <div v-if="queuedCount > 0" class="notification-stack-indicator">
        <button class="stack-button" @click="showAllNotifications"
          :aria-label="t('notifications.showMore', `Show ${queuedCount} more notifications`)">
          <span class="stack-count">+{{ queuedCount }}</span>
          <span class="material-icons">expand_more</span>
        </button>
      </div>
    </div>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { useNotificationStore } from '@/stores/notifications'
import { storeToRefs } from 'pinia'
import BaseIcon from '@/components/BaseIcon.vue'

const { t } = useI18n()
const notificationStore = useNotificationStore()
const { notifications } = storeToRefs(notificationStore)

// Reactive state
const expandedDetails = ref(new Set<string>())
const timerStates = ref(new Map<string, 'running' | 'paused'>())
const maxVisible = ref(3) // Maximum notifications visible at once

// Device detection
const isMobile = ref(false)

// Computed properties
const visibleNotifications = computed(() => {
  return notifications.value.slice(0, maxVisible.value)
})

const queuedCount = computed(() => {
  return Math.max(0, notifications.value.length - maxVisible.value)
})

// Smart icon mapping
const getNotificationIcon = (type: string) => {
  const iconMap: Record<string, string> = {
    success: 'ic:round-check-circle',
    error: 'ic:round-error',
    warning: 'ic:round-warning',
    info: 'ic:round-info',
    loading: 'svg-spinners:180-ring-with-bg',
  }
  return iconMap[type as keyof typeof iconMap] || iconMap.info
}

// Notification interactions
const dismissNotification = (id: string) => {
  notificationStore.removeNotification(id)
}

const pauseTimer = (id: string) => {
  timerStates.value.set(id, 'paused')
}

const resumeTimer = (id: string) => {
  timerStates.value.set(id, 'running')
}

const toggleDetails = (id: string) => {
  if (expandedDetails.value.has(id)) {
    expandedDetails.value.delete(id)
  } else {
    expandedDetails.value.add(id)
  }
}

const handleAction = async (notificationId: string, action: any) => {
  // Set loading state
  action.loading = true

  try {
    // Execute action handler
    if (action.handler) {
      await action.handler()
    }

    // Auto-dismiss after successful action (unless persistent)
    const notification = notifications.value.find(n => n.id === notificationId)
    if (notification && !notification.persistent) {
      dismissNotification(notificationId)
    }
  } catch (error) {
    console.error('Action failed:', error)

    // Show error notification
    notificationStore.addNotification({
      type: 'error',
      message: t('notifications.actionFailed', 'Action failed. Please try again.'),
      duration: 3000
    })
  } finally {
    action.loading = false
  }
}

const showAllNotifications = () => {
  maxVisible.value = notifications.value.length
}

// Device detection and responsive behavior
const updateDeviceType = () => {
  isMobile.value = window.innerWidth < 768

  // Adjust max visible based on device
  maxVisible.value = isMobile.value ? 2 : 3
}

// Lifecycle
onMounted(() => {
  updateDeviceType()
  window.addEventListener('resize', updateDeviceType, { passive: true })

  // Auto-cleanup expanded details when notifications are removed
  const cleanupExpandedDetails = () => {
    const currentIds = new Set(notifications.value.map(n => n.id))
    expandedDetails.value.forEach(id => {
      if (!currentIds.has(id)) {
        expandedDetails.value.delete(id)
      }
    })
  }

  // Watch for notification changes
  const unwatchNotifications = notificationStore.$subscribe(cleanupExpandedDetails)

  onUnmounted(() => {
    window.removeEventListener('resize', updateDeviceType)
    unwatchNotifications()
  })
})
</script>

<style scoped lang="scss">
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');

.notification-container {
  position: fixed;
  top: 1rem;
  right: 1rem;
  z-index: 1000;
  max-width: 400px;
  pointer-events: none;

  &.mobile {
    top: auto;
    bottom: 6rem; // Above mobile nav
    left: 1rem;
    right: 1rem;
    max-width: none;
  }

  @media (min-width: 768px) {
    top: 1rem;
    right: 1rem;
    bottom: auto;
    left: auto;
    max-width: 400px;
  }
}

.notifications-list {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

/* Notification Item */
.notification-item {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 1px solid #e5e7eb;
  pointer-events: auto;
  position: relative;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
  }

  // Type-specific styling
  &.notification-success {
    border-left: 4px solid #10b981;

    .notification-icon {
      background: #ecfdf5;
      color: #065f46;
    }
  }

  &.notification-error {
    border-left: 4px solid #ef4444;

    .notification-icon {
      background: #fef2f2;
      color: #991b1b;
    }
  }

  &.notification-warning {
    border-left: 4px solid #f59e0b;

    .notification-icon {
      background: #fffbeb;
      color: #92400e;
    }
  }

  &.notification-info {
    border-left: 4px solid #3b82f6;

    .notification-icon {
      background: #eff6ff;
      color: #1e40af;
    }
  }

  &.notification-loading {
    border-left: 4px solid #8b5cf6;

    .notification-icon {
      background: #f5f3ff;
      color: #6d28d9;
    }
  }

  // Interactive notifications
  &.notification-interactive {
    cursor: pointer;
  }

  // Persistent notifications
  &.notification-persistent {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 2px rgba(59, 130, 246, 0.1);
  }

  // Progress notifications
  &.notification-with-progress {
    padding-bottom: 0;
  }
}

.notification-content {
  display: flex;
  align-items: flex-start;
  gap: 1rem;
  padding: 1rem;
  position: relative;
}

/* Icon */
.notification-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  flex-shrink: 0;

  .icon-component {
    font-size: 1.25rem;

    &.icon-animated {
      animation: icon-bounce 0.6s ease-out;
    }
  }
}

/* Message Content */
.notification-message {
  flex-grow: 1;
  min-width: 0;
}

.message-main {
  margin-bottom: 0.75rem;
}

.notification-title {
  font-size: 0.875rem;
  font-weight: 600;
  color: #111827;
  margin: 0 0 0.25rem 0;
  line-height: 1.4;
}

.notification-text {
  font-size: 0.875rem;
  color: #374151;
  margin: 0;
  line-height: 1.5;
}

/* Details Section */
.notification-details {
  margin-top: 0.5rem;
}

.details-toggle {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  background: none;
  border: none;
  color: #3b82f6;
  cursor: pointer;
  font-size: 0.75rem;
  font-weight: 500;
  transition: color 0.2s ease;

  &:hover {
    color: #2563eb;
  }

  .material-icons {
    font-size: 1rem;
  }
}

.details-content {
  margin-top: 0.5rem;
  padding: 0.75rem;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 0.8rem;
  color: #6b7280;
  line-height: 1.4;
}

/* Progress Bar */
.notification-progress {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-top: 0.75rem;
}

.progress-bar {
  flex-grow: 1;
  height: 4px;
  background: #e5e7eb;
  border-radius: 2px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  border-radius: 2px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 0.75rem;
  color: #6b7280;
  font-weight: 500;
  min-width: 3rem;
  text-align: right;
}

/* Actions */
.notification-actions {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.75rem;
  flex-wrap: wrap;
}

.action-button {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.375rem 0.75rem;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;

  &.action-primary {
    background: #3b82f6;
    color: white;
    border: 1px solid #3b82f6;

    &:hover {
      background: #2563eb;
    }

    &:disabled {
      background: #9ca3af;
      border-color: #9ca3af;
    }
  }

  &.action-secondary {
    background: white;
    color: #374151;
    border: 1px solid #d1d5db;

    &:hover {
      background: #f9fafb;
    }
  }

  &.action-danger {
    background: #ef4444;
    color: white;
    border: 1px solid #ef4444;

    &:hover {
      background: #dc2626;
    }
  }

  &.action-loading {
    pointer-events: none;
    opacity: 0.7;
  }

  .material-icons {
    font-size: 1rem;

    &.spinning {
      animation: spin 1s linear infinite;
    }
  }
}

/* Dismiss Button */
.notification-dismiss {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.5rem;
  height: 1.5rem;
  background: none;
  border: none;
  color: #9ca3af;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: #f3f4f6;
    color: #6b7280;
  }

  .material-icons {
    font-size: 1rem;
  }
}

/* Auto-dismiss Timer */
.notification-timer {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 3px;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  animation: timer-countdown linear forwards;
  transform-origin: left;
}

/* Stack Indicator */
.notification-stack-indicator {
  margin-top: 0.75rem;
  pointer-events: auto;
}

.stack-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  width: 100%;
  padding: 0.75rem;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.875rem;
  color: #6b7280;

  &:hover {
    background: #f8f9fa;
    border-color: #d1d5db;
  }
}

.stack-count {
  font-weight: 600;
  color: #3b82f6;
}

/* Animations */
@keyframes icon-bounce {
  0% {
    transform: scale(0.8);
  }

  50% {
    transform: scale(1.1);
  }

  100% {
    transform: scale(1);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

@keyframes timer-countdown {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(0);
  }
}

/* Transition Animations */
.notification-enter-active,
.notification-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.notification-enter-from {
  opacity: 0;
  transform: translateX(100%);
}

.notification-leave-to {
  opacity: 0;
  transform: translateX(100%);
}

.notification-move {
  transition: transform 0.3s ease;
}

.details-expand-enter-active,
.details-expand-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.details-expand-enter-from,
.details-expand-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
}

.details-expand-enter-to,
.details-expand-leave-from {
  opacity: 1;
  max-height: 200px;
  margin-top: 0.5rem;
}

/* Dark Mode Support */
@media (prefers-color-scheme: dark) {
  .notification-item {
    background: #374151;
    border-color: #4b5563;
    color: #f9fafb;
  }

  .notification-title {
    color: #f9fafb;
  }

  .notification-text {
    color: #d1d5db;
  }

  .details-content {
    background: #4b5563;
    color: #d1d5db;
  }

  .action-button.action-secondary {
    background: #4b5563;
    color: #f9fafb;
    border-color: #6b7280;

    &:hover {
      background: #374151;
    }
  }

  .notification-dismiss:hover {
    background: #4b5563;
  }

  .stack-button {
    background: #374151;
    border-color: #4b5563;
    color: #d1d5db;

    &:hover {
      background: #4b5563;
    }
  }
}

/* Mobile Optimizations */
@media (max-width: 767px) {
  .notification-container {
    &.mobile {
      .notification-item {
        margin-bottom: 0.5rem;
      }

      .notification-content {
        padding: 0.875rem;
      }

      .notification-icon {
        width: 2rem;
        height: 2rem;

        .icon-component {
          font-size: 1rem;
        }
      }

      .notification-actions {
        flex-direction: column;

        .action-button {
          justify-content: center;
        }
      }
    }
  }
}

/* Accessibility */
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
  }
}

/* Performance optimizations */
.notification-item {
  will-change: transform, opacity;
}

.progress-fill {
  will-change: width;
}

.notification-timer {
  will-change: transform;
}
</style>