<template>
    <div class="universal-fab-container">
        <!-- Main FAB Button -->
        <Transition name="fab-main" appear>
            <button ref="fabButton" class="fab-main" :class="{
                'is-open': isOpen,
                'has-priority': !!priorityAction,
                'is-contextual': isContextualMode
            }" @click="handleFabClick" @touchstart="handleTouchStart" @touchend="handleTouchEnd"
                @mousedown="handleMouseDown" @mouseup="handleMouseUp" @contextmenu.prevent="handleContextMenu"
                :aria-expanded="isOpen" :aria-label="fabAriaLabel"
                :aria-describedby="isOpen ? 'fab-actions-description' : undefined">
                <Transition name="fab-icon" mode="out-in">
                    <span v-if="isOpen" key="close" class="material-icons fab-icon">close</span>
                    <span v-else-if="priorityAction && !isContextualMode" key="priority"
                        class="material-icons fab-icon priority-icon">
                        {{ getPriorityIcon(priorityAction) }}
                    </span>
                    <span v-else key="add" class="material-icons fab-icon">add</span>
                </Transition>

                <!-- Priority indicator -->
                <div v-if="priorityAction && !isOpen" class="priority-indicator" :class="priorityAction.priority" />

                <!-- Context indicator -->
                <div v-if="isContextualMode && !isOpen" class="context-indicator" />
            </button>
        </Transition>

        <!-- Action Buttons -->
        <Transition name="fab-actions" @after-enter="onActionsEntered">
            <div v-if="isOpen" class="fab-actions-container" id="fab-actions-description">
                <button v-for="(action, index) in visibleActions" :key="action.id" class="fab-action" :class="{
                    'is-primary': action.isPrimary,
                    'is-contextual': action.contextual,
                    'is-smart': action.isSmart
                }" :style="getActionPosition(index)" @click="handleActionClick(action)"
                    @keydown="handleActionKeydown($event, action)" :aria-label="getActionAriaLabel(action)"
                    :title="action.description || action.label" tabindex="0">
                    <span class="material-icons action-icon">{{ action.icon }}</span>
                    <span class="fab-action-label">{{ action.label }}</span>

                    <!-- Usage indicator for frequently used actions -->
                    <div v-if="action.usageCount > 10" class="usage-indicator" />

                    <!-- Smart indicator for AI-suggested actions -->
                    <div v-if="action.isSmart" class="smart-indicator">
                        <span class="material-icons">auto_awesome</span>
                    </div>
                </button>
            </div>
        </Transition>

        <!-- Backdrop -->
        <Transition name="fab-backdrop">
            <div v-if="isOpen" class="fab-backdrop" @click="closeFAB" @touchstart="closeFAB" aria-hidden="true" />
        </Transition>

        <!-- Long press hint tooltip -->
        <Transition name="tooltip">
            <div v-if="showLongPressHint" class="long-press-hint">
                Hold for {{ primaryAction?.label || 'quick action' }}
            </div>
        </Transition>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { onClickOutside, useDeviceMotion, usePreferredReducedMotion } from '@vueuse/core'
import { useNotificationStore } from '@/stores/notifications'
import { usePersonalStatus } from '@/composables/usePersonalStatus'
import { useChoreStore } from '@/stores/choreStore'
import { useExpensesStore } from '@/stores/expensesStore'
import { useAuthStore } from '@/stores/auth'
import { useGroupStore } from '@/stores/groupStore'

interface FABAction {
    id: string
    label: string
    description?: string
    icon: string
    action: () => void | Promise<void>
    usageCount: number
    priority: number
    contextual?: boolean
    routeContexts?: string[]
    requiresAuth?: boolean
    isPrimary?: boolean
    isSmart?: boolean
    longPressAction?: () => void | Promise<void>
    keyboardShortcut?: string
}

