<template>
  <!-- Enhanced Header with Context -->
  <header
    class="page-header sticky top-0 z-40 bg-white/80 backdrop-blur-xl border-b border-slate-200 -mx-6 -mt-6 mb-6 px-6 py-3">
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <Button variant="ghost" size="sm" @click="router.back()" class="p-2 hover:bg-slate-100 rounded-full">
          <BaseIcon name="heroicons:arrow-left" class="w-5 h-5" />
        </Button>
        <div>
          <Heading :level="1" class="text-xl font-bold text-slate-900">
            {{ list?.name || t('listDetailPage.loading.list') }}
          </Heading>
          <p v-if="list?.description" class="text-sm text-slate-600">
            {{ list.description }}
          </p>
        </div>
      </div>

      <!-- Shopping Mode Toggle -->
      <div class="flex items-center gap-2">
        <Switch v-model="shoppingMode" :label="t('listDetailPage.shoppingMode')"
          class="data-[checked]:bg-emerald-500" />
        <Menu as="div" class="relative">
          <MenuButton as="template">
            <Button variant="ghost" size="sm" class="p-2">
              <BaseIcon name="heroicons:ellipsis-horizontal" class="w-5 h-5" />
            </Button>
          </MenuButton>
          <MenuItems class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-slate-200 py-1 z-50">
            <MenuItem v-slot="{ active }">
            <button
              :class="[active ? 'bg-slate-50' : '', 'w-full px-4 py-2 text-left text-sm text-slate-700 flex items-center gap-2']"
              @click="showExpenseModal = true">
              <BaseIcon name="heroicons:currency-dollar" class="w-4 h-4" />
              {{ t('listDetailPage.createExpense') }}
            </button>
            </MenuItem>
            <MenuItem v-slot="{ active }">
            <button
              :class="[active ? 'bg-slate-50' : '', 'w-full px-4 py-2 text-left text-sm text-slate-700 flex items-center gap-2']"
              @click="showReceiptScanner = true">
              <BaseIcon name="heroicons:camera" class="w-4 h-4" />
              {{ t('listDetailPage.scanReceipt') }}
            </button>
            </MenuItem>
            <MenuItem v-slot="{ active }">
            <button
              :class="[active ? 'bg-slate-50' : '', 'w-full px-4 py-2 text-left text-sm text-slate-700 flex items-center gap-2']"
              @click="openCostSummary">
              <BaseIcon name="heroicons:calculator" class="w-4 h-4" />
              {{ t('listDetailPage.costSummary', 'Cost Summary') }}
            </button>
            </MenuItem>
          </MenuItems>
        </Menu>
      </div>
    </div>

    <!-- Progress Bar for Shopping Mode -->
    <Transition name="slide-down">
      <div v-if="shoppingMode" class="mt-3">
        <ProgressBar :value="completionPercentage" class="h-2 bg-slate-200 rounded-full overflow-hidden"
          :class="[completionPercentage === 100 ? 'bg-emerald-500' : 'bg-blue-500']" />
        <p class="text-xs text-slate-600 mt-1">
          {{ t('listDetailPage.progress', { completed: completedCount, total: totalCount }) }}
        </p>
      </div>
    </Transition>
  </header>

  <!-- Loading State -->
  <div v-if="isLoading && !list" class="flex items-center justify-center py-12">
    <div class="text-center">
      <Spinner class="w-8 h-8 mx-auto mb-4" />
      <p class="text-slate-600">{{ t('listDetailPage.loading.list') }}</p>
    </div>
  </div>

  <!-- Error State -->
  <Alert v-else-if="error" type="error" class="mb-4" :message="error">
    <Button variant="outline" size="sm" @click="refetchList" class="mt-2">
      {{ t('common.retry') }}
    </Button>
  </Alert>

  <!-- Main Content -->
  <div v-else-if="list" class="pb-24">


    <!-- Enhanced Loading State -->
    <div v-if="isLoading && !list" class="loading-container">
      <div class="loading-header">
        <div class="skeleton-line title"></div>
        <div class="skeleton-line subtitle"></div>
      </div>
      <div class="loading-items">
        <div v-for="i in 8" :key="i" class="skeleton-item">
          <div class="skeleton-checkbox"></div>
          <div class="skeleton-content">
            <div class="skeleton-line"></div>
            <div class="skeleton-line short"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div v-else-if="list && list.items?.length === 0" class="empty-state">
      <div class="empty-illustration">
        <span class="material-icons">checklist</span>
      </div>
      <h3 class="empty-title">{{ t('listDetailPage.emptyState.title') }}</h3>
      <p class="empty-subtitle">{{ t('listDetailPage.emptyState.description') }}</p>
      <Button @click="focusNewItemInput" variant="outline">
        {{ t('listDetailPage.emptyState.addFirstItem') }}
      </Button>
    </div>

    <!-- Items List with Smart Grouping -->
    <section class="items-section">
      <ItemsList :list="list" :items="list.items || []" :is-online="isOnline" :supermarkt-mode="shoppingMode"
        :category-options="categoryOptions" :categories="categories" :new-item="newItem"
        @delete-item="deleteItemOptimistic" @checkbox-change="handleItemCheckboxChange"
        @update-price="handleUpdateItemPrice" @update-quantity="handleUpdateItemQuantity"
        @reorder-items="handleReorderItems" @add-item="handleAddItem" @update:newItemName="newItem.name = $event"
        @update:newItemCategoryId="newItem.category_id = $event" @mark-bought="handleMarkBought"
        @create-category="handleCreateCategory" />
    </section>
  </div>

  <!-- Purchase Confirmation Dialog -->
  <PurchaseConfirmationDialog v-if="showPurchaseDialog && selectedItems.length > 0" :items="selectedItems"
    @confirm="handleConfirmPurchase" />

  <!-- Expense Creation Modal -->
  <ExpenseCreationSheet v-if="showExpenseModal" v-model="showExpenseModal" :list-items="completedItems"
    @created="handleExpenseCreated" />

  <!-- Receipt Scanner Modal -->
  <ReceiptScannerModal v-if="showReceiptScanner" v-model="showReceiptScanner" @items-detected="handleReceiptItems" />

  <!-- Undo Toast -->
  <Transition name="slide-up">
    <div v-if="undoAction"
      class="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-slate-800 text-white px-4 py-3 rounded-lg shadow-lg z-50">
      <div class="flex items-center gap-3">
        <p class="text-sm">{{ undoAction.message }}</p>
        <Button variant="ghost" size="sm" @click="executeUndo" class="text-white hover:bg-slate-700">
          {{ t('common.undo') }}
        </Button>
      </div>
      <div class="mt-2 h-1 bg-slate-600 rounded-full overflow-hidden">
        <div class="h-full bg-slate-400 transition-all duration-[10000ms] ease-linear"
          :style="{ width: undoAction.timeLeft + '%' }"></div>
      </div>
    </div>
  </Transition>

  <!-- Offline Indicator -->
  <OfflineIndicator />

  <!-- Conflict Resolution Dialog -->
  <ConflictResolutionDialog v-if="showConflictDialog" v-model="showConflictDialog" :conflict="currentConflict"
    @resolved="handleConflictResolved" />

  <!-- Cost Summary Dialog -->
  <CostSummaryDialog v-model="showCostSummaryDialog" :summary="costSummary" :loading="costSummaryLoading"
    :error="costSummaryError" @generate-expense="handleGenerateExpense" />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useNetwork } from '@vueuse/core'
