<template>
  <div class="p-6">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="text-3xl font-bold">Projects</h1>
        <p class="text-muted-foreground">Manage your VFX projects and production workflows</p>
      </div>
      <div class="flex items-center gap-3">
        <!-- Search -->
        <div class="relative">
          <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            v-model="searchQuery"
            placeholder="Search projects..."
            class="pl-10 w-64"
          />
        </div>
        <!-- Filter -->
        <Select :model-value="statusFilter" @update:model-value="(value) => statusFilter = value as string">
          <SelectTrigger class="w-40">
            <SelectValue placeholder="All Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="planning">Planning</SelectItem>
            <SelectItem value="in_progress">In Progress</SelectItem>
            <SelectItem value="on_hold">On Hold</SelectItem>
            <SelectItem value="completed">Completed</SelectItem>
            <SelectItem value="cancelled">Cancelled</SelectItem>
          </SelectContent>
        </Select>
        <!-- Create Project Button -->
        <Button @click="openCreateDialog" v-if="canCreateProjects">
          <Plus class="h-4 w-4 mr-2" />
          New Project
        </Button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="projectsStore.isLoading" class="flex items-center justify-center py-12">
      <div class="flex items-center gap-2">
        <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
        <span class="text-muted-foreground">Loading projects...</span>
      </div>
    </div>

    <!-- Error State -->
    <div v-else-if="projectsStore.error" class="text-center py-12">
      <AlertCircle class="h-12 w-12 mx-auto text-destructive mb-4" />
      <h3 class="text-lg font-semibold mb-2">Failed to load projects</h3>
      <p class="text-muted-foreground mb-4">{{ projectsStore.error }}</p>
      <Button @click="loadProjects" variant="outline">
        <RefreshCw class="h-4 w-4 mr-2" />
        Try Again
      </Button>
    </div>

    <!-- Projects Grid -->
    <div v-else-if="filteredProjects.length > 0" class="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
      <Card 
        v-for="project in filteredProjects" 
        :key="project.id"
        :data-project-id="project.id"
        class="cursor-pointer hover:shadow-md transition-shadow overflow-hidden"
        @click="selectProject(project)"
      >
        <!-- Project Thumbnail -->
        <div class="relative w-full h-40 bg-muted overflow-hidden">
          <!-- Loading Skeleton -->
          <div
            v-if="isThumbnailLoading(project.id)"
            class="w-full h-full animate-pulse bg-gradient-to-br from-muted to-muted/50"
          >
            <div class="w-full h-full flex items-center justify-center">
              <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary/30"></div>
            </div>
          </div>
          
          <!-- Thumbnail Image with Lazy Loading -->
          <img
            v-else-if="getThumbnailUrl(project.id)"
            :src="getThumbnailUrl(project.id)"
            :alt="project.name"
            loading="lazy"
            class="w-full h-full object-cover transition-opacity duration-300"
            :class="{ 'opacity-0': !isThumbnailLoaded(project.id), 'opacity-100': isThumbnailLoaded(project.id) }"
            @load="onThumbnailLoad(project.id)"
            @error="onThumbnailError(project.id)"
          />
          
          <!-- Fallback Placeholder -->
          <div
            v-else
            class="w-full h-full flex items-center justify-center bg-gradient-to-br from-primary/10 to-primary/5"
          >
            <div class="text-center">
              <div class="text-4xl font-bold text-primary/40 mb-1">
                {{ getProjectInitials(project.name) }}
              </div>
              <FolderOpen class="h-8 w-8 mx-auto text-primary/30" />
            </div>
          </div>
          
          <!-- Status Badge Overlay -->
          <div class="absolute top-2 right-2">
            <Badge :variant="getStatusVariant(project.status)">
              {{ formatStatus(project.status) }}
            </Badge>
          </div>
        </div>

        <CardHeader class="pb-3">
          <div class="flex items-start justify-between">
            <div class="flex-1">
              <CardTitle class="text-lg">{{ project.name }}</CardTitle>
            </div>
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" @click.stop>
                  <MoreHorizontal class="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem @click.stop="editProject(project)">
                  <Edit class="h-4 w-4 mr-2" />
                  Edit Project
                </DropdownMenuItem>
                <DropdownMenuItem @click.stop="manageMembers(project)">
                  <Users class="h-4 w-4 mr-2" />
                  Manage Members
                </DropdownMenuItem>
                <DropdownMenuItem @click.stop="manageTechnicalSpecs(project)">
                  <Settings class="h-4 w-4 mr-2" />
                  Technical Specs
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem 
                  @click.stop="deleteProject(project)"
                  class="text-destructive"
                  v-if="canDeleteProjects"
                >
                  <Trash2 class="h-4 w-4 mr-2" />
                  Delete Project
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </div>
        </CardHeader>
        <CardContent>
          <!-- Project Info -->
          <div class="space-y-2 mb-4">
            <div class="flex items-center justify-between text-sm">
              <span class="text-muted-foreground">Code:</span>
              <span class="font-mono font-medium">{{ project.code_name }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
              <span class="text-muted-foreground">Client:</span>
              <span class="font-medium">{{ project.client_name }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
              <span class="text-muted-foreground">Type:</span>
              <Badge variant="outline">{{ formatProjectType(project.project_type) }}</Badge>
            </div>
          </div>
          
          <p class="text-sm text-muted-foreground mb-4" v-if="project.description">
            {{ project.description }}
          </p>
          
          <!-- Progress Indicators -->
          <div class="space-y-3">
            <div class="flex items-center justify-between text-sm">
              <span class="text-muted-foreground">Members</span>
              <span class="font-medium">{{ project.member_count || 0 }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
              <span class="text-muted-foreground">Episodes</span>
              <span class="font-medium">{{ project.episode_count || 0 }}</span>
            </div>
            <div class="flex items-center justify-between text-sm">
              <span class="text-muted-foreground">Assets</span>
              <span class="font-medium">{{ project.asset_count || 0 }}</span>
            </div>
          </div>

          <!-- Dates -->
          <div class="mt-4 pt-4 border-t">
            <div class="flex items-center justify-between text-xs text-muted-foreground">
              <span v-if="project.start_date">Started {{ formatDate(project.start_date) }}</span>
              <span v-if="project.end_date">Due {{ formatDate(project.end_date) }}</span>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>

    <!-- Empty State -->
    <div v-else class="text-center py-12">
      <FolderOpen class="h-12 w-12 mx-auto text-muted-foreground mb-4" />
      <h3 class="text-lg font-semibold mb-2">
        {{ searchQuery || statusFilter !== 'all' ? 'No projects found' : 'No projects yet' }}
      </h3>
      <p class="text-muted-foreground mb-4">
        {{ searchQuery || statusFilter !== 'all' 
          ? 'Try adjusting your search or filter criteria' 
          : 'Create your first project to get started with production management' 
        }}
      </p>
      <Button @click="openCreateDialog" v-if="canCreateProjects && !searchQuery && statusFilter === 'all'">
        <Plus class="h-4 w-4 mr-2" />
        Create Project
      </Button>
    </div>

    <!-- Create/Edit Project Dialog -->
    <Dialog :open="showCreateDialog" @update:open="showCreateDialog = $event">
      <DialogContent class="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>{{ editingProject ? 'Edit Project' : 'Create New Project' }}</DialogTitle>
          <DialogDescription>
            {{ editingProject ? 'Update project information' : 'Set up a new VFX project for your team' }}
          </DialogDescription>
        </DialogHeader>
        
        <form @submit.prevent="submitProject" class="space-y-4">
          <div>
            <Label for="name">Project Name</Label>
            <Input
              id="name"
              v-model="projectForm.name"
              placeholder="Enter project name"
              required
            />
          </div>
          
          <div class="grid grid-cols-2 gap-4">
            <div>
              <Label for="code_name">Code Name</Label>
              <Input
                id="code_name"
                v-model="projectForm.code_name"
                placeholder="e.g. PROJ_001"
                required
              />
            </div>
            <div>
              <Label for="client_name">Client Name</Label>
              <Input
                id="client_name"
                v-model="projectForm.client_name"
                placeholder="Enter client or studio name"
                required
              />
            </div>
          </div>
          
          <div>
            <Label for="project_type">Project Type</Label>
            <Select :model-value="projectForm.project_type" @update:model-value="(value) => projectForm.project_type = value as 'tv' | 'cinema' | 'game'">
              <SelectTrigger>
                <SelectValue placeholder="Select project type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="tv">TV Series</SelectItem>
                <SelectItem value="cinema">Cinema/Film</SelectItem>
                <SelectItem value="game">Game</SelectItem>
              </SelectContent>
            </Select>
          </div>
          
          <div>
            <Label for="description">Description</Label>
            <Textarea
              id="description"
              v-model="projectForm.description"
              placeholder="Brief description of the project"
              rows="3"
            />
          </div>
          
          <div class="grid grid-cols-2 gap-4">
            <div>
              <Label for="status">Status</Label>
              <Select :model-value="projectForm.status" @update:model-value="(value) => projectForm.status = value as 'planning' | 'in_progress' | 'on_hold' | 'completed' | 'cancelled'">
                <SelectTrigger>
                  <SelectValue placeholder="Select status" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="planning">Planning</SelectItem>
                  <SelectItem value="in_progress">In Progress</SelectItem>
                  <SelectItem value="on_hold">On Hold</SelectItem>
                  <SelectItem value="completed">Completed</SelectItem>
                  <SelectItem value="cancelled">Cancelled</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div class="grid grid-cols-2 gap-4">
            <div>
              <Label for="start_date">Start Date</Label>
              <DatePicker
                v-model="projectForm.start_date"
                placeholder="Select start date"
              />
              <p class="text-xs text-muted-foreground mt-1">Project start date (defaults to today)</p>
            </div>
            <div>
              <Label for="end_date">End Date</Label>
              <DatePicker
                v-model="projectForm.end_date"
                placeholder="Select end date"
                :min="projectForm.start_date"
              />
              <p class="text-xs text-muted-foreground mt-1">Expected completion date (defaults to 1 month from today)</p>
            </div>
          </div>
          
          <!-- Date validation error -->
          <div v-if="!isDateRangeValid" class="text-sm text-destructive">
            End date must be after or equal to start date
          </div>
          
          <DialogFooter>
            <Button type="button" variant="outline" @click="cancelProjectForm">
              Cancel
            </Button>
            <Button type="submit" :disabled="isSubmitting || !isDateRangeValid">
              <div v-if="isSubmitting" class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
              {{ editingProject ? 'Update Project' : 'Create Project' }}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>

    <!-- Project Members Dialog -->
    <Dialog :open="showMembersDialog" @update:open="showMembersDialog = $event">
      <DialogContent class="sm:max-w-2xl">
        <DialogHeader>
          <DialogTitle>Manage Project Members</DialogTitle>
          <DialogDescription>
            Add or remove team members and assign department roles for {{ selectedProject?.name }}
          </DialogDescription>
        </DialogHeader>
        
        <ProjectMembersManager 
          v-if="selectedProject && showMembersDialog"
          :project="selectedProject"
          @close="showMembersDialog = false"
        />
      </DialogContent>
    </Dialog>

    <!-- Delete Confirmation Dialog -->
    <AlertDialog :open="showDeleteDialog" @update:open="showDeleteDialog = $event">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete Project</AlertDialogTitle>
          <AlertDialogDescription>
            Are you sure you want to delete "{{ projectToDelete?.name }}"? This action cannot be undone and will remove all associated episodes, shots, and tasks.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction @click="confirmDelete" class="bg-destructive text-destructive-foreground hover:bg-destructive/90">
            Delete Project
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Search, Plus, MoreHorizontal, Edit, Users, Trash2, FolderOpen, 
  AlertCircle, RefreshCw, Settings
} from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { DatePicker } from '@/components/ui/date-picker'
import { 
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue 
} from '@/components/ui/select'
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, 
  DropdownMenuSeparator, DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import {
  Dialog, DialogContent, DialogDescription, DialogFooter, 
  DialogHeader, DialogTitle
} from '@/components/ui/dialog'
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, 
  AlertDialogContent, AlertDialogDescription, AlertDialogFooter, 
  AlertDialogHeader, AlertDialogTitle
} from '@/components/ui/alert-dialog'
import { useToast } from '@/components/ui/toast/use-toast'
import { useProjectsStore } from '@/stores/projects'
import { useAuthStore } from '@/stores/auth'
import ProjectMembersManager from '@/components/project/ProjectMembersManager.vue'
import type { Project } from '@/stores/projects'
import { apiClient } from '@/services/api'

const router = useRouter()
const { toast } = useToast()
const projectsStore = useProjectsStore()
const authStore = useAuthStore()

// Reactive state
const searchQuery = ref('')
const statusFilter = ref('all')
const showCreateDialog = ref(false)
const showMembersDialog = ref(false)
const showDeleteDialog = ref(false)
const editingProject = ref<Project | null>(null)
const selectedProject = ref<Project | null>(null)
const projectToDelete = ref<Project | null>(null)
const isSubmitting = ref(false)
const thumbnailBlobUrls = ref<Map<number, string>>(new Map())
const thumbnailLoadingStates = ref<Map<number, boolean>>(new Map())
const thumbnailLoadedStates = ref<Map<number, boolean>>(new Map())
const thumbnailErrorStates = ref<Map<number, boolean>>(new Map())

// Utility functions for date handling
const getTodayDate = () => {
  const today = new Date()
  return today.toISOString().split('T')[0] // Format: YYYY-MM-DD
}

const getOneMonthFromToday = () => {
  const today = new Date()
  const oneMonthLater = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate())
  return oneMonthLater.toISOString().split('T')[0] // Format: YYYY-MM-DD
}