interface PriorityAction {
    id: string
    type: 'chore' | 'expense' | 'debt' | 'overdue'
    priority: 'urgent' | 'high' | 'medium' | 'low'
    title: string
    description?: string
    dueDate?: Date
    amount?: number
    actionUrl: string
}

// Stores and composables
const router = useRouter()
const route = useRoute()
const notificationStore = useNotificationStore()
const authStore = useAuthStore()
const groupStore = useGroupStore()
const choreStore = useChoreStore()
const expensesStore = useExpensesStore()
const { personalStatus, priorityAction } = usePersonalStatus()

// State
const isOpen = ref(false)
const fabButton = ref<HTMLElement | null>(null)
const showLongPressHint = ref(false)
const isLongPressing = ref(false)
const longPressTimer = ref<number | null>(null)
const touchStartTime = ref(0)
const mouseDownTime = ref(0)
const isPerformingAction = ref(false)

// Accessibility and performance
const reduceMotion = usePreferredReducedMotion()
const deviceMotion = useDeviceMotion()

// Usage tracking with intelligent defaults
const usageStats = ref<Record<string, number>>({
    'add-expense': 45,
    'complete-chore': 25,
    'add-to-list': 15,
    'scan-receipt': 8,
    'create-list': 4,
    'invite-member': 3
})

// Smart contextual mode detection
const isContextualMode = computed(() => {
    // Enable contextual mode based on route and user behavior
    const contextualRoutes = ['/lists', '/chores', '/expenses', '/groups']
    return contextualRoutes.some(path => route.path.includes(path))
})

// Dynamic action definitions with context awareness
const allActions = computed<FABAction[]>(() => {
    const currentRoute = route.name as string
    const userId = authStore.user?.id
    const hasActiveGroup = !!groupStore.currentGroupId

    return [
        // Primary expense action - most used across all contexts
        {
            id: 'add-expense',
            label: 'Add Expense',
            description: 'Create a new expense and split with household members',
            icon: 'receipt_long',
            priority: 1,
            usageCount: usageStats.value['add-expense'] || 0,
            isPrimary: true,
            requiresAuth: true,
            routeContexts: ['Dashboard', 'Expenses', 'GroupExpenses'],
            action: async () => {
                await navigateWithOptimism('/expenses/new')
            },
            longPressAction: async () => {
                // Quick expense with last amount
                emit('quick-expense')
            }
        },

        // Smart chore completion - context aware
        {
            id: 'complete-chore',
            label: priorityAction.value ? `Complete: ${priorityAction.value.title}` : 'Complete Chore',
            description: priorityAction.value ?
                `Mark "${priorityAction.value.title}" as complete` :
                'Mark a chore as complete',
            icon: priorityAction.value?.priority === 'urgent' ? 'priority_high' : 'task_alt',
            priority: priorityAction.value ? 1 : 3,
            usageCount: usageStats.value['complete-chore'] || 0,
            contextual: true,
            isSmart: !!priorityAction.value,
            requiresAuth: true,
            routeContexts: ['Dashboard', 'Chores', 'GroupChores'],
            action: async () => {
                if (priorityAction.value) {
                    await router.push(priorityAction.value.actionUrl)
                } else {
                    await navigateWithOptimism('/chores')
                }
            }
        },

        // Context-aware list action
        {
            id: 'add-to-list',
            label: currentRoute.includes('List') ? 'Add Item' : 'Quick Add',
            description: 'Add item to shopping list or create new list',
            icon: currentRoute.includes('List') ? 'add' : 'add_shopping_cart',
            priority: 2,
            usageCount: usageStats.value['add-to-list'] || 0,
            contextual: currentRoute.includes('List'),
            routeContexts: ['PersonalLists', 'GroupLists', 'ListDetail'],
            action: async () => {
                if (route.name === 'ListDetail') {
                    emit('add-item-to-current-list')
                } else {
                    await navigateWithOptimism('/lists')
                }
            }
        },

        // Smart receipt scanning
        {
            id: 'scan-receipt',
            label: 'Scan Receipt',
            description: 'Scan receipt to automatically create expense and items',
            icon: 'qr_code_scanner',
            priority: 3,
            usageCount: usageStats.value['scan-receipt'] || 0,
            isSmart: true,
            routeContexts: ['Dashboard', 'Expenses', 'PersonalLists'],
            action: async () => {
                emit('scan-receipt')
            }
        },

        // Group context actions
        {
            id: 'create-list',
            label: hasActiveGroup ? 'New Group List' : 'New List',
            description: 'Create a new shopping or todo list',
            icon: 'playlist_add',
            priority: 4,
            usageCount: usageStats.value['create-list'] || 0,
            contextual: currentRoute.includes('List') || hasActiveGroup,
            action: async () => {
                emit('create-list')
            }
        },

        // Social action - context dependent
        {
            id: 'invite-member',
            label: 'Invite Member',
            description: 'Invite someone to join your household',
            icon: 'person_add',
            priority: 5,
            usageCount: usageStats.value['invite-member'] || 0,
            contextual: hasActiveGroup,
            requiresAuth: true,
            routeContexts: ['Groups', 'GroupDetail', 'Dashboard'],
            action: async () => {
                emit('invite-member')
            }
        },

        // Emergency/quick access actions
        {
            id: 'settings',
            label: 'Quick Settings',
            description: 'Access account and household settings',
            icon: 'settings',
            priority: 6,
            usageCount: usageStats.value['settings'] || 0,
            contextual: false,
            action: async () => {
                await navigateWithOptimism('/account')
            }
        }
    ].filter(action => {
        // Filter based on auth requirements
        if (action.requiresAuth && !authStore.isAuthenticated) return false

        // Filter based on route context if specified
        if (action.routeContexts && !action.routeContexts.includes(currentRoute)) {
            return action.contextual !== true // Allow non-contextual actions
        }

        return true
    })
})