import { formatDistanceToNow } from 'date-fns'
import { storeToRefs } from 'pinia'
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'

// Stores
import { useListsStore } from '@/stores/listsStore'
import { useAuthStore } from '@/stores/auth'
import { useCategoryStore } from '@/stores/categoryStore'
import { useSocket } from '@/composables/useSocket'
import { useOptimisticUpdates } from '@/composables/useOptimisticUpdates'
import { useConflictResolution } from '@/composables/useConflictResolution'
import { useNotificationStore } from '@/stores/notifications'

// UI Components
import {
  Heading,
  Button,
  Card,
  Alert,
  ProgressBar,
  Switch,
  Spinner
} from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import ListItemComposer from '@/components/list-detail/ListItemComposer.vue'
import ListItem from '@/components/list-detail/ListItem.vue'
import ItemsList from '@/components/list-detail/ItemsList.vue'
import PurchaseConfirmationDialog from '@/components/list-detail/PurchaseConfirmationDialog.vue'
import ExpenseCreationSheet from '@/components/expenses/ExpenseCreationSheet.vue'
import ReceiptScannerModal from '@/components/ReceiptScannerModal.vue'
import OfflineIndicator from '@/components/OfflineIndicator.vue'
import ConflictResolutionDialog from '@/components/global/ConflictResolutionDialog.vue'
import CostSummaryDialog from '@/components/list-detail/CostSummaryDialog.vue'
import { useItemHelpers } from '@/composables/useItemHelpers'
import { costService } from '@/services/costService'
import type { ListCostSummary } from '@/services/costService'