// Form data
const projectForm = ref({
  name: '',
  code_name: '',
  client_name: '',
  project_type: 'tv' as 'tv' | 'cinema' | 'game',
  description: '',
  status: 'planning' as 'planning' | 'in_progress' | 'on_hold' | 'completed' | 'cancelled',
  start_date: getTodayDate(),
  end_date: getOneMonthFromToday()
})

// Computed properties
const canCreateProjects = computed(() => {
  const userRole = authStore.userRole
  const isAdmin = authStore.user?.is_admin
  return userRole === 'coordinator' || isAdmin
})

const canDeleteProjects = computed(() => {
  return authStore.user?.is_admin
})

const filteredProjects = computed(() => {
  let filtered = projectsStore.projects

  // Filter by search query
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(project => 
      project.name.toLowerCase().includes(query) ||
      project.code_name.toLowerCase().includes(query) ||
      project.client_name.toLowerCase().includes(query) ||
      project.description?.toLowerCase().includes(query)
    )
  }

  // Filter by status
  if (statusFilter.value !== 'all') {
    filtered = filtered.filter(project => project.status === statusFilter.value)
  }

  return filtered
})

// Validation for date fields
const isDateRangeValid = computed(() => {
  if (!projectForm.value.start_date || !projectForm.value.end_date) {
    return true // Allow empty dates
  }
  return new Date(projectForm.value.start_date) <= new Date(projectForm.value.end_date)
})