// Intelligent action sorting and limiting
const visibleActions = computed(() => {
    const currentRoute = route.name as string
    const maxActions = isContextualMode.value ? 5 : 4

    return allActions.value
        .slice()
        .sort((a, b) => {
            // Boost smart/priority actions
            if (a.isSmart && !b.isSmart) return -1
            if (!a.isSmart && b.isSmart) return 1

            // Boost contextual actions in contextual mode
            if (isContextualMode.value) {
                if (a.contextual && !b.contextual) return -1
                if (!a.contextual && b.contextual) return 1
            }

            // Primary sort: usage count (with recency weighting)
            const aUsage = a.usageCount + (a.isPrimary ? 100 : 0)
            const bUsage = b.usageCount + (b.isPrimary ? 100 : 0)

            if (bUsage !== aUsage) return bUsage - aUsage

            // Secondary sort: priority
            return a.priority - b.priority
        })
        .slice(0, maxActions)
})

// Primary action for long press
const primaryAction = computed(() => {
    return visibleActions.value.find(a => a.isPrimary) || visibleActions.value[0]
})

// FAB button accessibility
const fabAriaLabel = computed(() => {
    if (isOpen.value) return 'Close quick actions menu'
    if (priorityAction.value) return `Quick actions (${priorityAction.value.title} pending)`
    return 'Open quick actions menu'
})

// Smart positioning for radial layout
const getActionPosition = (index: number) => {
    const totalActions = visibleActions.value.length
    const isMobile = typeof window !== 'undefined' && window.innerWidth < 640

    if (isMobile) {
        // Vertical stack on mobile for easier thumb access
        const spacing = 60 // 60px between items
        const y = -(spacing * (index + 1)) + 4 // +4 to better align with FAB center
        return {
            transform: `translateY(${y}px)`,
            transitionDelay: `${index * 40}ms`
        }
    } else {
        // Radial layout on desktop, opening up and to the left
        const radius = 85
        const angleRange = Math.PI / 2 // 90 degree arc

        // Start from -90deg (up) and move towards -180deg (left)
        const startAngle = -Math.PI / 2
        const angleStep = angleRange / Math.max(totalActions - 1, 1)
        const angle = startAngle - (angleStep * index)

        const x = Math.cos(angle) * radius
        const y = Math.sin(angle) * radius

        return {
            transform: `translate(${x}px, ${y}px)`,
            transitionDelay: `${index * 40}ms`
        }
    }
}