// Types
interface UndoAction {
  message: string
  action: () => void
  timeLeft: number
}

const { t } = useI18n()
const { isOnline } = useNetwork()
const route = useRoute()
const router = useRouter()

// Stores
const listsStore = useListsStore()
const authStore = useAuthStore()
const categoryStore = useCategoryStore()
const notificationStore = useNotificationStore()

// Store refs
const {
  currentList: list,
  isLoading,
  error
} = storeToRefs(listsStore)
const { categories } = storeToRefs(categoryStore)

// Composables
const { connect, on, off, emit } = useSocket()
const optimisticUpdates = useOptimisticUpdates([])
const conflictResolution = useConflictResolution()
const { buildCategoryOptions } = useItemHelpers()

// Local state
const shoppingMode = ref(false)
const showPurchaseDialog = ref(false)
const showExpenseModal = ref(false)
const showReceiptScanner = ref(false)
const selectedItems = ref<any[]>([])
const undoAction = ref<UndoAction | null>(null)
const activeShoppers = ref<any[]>([])
const showConflictDialog = ref(false)
const currentConflict = ref<any>(null)
const showListOptions = ref(false)
const showItemEdit = ref(false)
const editingItem = ref(null)
const viewMode = ref<'all' | 'pending'>('all')
const showCompletedItems = ref(false)

// New item state for ItemsList
const newItem = ref({
  name: '',
  category_id: null as number | null
})

// Computed
const listId = computed(() => route.params.id as string)

const sortedItems = computed(() => {
  if (!list.value?.items) return []

  return [...list.value.items].sort((a, b) => {
    // In shopping mode, prioritize claimed items and incomplete items
    if (shoppingMode.value) {
      if (a.claimed_by_user_id && !b.claimed_by_user_id) return -1
      if (!a.claimed_by_user_id && b.claimed_by_user_id) return 1
      if (!a.is_complete && b.is_complete) return -1
      if (a.is_complete && !b.is_complete) return 1
    }

    // Default sort by completion status, then by creation date
    if (!a.is_complete && b.is_complete) return -1
    if (a.is_complete && !b.is_complete) return 1
    return new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
  })
})

const completedCount = computed(() =>
  list.value?.items?.filter(item => item.is_complete).length || 0
)

const totalCount = computed(() => list.value?.items?.length || 0)

const completionPercentage = computed(() =>
  totalCount.value === 0 ? 0 : Math.round((completedCount.value / totalCount.value) * 100)
)

const completedItems = computed(() =>
  list.value?.items?.filter(item => item.is_complete) || []
)

const incompleteTasks = computed(() => {
  return list.value?.items.filter(item => !item.is_complete) || []
})

const completedTasks = computed(() => {
  return list.value?.items.filter(item => item.is_complete) || []
})

const isCompleted = computed(() => {
  return list.value?.items.every(item => item.is_complete) && list.value?.items.length > 0
})

const lastUpdated = computed(() => {
  if (!list.value?.updated_at) return null
  return formatDistanceToNow(new Date(list.value.updated_at), { addSuffix: true })
})

const completionStats = computed(() => {
  if (!list.value?.items.length) return t('listDetailPage.stats.empty', 'No items')
  const completed = completedTasks.value.length
  const total = list.value.items.length
  return t('listDetailPage.stats.progress', `${completed}/${total} completed`)
})

const categoryOptions = computed(() => {
  return buildCategoryOptions(categories.value || [], true)
})

// Cost Summary dialog state
const showCostSummaryDialog = ref(false)
const costSummaryLoading = ref(false)
const costSummaryError = ref<string | null>(null)
const costSummary = ref<ListCostSummary | null>(null)

// Methods
const refetchList = () => {
  listsStore.fetchListDetails(listId.value)
}

const focusNewItemInput = () => {
  // TODO: Focus the input in ListItemComposer
}