// Methods
const loadProjects = async () => {
  await projectsStore.fetchProjects()
}

const selectProject = (project: Project) => {
  projectsStore.setActiveProject(project)
  // Navigate to project detail view (overview tab)
  router.push(`/projects/${project.id}`)
}

const openCreateDialog = () => {
  // Reset form to default values for new project creation
  projectForm.value = {
    name: '',
    code_name: '',
    client_name: '',
    project_type: 'tv',
    description: '',
    status: 'planning',
    start_date: getTodayDate(),
    end_date: getOneMonthFromToday()
  }
  editingProject.value = null
  showCreateDialog.value = true
}

const editProject = (project: Project) => {
  editingProject.value = project
  projectForm.value = {
    name: project.name,
    code_name: project.code_name,
    client_name: project.client_name,
    project_type: project.project_type,
    description: project.description || '',
    status: project.status,
    start_date: project.start_date || '',
    end_date: project.end_date || ''
  }
  showCreateDialog.value = true
}

const manageMembers = (project: Project) => {
  selectedProject.value = project
  showMembersDialog.value = true
}

const manageTechnicalSpecs = (project: Project) => {
  router.push(`/projects/${project.id}/technical-specs`)
}

const deleteProject = (project: Project) => {
  projectToDelete.value = project
  showDeleteDialog.value = true
}