// Enhanced interaction handlers
const handleFabClick = () => {
    if (isLongPressing.value) return // Ignore if long press is active

    if (isOpen.value) {
        closeFAB()
    } else {
        openFAB()
    }
}

const handleTouchStart = (event: TouchEvent) => {
    touchStartTime.value = Date.now()
    startLongPressTimer()
}

const handleTouchEnd = (event: TouchEvent) => {
    const touchDuration = Date.now() - touchStartTime.value
    clearLongPressTimer()

    if (touchDuration < 200 && !isLongPressing.value) {
        // Quick tap - toggle menu
        handleFabClick()
    }
}

const handleMouseDown = (event: MouseEvent) => {
    mouseDownTime.value = Date.now()
    if (event.button === 0) { // Left click only
        startLongPressTimer()
    }
}

const handleMouseUp = (event: MouseEvent) => {
    clearLongPressTimer()
}

const handleContextMenu = (event: Event) => {
    event.preventDefault()
    if (primaryAction.value?.longPressAction) {
        primaryAction.value.longPressAction()
        addHapticFeedback('medium')
    }
}

const startLongPressTimer = () => {
    if (longPressTimer.value) clearTimeout(longPressTimer.value)

    // Show hint after 300ms
    setTimeout(() => {
        if (!isOpen.value) showLongPressHint.value = true
    }, 300)

    // Trigger long press after 800ms
    longPressTimer.value = window.setTimeout(() => {
        if (!isOpen.value && primaryAction.value) {
            isLongPressing.value = true
            showLongPressHint.value = false

            if (primaryAction.value.longPressAction) {
                primaryAction.value.longPressAction()
            } else {
                primaryAction.value.action()
            }

            addHapticFeedback('medium')

            // Reset after action
            setTimeout(() => {
                isLongPressing.value = false
            }, 100)
        }
    }, 800)
}

const clearLongPressTimer = () => {
    if (longPressTimer.value) {
        clearTimeout(longPressTimer.value)
        longPressTimer.value = null
    }
    showLongPressHint.value = false
}

const openFAB = () => {
    isOpen.value = true
    addHapticFeedback('light')

    // Focus management for accessibility
    nextTick(() => {
        const firstAction = document.querySelector('.fab-action') as HTMLElement
        firstAction?.focus()
    })
}

const closeFAB = () => {
    isOpen.value = false
    showLongPressHint.value = false
    fabButton.value?.focus() // Return focus to FAB
}

const handleActionClick = async (action: FABAction) => {
    if (isPerformingAction.value) return

    isPerformingAction.value = true
    addHapticFeedback('light')

    try {
        incrementUsage(action.id)
        await action.action()
        closeFAB()

        notificationStore.addNotification({
            type: 'success',
            message: `${action.label} opened`,
            duration: 2000
        })
    } catch (error) {
        console.error('Action failed:', error)
        notificationStore.addNotification({
            type: 'error',
            message: `Failed to execute ${action.label}`,
            duration: 4000
        })
    } finally {
        isPerformingAction.value = false
    }
}

const handleActionKeydown = (event: KeyboardEvent, action: FABAction) => {
    if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault()
        handleActionClick(action)
    } else if (event.key === 'Escape') {
        event.preventDefault()
        closeFAB()
    } else if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
        event.preventDefault()
        focusNextAction(event.target as HTMLElement)
    } else if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
        event.preventDefault()
        focusPreviousAction(event.target as HTMLElement)
    }
}