const handleItemAdded = (item: any) => {
  // Item was added through ListItemComposer
  // The component handles the API call internally
  console.log('Item added:', item)

  // Emit to other users for real-time updates
  emit('item:created', {
    listId: listId.value,
    item,
    user: authStore.user
  })
}

const handleCheckboxChange = (item: any, checked: boolean) => {
  if (!list.value) return

  listsStore.updateItem(String(list.value.id), item.id, {
    is_complete: checked,
    version: item.version
  }).then(() => {
    setupUndo({
      message: checked
        ? t('listDetailPage.undo.itemCompleted', { name: item.name })
        : t('listDetailPage.undo.itemUncompleted', { name: item.name }),
      action: () => handleCheckboxChange(item, !checked)
    })

    emit('item:updated', {
      listId: listId.value,
      itemId: item.id,
      changes: { is_complete: checked },
      user: authStore.user
    })
  }).catch(err => {
    console.error('Update item failed:', err)
  })
}

const handleMarkBought = async (item: any) => {
  selectedItems.value = [item]
  showPurchaseDialog.value = true
}

const handleUpdatePrice = (item: any, price: number) => {
  if (!list.value) return

  listsStore.updateItem(String(list.value.id), item.id, {
    price,
    version: item.version
  }).catch(err => {
    console.error('Update price failed:', err)
  })
}

const handleEditItem = (item: any) => {
  // TODO: Implement item editing
  console.log('Edit item:', item)
}

const handleUpdateQuantity = (item: any, quantity: number) => {
  if (!list.value) return

  listsStore.updateItem(list.value.id, item.id, {
    quantity: String(quantity),
    version: item.version
  }).catch(err => {
    console.error('Update quantity failed:', err)
  })
}

const handleDeleteItem = (item: any) => {
  if (!list.value) return

  listsStore.deleteItem(list.value.id, item.id, item.version).then(() => {
    setupUndo({
      message: t('listDetailPage.undo.itemDeleted', { name: item.name }),
      action: () => handleRestoreItem(item)
    })

    emit('item:deleted', {
      listId: listId.value,
      itemId: item.id,
      user: authStore.user
    })
  }).catch(err => {
    console.error('Delete item failed:', err)
  })
}

const handleRestoreItem = async (item: any) => {
  if (!list.value) return

  try {
    await listsStore.addItem(list.value.id, {
      name: item.name,
      quantity: item.quantity,
      category_id: item.category_id
    })
  } catch (error) {
    console.error('Failed to restore item:', error)
  }
}

const handleConfirmPurchase = () => {
  showPurchaseDialog.value = false

  // Mark selected items as complete and purchased
  selectedItems.value.forEach(item => {
    handleCheckboxChange(item, true)
  })

  selectedItems.value = []

  // TODO: Create expense from purchased items
}

const handleExpenseCreated = (expense: any) => {
  showExpenseModal.value = false
  console.log('Expense created:', expense)
}

const handleReceiptItems = (detectedItems: any[]) => {
  showReceiptScanner.value = false
  console.log('Receipt items detected:', detectedItems)
  // TODO: Add detected items to the list
}

const setupUndo = (action: Omit<UndoAction, 'timeLeft'>) => {
  if (undoAction.value) {
    clearTimeout(undoAction.value.timeLeft)
  }

  undoAction.value = {
    ...action,
    timeLeft: 100
  }

  // Start countdown
  const interval = setInterval(() => {
    if (undoAction.value) {
      undoAction.value.timeLeft -= 1
      if (undoAction.value.timeLeft <= 0) {
        undoAction.value = null
        clearInterval(interval)
      }
    }
  }, 100)

  // Auto-clear after 10 seconds
  setTimeout(() => {
    undoAction.value = null
    clearInterval(interval)
  }, 10000)
}

const executeUndo = () => {
  if (undoAction.value) {
    undoAction.value.action()
    undoAction.value = null
  }
}

const handleConflictResolved = (resolution: any) => {
  conflictResolution.resolveConflict(currentConflict.value?.id, resolution.strategy, resolution.data)
  showConflictDialog.value = false
}

// WebSocket event handlers
const handleItemUpdated = (payload: any) => {
  if (payload.listId === listId.value) {
    // Refetch list to get latest data
    refetchList()
  }
}

const handleItemClaimed = (payload: any) => {
  if (payload.listId === listId.value) {
    // Update UI to show item is claimed
    console.log('Item claimed by:', payload.user)
  }
}