const submitProject = async () => {
  try {
    isSubmitting.value = true
    
    // Clean up the form data - convert empty strings to null for optional date fields
    const cleanedFormData = {
      ...projectForm.value,
      start_date: projectForm.value.start_date || null,
      end_date: projectForm.value.end_date || null,
      description: projectForm.value.description || null
    }
    
    if (editingProject.value) {
      await projectsStore.updateProject(editingProject.value.id, cleanedFormData)
      toast({
        title: 'Project updated',
        description: 'Project has been updated successfully.'
      })
    } else {
      await projectsStore.createProject(cleanedFormData)
      toast({
        title: 'Project created',
        description: 'New project has been created successfully.'
      })
    }
    
    cancelProjectForm()
  } catch (error) {
    toast({
      title: 'Error',
      description: error instanceof Error ? error.message : 'Failed to save project',
      variant: 'destructive'
    })
  } finally {
    isSubmitting.value = false
  }
}

const cancelProjectForm = () => {
  showCreateDialog.value = false
  editingProject.value = null
  projectForm.value = {
    name: '',
    code_name: '',
    client_name: '',
    project_type: 'tv',
    description: '',
    status: 'planning',
    start_date: getTodayDate(),
    end_date: getOneMonthFromToday()
  }
}

const confirmDelete = async () => {
  if (!projectToDelete.value) return
  
  try {
    await projectsStore.deleteProject(projectToDelete.value.id)
    toast({
      title: 'Project deleted',
      description: 'Project has been deleted successfully.'
    })
  } catch (error) {
    toast({
      title: 'Error',
      description: error instanceof Error ? error.message : 'Failed to delete project',
      variant: 'destructive'
    })
  } finally {
    showDeleteDialog.value = false
    projectToDelete.value = null
  }
}