const focusNextAction = (currentElement: HTMLElement) => {
    const actions = Array.from(document.querySelectorAll('.fab-action')) as HTMLElement[]
    const currentIndex = actions.indexOf(currentElement)
    const nextIndex = (currentIndex + 1) % actions.length
    actions[nextIndex]?.focus()
}

const focusPreviousAction = (currentElement: HTMLElement) => {
    const actions = Array.from(document.querySelectorAll('.fab-action')) as HTMLElement[]
    const currentIndex = actions.indexOf(currentElement)
    const prevIndex = currentIndex === 0 ? actions.length - 1 : currentIndex - 1
    actions[prevIndex]?.focus()
}

// Utility functions
const incrementUsage = (actionId: string) => {
    usageStats.value[actionId] = (usageStats.value[actionId] || 0) + 1
    localStorage.setItem('fab-usage-stats-v2', JSON.stringify(usageStats.value))
}

const addHapticFeedback = (intensity: 'light' | 'medium' | 'heavy' = 'light') => {
    if ('vibrate' in navigator) {
        const patterns = {
            light: 30,
            medium: 50,
            heavy: [50, 10, 50]
        }
        navigator.vibrate(patterns[intensity])
    }
}

const navigateWithOptimism = async (path: string) => {
    // Show immediate feedback
    isPerformingAction.value = true
    await router.push(path)
    isPerformingAction.value = false
}

const getPriorityIcon = (action: PriorityAction) => {
    const iconMap = {
        urgent: 'priority_high',
        high: 'schedule',
        medium: 'task_alt',
        low: 'task_alt'
    }
    return iconMap[action.priority] || 'task_alt'
}

const getActionAriaLabel = (action: FABAction) => {
    let label = action.label
    if (action.description) label += `. ${action.description}`
    if (action.keyboardShortcut) label += `. Keyboard shortcut: ${action.keyboardShortcut}`
    return label
}

const onActionsEntered = () => {
    // Could add screen reader announcement here if needed
    // For now, the ARIA attributes handle accessibility
}

// Keyboard shortcuts
const handleGlobalKeydown = (event: KeyboardEvent) => {
    // Ctrl/Cmd + Space to toggle FAB
    if ((event.ctrlKey || event.metaKey) && event.code === 'Space') {
        event.preventDefault()
        if (isOpen.value) closeFAB()
        else openFAB()
    }

    // Escape to close
    if (event.key === 'Escape' && isOpen.value) {
        closeFAB()
    }

    // Number keys for direct action access when open
    if (isOpen.value && /^[1-5]$/.test(event.key)) {
        const actionIndex = parseInt(event.key) - 1
        const action = visibleActions.value[actionIndex]
        if (action) {
            event.preventDefault()
            handleActionClick(action)
        }
    }
}

// Click outside handler
onClickOutside(fabButton, () => {
    if (isOpen.value) closeFAB()
})

// Lifecycle
onMounted(() => {
    document.addEventListener('keydown', handleGlobalKeydown)

    // Load usage stats from localStorage
    const savedStats = localStorage.getItem('fab-usage-stats-v2')
    if (savedStats) {
        try {
            const parsed = JSON.parse(savedStats)
            usageStats.value = { ...usageStats.value, ...parsed }
        } catch (e) {
            console.warn('Failed to load FAB usage stats:', e)
        }
    }
})

onUnmounted(() => {
    document.removeEventListener('keydown', handleGlobalKeydown)
    clearLongPressTimer()
})

// Watch for route changes to close FAB
watch(() => route.path, () => {
    if (isOpen.value) closeFAB()
})

// Define emits
const emit = defineEmits<{
    'scan-receipt': []
    'create-list': []
    'invite-member': []
    'add-item-to-current-list': []
    'quick-expense': []
}>()
</script>