const handleShoppingModeChanged = () => {
  emit('shopping:mode-changed', {
    listId: listId.value,
    mode: shoppingMode.value,
    user: authStore.user
  })
}



const toggleItemOptimistic = async (item: any) => {
  if (!list.value || item.updating) return

  const originalComplete = item.is_complete
  const originalCompletedBy = item.completed_by_id
  const originalCompletedAt = item.completed_at

  // Optimistic update
  item.is_complete = !item.is_complete
  item.updating = true

  if (item.is_complete) {
    item.completed_by_id = authStore.user?.id || null
    item.completed_at = new Date().toISOString()
  } else {
    item.completed_by_id = null
    item.completed_at = null
  }

  try {
    const response = await listsStore.updateItem(String(list.value.id), item.id, {
      is_complete: item.is_complete,
      version: item.version
    })

    // Update with server response
    Object.assign(item, response)
    item.updating = false

    setupUndo({
      message: item.is_complete
        ? t('listDetailPage.undo.itemCompleted', { name: item.name })
        : t('listDetailPage.undo.itemUncompleted', { name: item.name }),
      action: () => toggleItemOptimistic(item)
    })

    emit('item:updated', {
      listId: list.value.id,
      itemId: item.id,
      changes: { is_complete: item.is_complete },
      user: authStore.user
    })

  } catch (err: any) {
    // Rollback optimistic update
    item.is_complete = originalComplete
    item.completed_by_id = originalCompletedBy
    item.completed_at = originalCompletedAt
    item.updating = false

    if (err.response?.status === 409) {
      error.value = `Item "${item.name}" was modified by someone else. Please refresh and try again.`
    } else {
      error.value = err.response?.data?.detail || 'Failed to update item'
    }

    // Visual error feedback
    item.shakeError = true
    setTimeout(() => { item.shakeError = false }, 500)
  }
}

const deleteItemOptimistic = async (item: any) => {
  if (!list.value || item.updating) return

  const originalIndex = list.value.items.findIndex(i => i.id === item.id)
  if (originalIndex === -1) return

  // Optimistic update - remove from list
  list.value.items.splice(originalIndex, 1)

  try {
    await listsStore.deleteItem(list.value.id, item.id, item.version)

    setupUndo({
      message: t('listDetailPage.undo.itemDeleted', { name: item.name }),
      action: () => restoreItem(item, originalIndex)
    })

    emit('item:deleted', {
      listId: list.value.id,
      itemId: item.id,
      user: authStore.user
    })

  } catch (err: any) {
    // Rollback - restore item at original position
    list.value.items.splice(originalIndex, 0, item)

    if (err.response?.status === 409) {
      error.value = `Item "${item.name}" was modified by someone else. Please refresh and try again.`
    } else {
      error.value = err.response?.data?.detail || 'Failed to delete item'
    }
  }
}

const restoreItem = async (item: any, index: number) => {
  if (!list.value) return

  try {
    const response = await listsStore.addItem(String(list.value.id), {
      name: item.name,
      quantity: item.quantity,
      category_id: item.category_id
    })

    // Insert at specific position or end
    const insertIndex = Math.min(index, list.value.items.length)
    list.value.items.splice(insertIndex, 0, response)

  } catch (error) {
    console.error('Failed to restore item:', error)
  }
}

const completeAllItems = async () => {
  try {
    // await listsStore.completedItems() // This is not a function, so comment out
    console.log('All items completed')
  } catch (error) {
    console.error('Failed to complete all items:', error)
  }
}



// ItemsList Event Handlers
const handleReorderItems = async (orderedIds: number[]) => {
  if (!list.value) return

  try {
    await listsStore.reorderItems(String(list.value.id), orderedIds)
  } catch (error) {
    console.error('Failed to reorder items:', error)
  }
}

const handleAddItem = async () => {
  if (!newItem.value.name.trim() || !list.value) return

  try {
    await listsStore.addItem(String(list.value.id), {
      name: newItem.value.name.trim(),
      category_id: newItem.value.category_id
    })

    // Reset form
    newItem.value.name = ''
    newItem.value.category_id = null

  } catch (error) {
    console.error('Failed to add item:', error)
  }
}

const handleItemCheckboxChange = async (item: any, checked: boolean) => {
  await toggleItemOptimistic(item)
}