const getStatusVariant = (status: string) => {
  switch (status) {
    case 'planning': return 'secondary'
    case 'in_progress': return 'default'
    case 'on_hold': return 'outline'
    case 'completed': return 'default' // Changed from 'success' to 'default'
    case 'cancelled': return 'destructive'
    default: return 'secondary'
  }
}

const formatStatus = (status: string) => {
  return status.split('_').map(word => 
    word.charAt(0).toUpperCase() + word.slice(1)
  ).join(' ')
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString()
}

const formatProjectType = (type: string) => {
  switch (type) {
    case 'tv': return 'TV Series'
    case 'cinema': return 'Cinema/Film'
    case 'game': return 'Game'
    default: return type
  }
}

const getThumbnailUrl = (projectId: number) => {
  return thumbnailBlobUrls.value.get(projectId) || ''
}

const isThumbnailLoading = (projectId: number) => {
  return thumbnailLoadingStates.value.get(projectId) || false
}

const isThumbnailLoaded = (projectId: number) => {
  return thumbnailLoadedStates.value.get(projectId) || false
}

const onThumbnailLoad = (projectId: number) => {
  thumbnailLoadedStates.value.set(projectId, true)
  thumbnailLoadingStates.value.set(projectId, false)
}

const onThumbnailError = (projectId: number) => {
  thumbnailErrorStates.value.set(projectId, true)
  thumbnailLoadingStates.value.set(projectId, false)
  // Revoke the blob URL on error
  const blobUrl = thumbnailBlobUrls.value.get(projectId)
  if (blobUrl) {
    URL.revokeObjectURL(blobUrl)
    thumbnailBlobUrls.value.delete(projectId)
  }
}