<style scoped>
.universal-fab-container {
    position: fixed;
    bottom: 24px;
    right: 24px;
    z-index: 1000;

    /* Improved z-index stacking */
    --fab-z-index: 1000;
    --fab-backdrop-z-index: 999;
    --fab-actions-z-index: 1001;
}

.fab-main {
    @apply relative w-14 h-14 rounded-full shadow-floating;
    @apply bg-primary-500 text-white;
    @apply flex items-center justify-center;
    @apply focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/50 focus-visible:ring-offset-2;
    @apply active:scale-95 transform-gpu;

    transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);
    border: none;
    cursor: pointer;
    user-select: none;
    -webkit-tap-highlight-color: transparent;
}

.fab-main:hover {
    @apply bg-primary-600 shadow-strong scale-105;
}

.fab-main.is-open {
    @apply bg-error-500 rotate-45;
    z-index: var(--fab-actions-z-index);
}

.fab-main.is-open:hover {
    @apply bg-error-600;
}

.fab-main.has-priority {
    @apply bg-warning-500;
    animation: gentle-pulse 2s ease-in-out infinite;
}

.fab-main.has-priority:hover {
    @apply bg-warning-600;
}

.fab-main.is-contextual {
    @apply bg-secondary;
}

.fab-main.is-contextual:hover {
    filter: brightness(0.9);
}

.fab-icon {
    @apply text-lg leading-none transition-all duration-150;
}

.priority-icon {
    @apply text-white;
    filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3));
}

.priority-indicator {
    @apply absolute -top-1 -right-1 w-3 h-3 rounded-full;

    &.urgent {
        @apply bg-error-500;
        animation: urgent-pulse 1s ease-in-out infinite;
    }

    &.high {
        @apply bg-warning-500;
    }

    &.medium {
        @apply bg-primary-500;
    }

    &.low {
        @apply bg-neutral-400;
    }
}

.context-indicator {
    @apply absolute -top-1 -right-1 w-3 h-3 rounded-full bg-warning-400;
}

.fab-actions-container {
    position: absolute;
    bottom: 0;
    right: 0;
    pointer-events: none;
    z-index: var(--fab-actions-z-index);
}

.fab-action {
    @apply absolute w-12 h-12 rounded-full shadow-medium;
    @apply bg-white text-neutral-700 border border-neutral-200;
    @apply flex items-center justify-center;
    @apply focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/50;
    @apply active:scale-90 transform-gpu;

    transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);
    bottom: 14px;
    right: 14px;
    border: none;
    cursor: pointer;
    pointer-events: all;
    user-select: none;
    -webkit-tap-highlight-color: transparent;
}

.fab-action:hover {
    @apply bg-primary-50 text-primary-600 shadow-strong scale-110;
}

.fab-action.is-primary {
    @apply bg-primary-100 text-primary-700 ring-2 ring-primary-200;
}

.fab-action.is-contextual {
    @apply bg-warning-50 text-warning-700;
}

.fab-action.is-smart {
    @apply bg-gradient-to-br from-purple-50 to-blue-50 text-purple-700;
    box-shadow: 0 4px 12px rgba(139, 92, 246, 0.2);
}

.action-icon {
    @apply text-lg leading-none;
}

.fab-action-label {
    @apply absolute top-full mt-2 text-xs font-medium whitespace-nowrap;
    @apply bg-neutral-900 text-white px-2 py-1 rounded;
    @apply opacity-0 pointer-events-none;
    @apply transition-opacity duration-150;
    z-index: 1002;
}

.fab-action:hover .fab-action-label,
.fab-action:focus .fab-action-label {
    @apply opacity-100;
}

.usage-indicator {
    @apply absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full bg-green-400;
}

.smart-indicator {
    @apply absolute -top-1 -right-1 w-4 h-4 rounded-full;
    @apply bg-gradient-to-r from-purple-400 to-blue-400;
    @apply flex items-center justify-center;
}

.smart-indicator .material-icons {
    @apply text-xs text-white;
}