const handleUpdateItemPrice = async (item: any, price: number) => {
  if (!list.value) return

  try {
    await listsStore.updateItem(String(list.value.id), item.id, {
      price,
      version: item.version
    })
  } catch (error) {
    console.error('Failed to update price:', error)
  }
}

const handleUpdateItemQuantity = async (item: any, quantity: string | number) => {
  if (!list.value) return

  try {
    await listsStore.updateItem(String(list.value.id), item.id, {
      quantity: typeof quantity === 'number' ? String(quantity) : quantity,
      version: item.version
    })
  } catch (error) {
    console.error('Failed to update quantity:', error)
  }
}

const onListUpdated = () => {
  refetchList()
}

const onItemUpdated = () => {
  refetchList()
  showItemEdit.value = false
}

const formatPrice = (price: number | null | undefined) => {
  if (typeof price !== 'number') return ''
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  }).format(price)
}

const handleCreateCategory = async (categoryData: { name: string; group_id?: number | null }) => {
  try {
    await categoryStore.createCategory({
      name: categoryData.name,
      group_id: categoryData.group_id || undefined
    })
    // Refresh categories
    await categoryStore.fetchCategories(list.value?.group_id || undefined)
  } catch (error) {
    console.error('Failed to create category:', error)
  }
}

const openCostSummary = async () => {
  if (!list.value) return
  showCostSummaryDialog.value = true
  costSummaryLoading.value = true
  costSummaryError.value = null
  try {
    costSummary.value = await costService.getListCostSummary(list.value.id)
  } catch (err: any) {
    costSummaryError.value = err.response?.data?.detail || err.message || 'Failed to load cost summary'
  } finally {
    costSummaryLoading.value = false
  }
}

async function handleGenerateExpense() {
  if (!list.value) return

  try {
    costSummaryLoading.value = true
    const expense = await costService.generateExpenseFromListSummary(list.value.id)

    // Refresh the cost summary to show the new expense
    await openCostSummary()

    notificationStore.addNotification({
      type: 'success',
      message: 'Expense generated successfully from list items'
    })
  } catch (err: any) {
    notificationStore.addNotification({
      type: 'error',
      message: err.response?.data?.detail || 'Failed to generate expense'
    })
  } finally {
    costSummaryLoading.value = false
  }
}

// Lifecycle
onMounted(async () => {
  // Load list details
  await listsStore.fetchListDetails(listId.value)

  // Load categories
  await categoryStore.fetchCategories(list.value?.group_id || undefined)

  // Connect to WebSocket for real-time updates
  if (list.value?.group_id) {
    try {
      await connect(list.value.group_id)

      // Register event listeners
      on('item:updated', handleItemUpdated)
      on('item:claimed', handleItemClaimed)
      on('item:unclaimed', handleItemClaimed)
      on('shopping:mode-changed', (payload: any) => {
        if (payload.listId === listId.value && payload.user.id !== authStore.user?.id) {
          // Update active shoppers list
          const existingIndex = activeShoppers.value.findIndex(s => s.id === payload.user.id)
          if (payload.mode && existingIndex === -1) {
            activeShoppers.value.push(payload.user)
          } else if (!payload.mode && existingIndex !== -1) {
            activeShoppers.value.splice(existingIndex, 1)
          }
        }
      })
    } catch (error) {
      console.warn('WebSocket connection failed:', error)
    }
  }

  // Establish list-specific WebSocket connection for real-time item updates.
  if (listsStore.currentList?.id && authStore.accessToken) {
    listsStore.connectWebSocket(Number(listsStore.currentList.id), authStore.accessToken || '')
  }
})

onUnmounted(() => {
  // Cleanup WebSocket listeners
  off('item:updated', handleItemUpdated)
  off('item:claimed', handleItemClaimed)
  off('item:unclaimed', handleItemClaimed)

  // Disconnect list-specific socket
  listsStore.disconnectWebSocket()

  // Clear any pending undo actions
  undoAction.value = null
})

// Watch for shopping mode changes
watch(shoppingMode, handleShoppingModeChanged)
</script>

<style scoped>
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease;
}

.slide-down-enter-from,
.slide-down-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from,
.slide-up-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

.list-item-enter-active,
.list-item-leave-active {
  transition: all 0.3s ease;
}

.list-item-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.list-item-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

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

.loading-container {
  padding: 2rem 0;
}