async function loadThumbnail(projectId: number, thumbnailUrl: string) {
  if (!thumbnailUrl) return
  
  // Skip if already loading or loaded
  if (thumbnailLoadingStates.value.get(projectId) || thumbnailBlobUrls.value.has(projectId)) {
    return
  }
  
  try {
    thumbnailLoadingStates.value.set(projectId, true)
    
    const response = await apiClient.get(thumbnailUrl, {
      responseType: 'blob'
    })
    
    // Revoke old blob URL if it exists
    const oldUrl = thumbnailBlobUrls.value.get(projectId)
    if (oldUrl) {
      URL.revokeObjectURL(oldUrl)
    }
    
    // Create new blob URL
    const blobUrl = URL.createObjectURL(response.data)
    thumbnailBlobUrls.value.set(projectId, blobUrl)
    thumbnailLoadingStates.value.set(projectId, false)
  } catch (error) {
    console.error(`Failed to load thumbnail for project ${projectId}:`, error)
    thumbnailErrorStates.value.set(projectId, true)
    thumbnailLoadingStates.value.set(projectId, false)
  }
}

async function loadAllThumbnails() {
  const projects = filteredProjects.value
  
  // Use Intersection Observer for lazy loading
  if ('IntersectionObserver' in window) {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            const projectId = parseInt(entry.target.getAttribute('data-project-id') || '0')
            const project = projects.find(p => p.id === projectId)
            
            if (project?.thumbnail_url && !thumbnailBlobUrls.value.has(projectId)) {
              loadThumbnail(projectId, project.thumbnail_url)
              observer.unobserve(entry.target)
            }
          }
        })
      },
      {
        rootMargin: '50px', // Start loading 50px before the element is visible
        threshold: 0.01
      }
    )
    
    // Observe all project cards
    setTimeout(() => {
      const cards = document.querySelectorAll('[data-project-id]')
      cards.forEach(card => observer.observe(card))
    }, 100)
  } else {
    // Fallback for browsers without Intersection Observer
    for (const project of projects) {
      if (project.thumbnail_url && !thumbnailBlobUrls.value.has(project.id)) {
        await loadThumbnail(project.id, project.thumbnail_url)
      }
    }
  }
}

const getProjectInitials = (name: string) => {
  const words = name.split(' ')
  if (words.length >= 2) {
    return (words[0].charAt(0) + words[1].charAt(0)).toUpperCase()
  }
  return name.substring(0, 2).toUpperCase()
}

// Watch for projects changes to load thumbnails
watch(() => projectsStore.projects, () => {
  loadAllThumbnails()
}, { deep: true })

// Watch for start date changes to auto-update end date for new projects
watch(() => projectForm.value.start_date, (newStartDate) => {
  // Only auto-update end date for new projects (not when editing)
  if (!editingProject.value && newStartDate) {
    const startDate = new Date(newStartDate)
    const endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, startDate.getDate())
    projectForm.value.end_date = endDate.toISOString().split('T')[0]
  }
})

// Lifecycle
onMounted(() => {
  loadProjects()
})

onUnmounted(() => {
  // Clean up all blob URLs to prevent memory leaks
  thumbnailBlobUrls.value.forEach(url => URL.revokeObjectURL(url))
  thumbnailBlobUrls.value.clear()
  thumbnailLoadingStates.value.clear()
  thumbnailLoadedStates.value.clear()
  thumbnailErrorStates.value.clear()
})

// Clear error when component unmounts
watch(() => projectsStore.error, (error) => {
  if (error) {
    projectsStore.clearError()
  }
})
</script>