.fab-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(2px);
    z-index: var(--fab-backdrop-z-index);
}

.long-press-hint {
    @apply absolute bottom-full mb-2 left-1/2 transform -translate-x-1/2;
    @apply bg-neutral-900 text-white text-xs px-3 py-1 rounded-full;
    @apply whitespace-nowrap;
    z-index: 1002;
}

/* Enhanced animations with reduced motion support */
.fab-main-enter-active,
.fab-main-leave-active {
    transition: all 300ms cubic-bezier(0.34, 1.56, 0.64, 1);
}

.fab-main-enter-from,
.fab-main-leave-to {
    opacity: 0;
    transform: scale(0) rotate(180deg);
}

.fab-icon-enter-active,
.fab-icon-leave-active {
    transition: all 150ms cubic-bezier(0.4, 0, 0.2, 1);
}

.fab-icon-enter-from,
.fab-icon-leave-to {
    opacity: 0;
    transform: rotate(90deg) scale(0.8);
}

.fab-actions-enter-active {
    transition: opacity 200ms ease-out;
}

.fab-actions-enter-active .fab-action {
    transition: all 300ms cubic-bezier(0.34, 1.56, 0.64, 1);
}

.fab-actions-leave-active {
    transition: opacity 150ms ease-in;
}

.fab-actions-leave-active .fab-action {
    transition: all 150ms ease-in;
}

.fab-actions-enter-from,
.fab-actions-leave-to {
    opacity: 0;
}

.fab-actions-enter-from .fab-action,
.fab-actions-leave-to .fab-action {
    opacity: 0;
    transform: translate(0, 0) scale(0.3);
}

.fab-backdrop-enter-active,
.fab-backdrop-leave-active {
    transition: all 200ms ease-out;
}

.fab-backdrop-enter-from,
.fab-backdrop-leave-to {
    opacity: 0;
    backdrop-filter: blur(0);
}

.tooltip-enter-active,
.tooltip-leave-active {
    transition: all 150ms ease-out;
}

.tooltip-enter-from,
.tooltip-leave-to {
    opacity: 0;
    transform: translateX(-50%) translateY(8px) scale(0.9);
}

/* Animation keyframes */
@keyframes gentle-pulse {

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

    50% {
        transform: scale(1.05);
    }
}

@keyframes urgent-pulse {

    0%,
    100% {
        opacity: 1;
        transform: scale(1);
    }

    50% {
        opacity: 0.7;
        transform: scale(1.2);
    }
}

/* Mobile optimizations */
@media (max-width: 640px) {
    .universal-fab-container {
        bottom: 90px;
        /* Above mobile navigation */
        right: 16px;
    }

    .fab-main {
        @apply w-12 h-12;
    }

    .fab-action {
        @apply w-10 h-10;
    }

    .fab-action-label {
        display: none;
        /* Reduce clutter on mobile */
    }

    .long-press-hint {
        @apply text-xs px-2 py-1;
    }
}

/* High contrast mode support */
@media (prefers-contrast: high) {
    .fab-main {
        border: 2px solid;
    }

    .fab-action {
        border: 2px solid;
    }
}

/* Reduced motion support */
@media (prefers-reduced-motion: reduce) {

    .fab-main,
    .fab-action,
    .fab-backdrop,
    .fab-icon {
        transition: none;
    }

    .fab-main.is-open {
        transform: none;
    }

    .fab-action:hover {
        transform: none;
    }

    .priority-indicator,
    .smart-indicator {
        animation: none;
    }
}

/* Focus improvements for better accessibility */
.fab-main:focus-visible,
.fab-action:focus-visible {
    outline: 2px solid #3B82F6;
    outline-offset: 2px;
}

/* Loading state */
.fab-main.is-loading {
    @apply cursor-wait;
}

.fab-main.is-loading .fab-icon {
    animation: spin 1s linear infinite;
}

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

    to {
        transform: rotate(360deg);
    }
}
</style>