.loading-header {
  margin-bottom: 2rem;

  .skeleton-line.title {
    height: 2rem;
    width: 60%;
    margin-bottom: 0.5rem;
  }

  .skeleton-line.subtitle {
    height: 1rem;
    width: 40%;
  }
}

.loading-items {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.skeleton-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: white;
  border-radius: 12px;
}

.skeleton-checkbox {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.5s infinite;
}

.skeleton-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.skeleton-line {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.5s infinite;
  border-radius: 4px;
  height: 1rem;

  &.short {
    width: 60%;
  }
}

.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background: white;
  border-radius: 16px;
  margin: 2rem 0;
}

.empty-illustration {
  margin-bottom: 1.5rem;

  .material-icons {
    font-size: 4rem;
    color: #d1d5db;
  }
}

.empty-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #374151;
  margin: 0 0 0.5rem 0;
}

.empty-subtitle {
  color: #6b7280;
  margin: 0;
}

.view-controls {
  margin-bottom: 1.5rem;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.control-label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #374151;
}

.view-toggle {
  display: flex;
  background: #f3f4f6;
  border-radius: 8px;
  padding: 0.25rem;
}

.toggle-option {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  border: none;
  background: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 0.875rem;

  &.active {
    background: white;
    color: #3b82f6;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  }
}

.count {
  background: rgba(0, 0, 0, 0.1);
  color: inherit;
  padding: 0.125rem 0.375rem;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 600;
}

.items-section {
  margin: 2rem 0;
}

.items-group {
  margin-bottom: 2rem;

  &:last-child {
    margin-bottom: 0;
  }
}

.group-title {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1.125rem;
  font-weight: 600;
  color: #374151;
  margin: 0 0 1rem 0;
}

.group-count {
  background: #e5e7eb;
  color: #6b7280;
  padding: 0.25rem 0.5rem;
  border-radius: 8px;
  font-size: 0.75rem;
  font-weight: 600;
}

.group-toggle {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
  background: none;
  border: none;
  cursor: pointer;
  margin-bottom: 1rem;
  text-align: left;

  .material-icons {
    color: #6b7280;
  }
}

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

  &.completed {
    opacity: 0.8;
  }
}

.item-card {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;

  &:hover {
    border-color: #d1d5db;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  &.incomplete {
    border-left: 4px solid #3b82f6;
  }

  &.complete {
    background: #f8f9fa;

    .item-name {
      text-decoration: line-through;
      color: #9ca3af;
    }
  }

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

  &.optimistic {
    background: #eff6ff;
    border-color: #3b82f6;
  }

  &.shake {
    animation: shake 0.5s ease-in-out;
  }
}

.item-content {
  display: flex;
  align-items: center;
  gap: 1rem;
  flex-grow: 1;
  cursor: pointer;
}

.item-checkbox-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-checkbox {
  width: 1.5rem;
  height: 1.5rem;
  opacity: 0;
  position: absolute;
}

.checkbox-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.5rem;
  height: 1.5rem;
  border-radius: 4px;
  transition: all 0.2s ease;

  .material-icons {
    font-size: 1.5rem;
    color: #d1d5db;

    &.checked {
      color: #10b981;
    }

    &.spinning {
      color: #3b82f6;
      animation: spin 1s linear infinite;
    }
  }
}

.item-details {
  flex-grow: 1;
  min-width: 0;
}

.item-name {
  display: block;
  font-size: 1rem;
  font-weight: 500;
  color: #374151;
  line-height: 1.4;
  margin-bottom: 0.25rem;
}

.item-metadata {
  display: flex;
  gap: 1rem;
  font-size: 0.875rem;
  color: #6b7280;
}

.item-actions {
  display: flex;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.item-card:hover .item-actions {
  opacity: 1;
}

.edit-btn,
.delete-btn {
  padding: 0.5rem;
  min-width: 2rem;
  height: 2rem;

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

@keyframes skeleton-shimmer {
  0% {
    background-position: 200% 0;
  }

  100% {
    background-position: -200% 0;
  }
}

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

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

@keyframes shake {

  0%,
  100% {
    transform: translateX(0);
  }

  25% {
    transform: translateX(-4px);
  }

  75% {
    transform: translateX(4px);
  }
}

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

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

.expand-enter-to,
.expand-leave-from {
  opacity: 1;
  max-height: 1000px;
}
</style>