1→import { useEffect, useState, useMemo } from 'react'
     2→import { useSearchParams } from 'react-router-dom'
     3→import { Plus, X, GripVertical, Clock, User, RefreshCw, Flag, Pencil, Check, Trash2, Filter, ArrowUpDown, LayoutGrid, List, ChevronLeft, ChevronRight } from 'lucide-react'
     4→import * as Dialog from '@radix-ui/react-dialog'
     5→import * as AlertDialog from '@radix-ui/react-alert-dialog'
     6→import { useProjectStore } from '../stores/projectStore'
     7→import { useTaskStore, Task, TaskCreate, TaskUpdate } from '../stores/taskStore'
     8→import { useToastStore } from '../components/Toast'
     9→
    10→const ITEMS_PER_PAGE = 10
    11→
    12→const COLUMNS = [
    13→  { id: 'backlog', title: 'Backlog', color: 'border-slate-500' },
    14→  { id: 'in_progress', title: 'In Progress', color: 'border-accent' },
    15→  { id: 'qa', title: 'QA', color: 'border-primary-400' },
    16→  { id: 'done', title: 'Done', color: 'border-green-400' },
    17→  { id: 'blocked', title: 'Blocked', color: 'border-destructive' },
    18→]
    19→
    20→const PRIORITY_LABELS: Record<number, string> = {
    21→  0: 'Low',
    22→  1: 'Medium',
    23→  2: 'High',
    24→  3: 'Critical',
    25→}
    26→
    27→const STATUS_LABELS: Record<string, string> = {
    28→  backlog: 'Backlog',
    29→  in_progress: 'In Progress',
    30→  qa: 'QA',
    31→  done: 'Done',
    32→  blocked: 'Blocked',
    33→}
    34→
    35→export default function KanbanBoard() {
    36→  const [searchParams, setSearchParams] = useSearchParams()
    37→  const { currentProject } = useProjectStore()
    38→  const { tasks, fetchTasks, createTask, updateTask, updateTaskStatus, deleteTask, isTaskDeleting, isLoading } = useTaskStore()
    39→  const { addToast } = useToastStore()
    40→  const [showAddDialog, setShowAddDialog] = useState(false)
    41→  const [newTaskName, setNewTaskName] = useState('')
    42→  const [newTaskDescription, setNewTaskDescription] = useState('')
    43→  const [newTaskPriority, setNewTaskPriority] = useState(0)
    44→  const [isCreating, setIsCreating] = useState(false)
    45→  const [draggedTask, setDraggedTask] = useState<number | null>(null)
    46→  const [selectedTask, setSelectedTask] = useState<Task | null>(null)
    47→  const [isEditing, setIsEditing] = useState(false)
    48→  const [editName, setEditName] = useState('')
    49→  const [editDescription, setEditDescription] = useState('')
    50→  const [editPriority, setEditPriority] = useState(0)
    51→  const [isSaving, setIsSaving] = useState(false)
    52→  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
    53→  const [isDeleting, setIsDeleting] = useState(false)
    54→  const [showUnsavedDialog, setShowUnsavedDialog] = useState(false)
    55→  const [pendingCloseAction, setPendingCloseAction] = useState<'close' | 'cancel' | null>(null)
    56→  // Filter and Sort state - initialize from URL params
    57→  const getInitialPriorityFilter = (): number | 'all' => {
    58→    const param = searchParams.get('priority')
    59→    if (param === 'all' || param === null) return 'all'
    60→    const num = parseInt(param, 10)
    61→    return [0, 1, 2, 3].includes(num) ? num : 'all'
    62→  }
    63→  const getInitialSortOrder = (): 'newest' | 'oldest' | 'priority' => {
    64→    const param = searchParams.get('sort')
    65→    if (param === 'newest' || param === 'oldest' || param === 'priority') return param
    66→    return 'newest'
    67→  }
    68→  const getInitialViewMode = (): 'kanban' | 'list' => {
    69→    const param = searchParams.get('view')
    70→    if (param === 'list') return 'list'
    71→    return 'kanban'
    72→  }
    73→
    74→  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>(getInitialPriorityFilter)
    75→  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>(getInitialSortOrder)
    76→  // View mode and pagination state
    77→  const [viewMode, setViewMode] = useState<'kanban' | 'list'>(getInitialViewMode)
    78→  const [currentPage, setCurrentPage] = useState(1)
    79→
    80→  useEffect(() => {
    81→    if (currentProject?.id) {
    82→      fetchTasks(currentProject.id)
    83→    }
    84→  }, [currentProject?.id, fetchTasks])
    85→
    86→  // Handle deep linking - select task from URL param after tasks are loaded
    87→  useEffect(() => {
    88→    const taskIdParam = searchParams.get('task')
    89→    if (taskIdParam && tasks.length > 0) {
    90→      const taskId = parseInt(taskIdParam, 10)
    91→      const task = tasks.find(t => t.id === taskId)
    92→      if (task) {
    93→        setSelectedTask(task)
    94→      }
    95→    }
    96→  }, [searchParams, tasks])
    97→
    98→  // Update URL when task is selected
    99→  const handleSelectTask = (task: Task) => {
   100→    setSelectedTask(task)
   101→    const newParams = new URLSearchParams(searchParams)
   102→    newParams.set('task', task.id.toString())
   103→    setSearchParams(newParams)
   104→  }
   105→
   106→  // Clear task from URL when panel is closed
   107→  const clearTaskFromUrl = () => {
   108→    const newParams = new URLSearchParams(searchParams)
   109→    newParams.delete('task')
   110→    setSearchParams(newParams)
   111→  }
   112→
   113→  // Update URL when filter changes
   114→  const handlePriorityFilterChange = (value: number | 'all') => {
   115→    setPriorityFilter(value)
   116→    const newParams = new URLSearchParams(searchParams)
   117→    if (value === 'all') {
   118→      newParams.delete('priority')
   119→    } else {
   120→      newParams.set('priority', value.toString())
   121→    }
   122→    setSearchParams(newParams)
   123→  }
   124→
   125→  // Update URL when sort changes
   126→  const handleSortOrderChange = (value: 'newest' | 'oldest' | 'priority') => {
   127→    setSortOrder(value)
   128→    const newParams = new URLSearchParams(searchParams)
   129→    if (value === 'newest') {
   130→      newParams.delete('sort') // default value, no need to store
   131→    } else {
   132→      newParams.set('sort', value)
   133→    }
   134→    setSearchParams(newParams)
   135→  }
   136→
   137→  // Update URL when view mode changes
   138→  const handleViewModeChange = (value: 'kanban' | 'list') => {
   139→    setViewMode(value)
   140→    const newParams = new URLSearchParams(searchParams)
   141→    if (value === 'kanban') {
   142→      newParams.delete('view') // default value, no need to store
   143→    } else {
   144→      newParams.set('view', value)
   145→    }
   146→    setSearchParams(newParams)
   147→  }
   148→
   149→  // Reset all filters to defaults
   150→  const handleResetFilters = () => {
   151→    setPriorityFilter('all')
   152→    setSortOrder('newest')
   153→    setCurrentPage(1)
   154→    const newParams = new URLSearchParams(searchParams)
   155→    newParams.delete('priority')
   156→    newParams.delete('sort')
   157→    setSearchParams(newParams)
   158→  }
   159→
   160→  // Check if filters are active (non-default)
   161→  const hasActiveFilters = priorityFilter !== 'all' || sortOrder !== 'newest'
   162→
   163→  // Filtered and sorted tasks
   164→  const filteredAndSortedTasks = useMemo(() => {
   165→    let result = [...tasks]
   166→
   167→    // Apply priority filter
   168→    if (priorityFilter !== 'all') {
   169→      result = result.filter(task => task.priority === priorityFilter)
   170→    }
   171→
   172→    // Apply sort
   173→    result.sort((a, b) => {
   174→      if (sortOrder === 'newest') {
   175→        return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
   176→      } else if (sortOrder === 'oldest') {
   177→        return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
   178→      } else {
   179→        // priority - highest first
   180→        return b.priority - a.priority
   181→      }
   182→    })
   183→
   184→    return result
   185→  }, [tasks, priorityFilter, sortOrder])
   186→
   187→  // Pagination calculations
   188→  const totalPages = Math.ceil(filteredAndSortedTasks.length / ITEMS_PER_PAGE)
   189→  const paginatedTasks = useMemo(() => {
   190→    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
   191→    return filteredAndSortedTasks.slice(startIndex, startIndex + ITEMS_PER_PAGE)
   192→  }, [filteredAndSortedTasks, currentPage])
   193→
   194→  // Reset page when filter changes
   195→  useEffect(() => {
   196→    setCurrentPage(1)
   197→  }, [priorityFilter, sortOrder])
   198→
   199→  const getTasksByStatus = (status: string) => {
   200→    return filteredAndSortedTasks.filter((task) => task.status === status)
   201→  }
   202→
   203→  const handleCreateTask = async () => {
   204→    if (!currentProject || !newTaskName.trim()) return
   205→    setIsCreating(true)
   206→    try {
   207→      const taskData: TaskCreate = {
   208→        name: newTaskName.trim(),
   209→        description: newTaskDescription.trim() || undefined,
   210→        priority: newTaskPriority,
   211→      }
   212→      await createTask(currentProject.id, taskData)
   213→      setNewTaskName('')
   214→      setNewTaskDescription('')
   215→      setNewTaskPriority(0)
   216→      setShowAddDialog(false)
   217→    } catch (error) {
   218→      console.error('Failed to create task:', error)
   219→      addToast('error', 'Create Failed', 'Failed to create task. Please try again.')
   220→    } finally {
   221→      setIsCreating(false)
   222→    }
   223→  }
   224→
   225→  const handleDragStart = (taskId: number) => {
   226→    setDraggedTask(taskId)
   227→  }
   228→
   229→  const handleDragOver = (e: React.DragEvent) => {
   230→    e.preventDefault()
   231→  }
   232→
   233→  const handleDrop = async (targetStatus: string) => {
   234→    if (draggedTask === null) return
   235→    try {
   236→      await updateTaskStatus(draggedTask, targetStatus)
   237→    } catch (error) {
   238→      console.error('Failed to update task status:', error)
   239→      addToast('error', 'Update Failed', 'Failed to update task status. Please try again.')
   240→    }
   241→    setDraggedTask(null)
   242→  }
   243→
   244→  const handleStartEdit = () => {
   245→    if (!selectedTask) return
   246→    setEditName(selectedTask.name)
   247→    setEditDescription(selectedTask.description || '')
   248→    setEditPriority(selectedTask.priority)
   249→    setIsEditing(true)
   250→  }
   251→
   252→  // Check if edit form has unsaved changes
   253→  const hasUnsavedChanges = () => {
   254→    if (!selectedTask || !isEditing) return false
   255→    return (
   256→      editName.trim() !== selectedTask.name ||
   257→      (editDescription.trim() || '') !== (selectedTask.description || '') ||
   258→      editPriority !== selectedTask.priority
   259→    )
   260→  }
   261→
   262→  const handleCancelEdit = () => {
   263→    if (hasUnsavedChanges()) {
   264→      setPendingCloseAction('cancel')
   265→      setShowUnsavedDialog(true)
   266→    } else {
   267→      setIsEditing(false)
   268→    }
   269→  }
   270→
   271→  const handleClosePanel = () => {
   272→    if (hasUnsavedChanges()) {
   273→      setPendingCloseAction('close')
   274→      setShowUnsavedDialog(true)
   275→    } else {
   276→      setSelectedTask(null)
   277→      setIsEditing(false)
   278→      clearTaskFromUrl()
   279→    }
   280→  }
   281→
   282→  const handleDiscardChanges = () => {
   283→    setShowUnsavedDialog(false)
   284→    if (pendingCloseAction === 'close') {
   285→      setSelectedTask(null)
   286→      clearTaskFromUrl()
   287→    }
   288→    setIsEditing(false)
   289→    setPendingCloseAction(null)
   290→  }
   291→
   292→  const handleKeepEditing = () => {
   293→    setShowUnsavedDialog(false)
   294→    setPendingCloseAction(null)
   295→  }
   296→
   297→  const handleSaveEdit = async () => {
   298→    if (!selectedTask) return
   299→    setIsSaving(true)
   300→    try {
   301→      const updates: TaskUpdate = {
   302→        name: editName.trim(),
   303→        description: editDescription.trim() || undefined,
   304→        priority: editPriority,
   305→      }
   306→      const updatedTask = await updateTask(selectedTask.id, updates)
   307→      setSelectedTask(updatedTask)
   308→      setIsEditing(false)
   309→    } catch (error) {
   310→      console.error('Failed to update task:', error)
   311→      addToast('error', 'Save Failed', 'Failed to save task changes. Please try again.')
   312→    } finally {
   313→      setIsSaving(false)
   314→    }
   315→  }
   316→
   317→  const handleDeleteTask = async () => {
   318→    if (!selectedTask) return
   319→    // Check if already being deleted (prevents rapid clicks)
   320→    if (isTaskDeleting(selectedTask.id)) return
   321→
   322→    const taskIdToDelete = selectedTask.id
   323→    const taskName = selectedTask.name
   324→    setIsDeleting(true)
   325→    // Close dialog immediately to prevent additional clicks
   326→    setShowDeleteDialog(false)
   327→
   328→    try {
   329→      await deleteTask(taskIdToDelete)
   330→      setSelectedTask(null)
   331→      clearTaskFromUrl()
   332→    } catch (error) {
   333→      console.error('Failed to delete task:', error)
   334→      addToast('error', 'Delete Failed', `Failed to delete task "${taskName}". Please try again.`)
   335→      // Re-open dialog if delete failed so user can retry
   336→      setShowDeleteDialog(true)
   337→    } finally {
   338→      setIsDeleting(false)
   339→    }
   340→  }
   341→
   342→  if (!currentProject) {
   343→    return (
   344→

   345→
Select a project to view its Kanban board

   346→

   347→    )
   348→  }
   349→
   350→  return (
   351→

   352→      {/* Header */}
   353→

   354→
Kanban Board

   355→

   356→          {/* Priority Filter */}
   357→

   358→            <Filter size={16} className="text-slate-400" />
   359→            <select
   360→              value={priorityFilter === 'all' ? 'all' : priorityFilter.toString()}
   361→              onChange={(e) => handlePriorityFilterChange(e.target.value === 'all' ? 'all' : Number(e.target.value))}
   362→              className="px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-accent"
   363→            >
   364→              <option value="all">All Priorities</option>
   365→              <option value="3">Critical</option>
   366→              <option value="2">High</option>
   367→              <option value="1">Medium</option>
   368→              <option value="0">Low</option>
   369→            </select>
   370→

   371→
   372→          {/* Sort Order */}
   373→

   374→            <ArrowUpDown size={16} className="text-slate-400" />
   375→            <select
   376→              value={sortOrder}
   377→              onChange={(e) => handleSortOrderChange(e.target.value as 'newest' | 'oldest' | 'priority')}
   378→              className="px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-accent"
   379→            >
   380→              <option value="newest">Newest First</option>
   381→              <option value="oldest">Oldest First</option>
   382→              <option value="priority">By Priority</option>
   383→            </select>
   384→

   385→
   386→          {/* Reset Filters Button */}
   387→          {hasActiveFilters && (
   388→            <button
   389→              onClick={handleResetFilters}
   390→              className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-slate-400 hover:text-white hover:bg-slate-700 rounded-lg transition-colors"
   391→              title="Reset Filters"
   392→            >
   393→              <RefreshCw size={14} />
   394→              Reset
   395→            </button>
   396→          )}
   397→
   398→          {/* View Mode Toggle */}
   399→

   400→            <button
   401→              onClick={() => handleViewModeChange('kanban')}
   402→              className={`p-1.5 rounded ${viewMode === 'kanban' ? 'bg-accent text-white' : 'text-slate-400 hover:text-white'}`}
   403→              title="Kanban View"
   404→            >
   405→              <LayoutGrid size={18} />
   406→            </button>
   407→            <button
   408→              onClick={() => handleViewModeChange('list')}
   409→              className={`p-1.5 rounded ${viewMode === 'list' ? 'bg-accent text-white' : 'text-slate-400 hover:text-white'}`}
   410→              title="List View"
   411→            >
   412→              <List size={18} />
   413→            </button>
   414→

   415→
   416→        <Dialog.Root open={showAddDialog} onOpenChange={setShowAddDialog}>
   417→          <Dialog.Trigger asChild>
   418→            <button className="btn-accent flex items-center gap-2">
   419→              <Plus size={18} />
   420→              Add Task
   421→            </button>
   422→          </Dialog.Trigger>
   423→          <Dialog.Portal>
   424→            <Dialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
   425→            <Dialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-slate-800 border border-slate-700 rounded-lg p-4 md:p-6 w-[calc(100%-2rem)] max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto z-50 shadow-xl">
   426→

   427→                <Dialog.Title className="text-xl font-semibold text-white">
   428→                  Add New Task
   429→                </Dialog.Title>
   430→                <Dialog.Close asChild>
   431→                  <button className="text-slate-400 hover:text-white" aria-label="Close dialog">
   432→                    <X size={20} />
   433→                  </button>
   434→                </Dialog.Close>
   435→

   436→              <Dialog.Description className="text-slate-400 mb-4">
   437→                Create a new task for this project.
   438→              </Dialog.Description>
   439→

   440→

   441→
   442→                    Task Name *
   443→
   444→                  <input
   445→                    type="text"
   446→                    value={newTaskName}
   447→                    onChange={(e) => setNewTaskName(e.target.value)}
   448→                    className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
   449→                    placeholder="Enter task name"
   450→                  />
   451→

   452→

   453→
   454→                    Description
   455→
   456→                  <textarea
   457→                    value={newTaskDescription}
   458→                    onChange={(e) => setNewTaskDescription(e.target.value)}
   459→                    rows={3}
   460→                    className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent resize-none"
   461→                    placeholder="Enter task description"
   462→                  />
   463→

   464→

   465→
   466→                    Priority
   467→
   468→                  <select
   469→                    value={newTaskPriority}
   470→                    onChange={(e) => setNewTaskPriority(Number(e.target.value))}
   471→                    className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
   472→                  >
   473→                    <option value={0}>Low</option>
   474→                    <option value={1}>Medium</option>
   475→                    <option value={2}>High</option>
   476→                    <option value={3}>Critical</option>
   477→                  </select>
   478→

   479→

   480→

   481→                <Dialog.Close asChild>
   482→                  <button className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors">
   483→                    Cancel
   484→                  </button>
   485→                </Dialog.Close>
   486→                <button
   487→                  onClick={handleCreateTask}
   488→                  disabled={isCreating || !newTaskName.trim()}
   489→                  className="px-4 py-2 text-sm bg-accent hover:bg-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
   490→                >
   491→                  {isCreating ? 'Creating...' : 'Create Task'}
   492→                </button>
   493→

   494→            </Dialog.Content>
   495→          </Dialog.Portal>
   496→        </Dialog.Root>
   497→

   498→

   499→
   500→      {/* Main Content Area */}
   501→

   502→        {viewMode === 'list' ? (
   503→          /* List View with Pagination */
   504→

   505→            {/* Task List Table */}
   506→

   507→

   508→

   509→

   510→                    Task Name
   511→                    Status
   512→                    Priority
   513→                    Created
   514→

   515→

   516→

   517→                  {isLoading && tasks.length === 0 ? (
   518→

   519→
   520→                        Loading...
   521→
   522→

   523→                  ) : paginatedTasks.length === 0 ? (
   524→

   525→
   526→                        No tasks found
   527→
   528→

   529→                  ) : (
   530→                    paginatedTasks.map((task) => (
   531→
 handleSelectTask(task)}
   534→                        className={`border-t border-slate-700 hover:bg-slate-700/50 cursor-pointer ${
   535→                          selectedTask?.id === task.id ? 'bg-slate-700' : ''
   536→                        }`}
   537→                      >
   538→
   539→
{task.name}

   540→                          {task.description && (
   541→

   542→                              {task.description}
   543→

   544→                          )}
   545→
   546→
   547→
   554→                            {STATUS_LABELS[task.status] || task.status}
   555→
   556→
   557→
   558→
   564→                            {PRIORITY_LABELS[task.priority] || 'Unknown'}
   565→
   566→
   567→
   568→                          {new Date(task.created_at).toLocaleDateString()}
   569→
   570→

   571→                    ))
   572→                  )}
   573→

   574→

   575→

   576→
   577→            {/* Pagination Controls */}
   578→            {totalPages > 1 && (
   579→

   580→

   581→                  Showing {((currentPage - 1) * ITEMS_PER_PAGE) + 1} to {Math.min(currentPage * ITEMS_PER_PAGE, filteredAndSortedTasks.length)} of {filteredAndSortedTasks.length} tasks
   582→

   583→

   584→                  <button
   585→                    onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
   586→                    disabled={currentPage === 1}
   587→                    className="p-2 rounded-lg bg-slate-800 border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
   588→                  >
   589→                    <ChevronLeft size={18} />
   590→                  </button>
   591→

   592→                    {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
   593→                      <button
   594→                        key={page}
   595→                        onClick={() => setCurrentPage(page)}
   596→                        className={`w-8 h-8 rounded-lg text-sm ${
   597→                          page === currentPage
   598→                            ? 'bg-accent text-white'
   599→                            : 'bg-slate-800 border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700'
   600→                        }`}
   601→                      >
   602→                        {page}
   603→                      </button>
   604→                    ))}
   605→

   606→                  <button
   607→                    onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
   608→                    disabled={currentPage === totalPages}
   609→                    className="p-2 rounded-lg bg-slate-800 border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
   610→                  >
   611→                    <ChevronRight size={18} />
   612→                  </button>
   613→

   614→

   615→            )}
   616→

   617→        ) : (
   618→        /* Kanban Columns */
   619→        <div className={`flex-1 flex gap-4 overflow-x-auto pb-4 ${selectedTask ? 'mr-0' : ''}`}>
   620→          {COLUMNS.map((column) => (
   621→          <div
   622→            key={column.id}
   623→            className={`flex-shrink-0 w-72 bg-slate-800 rounded-lg border-t-2 ${column.color}`}
   624→            onDragOver={handleDragOver}
   625→            onDrop={() => handleDrop(column.id)}
   626→          >
   627→            {/* Column Header */}
   628→

   629→

   630→
{column.title}

   631→
   632→                  {getTasksByStatus(column.id).length}
   633→
   634→

   635→

   636→
   637→            {/* Column Content */}
   638→

   639→              {isLoading && tasks.length === 0 ? (
   640→

   641→                  Loading...
   642→

   643→              ) : getTasksByStatus(column.id).length === 0 ? (
   644→

   645→                  No tasks
   646→

   647→              ) : (
   648→                getTasksByStatus(column.id).map((task) => (
   649→
 handleDragStart(task.id)}
   653→                    onClick={() => handleSelectTask(task)}
   654→                    className={`kanban-card bg-slate-900 rounded-lg p-4 border border-slate-700 cursor-pointer hover:border-slate-600 ${
   655→                      draggedTask === task.id ? 'opacity-50' : ''
   656→                    } ${selectedTask?.id === task.id ? 'ring-2 ring-accent' : ''}`}
   657→                  >
   658→

   659→                      <GripVertical size={16} className="text-slate-600 mt-0.5 flex-shrink-0" />
   660→

   661→
{task.name}

   662→                        {task.description && (
   663→

   664→                            {task.description}
   665→

   666→                        )}
   667→

   668→                          <span
   669→                            className={`badge ${
   670→                              column.id === 'backlog'
   671→                                ? 'badge-backlog'
   672→                                : column.id === 'in_progress'
   673→                                ? 'badge-in-progress'
   674→                                : column.id === 'qa'
   675→                                ? 'badge-qa'
   676→                                : column.id === 'done'
   677→                                ? 'badge-done'
   678→                                : 'badge-blocked'
   679→                            }`}
   680→                          >
   681→                            {column.title}
   682→
   683→
   689→                            {task.priority === 3 ? 'Critical' :
   690→                             task.priority === 2 ? 'High' :
   691→                             task.priority === 1 ? 'Medium' : 'Low'}
   692→
   693→

   694→

   695→

   696→

   697→                ))
   698→              )}
   699→

   700→

   701→          ))}
   702→

   703→        )}
   704→
   705→        {/* Task Details Panel */}
   706→        {selectedTask && (
   707→

   708→

   709→
Task Details

   710→

   711→                {!isEditing && (
   712→                  <>
   713→                    <button
   714→                      onClick={handleStartEdit}
   715→                      className="text-slate-400 hover:text-accent transition-colors"
   716→                      title="Edit Task"
   717→                    >
   718→                      <Pencil size={18} />
   719→                    </button>
   720→                    <AlertDialog.Root open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
   721→                      <AlertDialog.Trigger asChild>
   722→                        <button
   723→                          className="text-slate-400 hover:text-destructive transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
   724→                          title="Delete Task"
   725→                          disabled={isDeleting || (selectedTask ? isTaskDeleting(selectedTask.id) : false)}
   726→                        >
   727→                          <Trash2 size={18} />
   728→                        </button>
   729→                      </AlertDialog.Trigger>
   730→                      <AlertDialog.Portal>
   731→                        <AlertDialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
   732→                        <AlertDialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-slate-800 border border-slate-700 rounded-lg p-4 md:p-6 w-[calc(100%-2rem)] max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto z-50 shadow-xl">
   733→                          <AlertDialog.Title className="text-xl font-semibold text-white">
   734→                            Delete Task
   735→                          </AlertDialog.Title>
   736→                          <AlertDialog.Description className="mt-3 text-slate-400">
   737→                            Are you sure you want to delete {selectedTask.name}?
   738→                            This action cannot be undone.
   739→                          </AlertDialog.Description>
   740→

   741→                            <AlertDialog.Cancel asChild>
   742→                              <button className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors">
   743→                                Cancel
   744→                              </button>
   745→                            </AlertDialog.Cancel>
   746→                            <AlertDialog.Action asChild>
   747→                              <button
   748→                                onClick={handleDeleteTask}
   749→                                disabled={isDeleting || (selectedTask ? isTaskDeleting(selectedTask.id) : false)}
   750→                                className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors disabled:opacity-50"
   751→                              >
   752→                                {isDeleting || (selectedTask && isTaskDeleting(selectedTask.id)) ? 'Deleting...' : 'Delete Task'}
   753→                              </button>
   754→                            </AlertDialog.Action>
   755→

   756→                        </AlertDialog.Content>
   757→                      </AlertDialog.Portal>
   758→                    </AlertDialog.Root>
   759→                  </>
   760→                )}
   761→                <button
   762→                  onClick={handleClosePanel}
   763→                  className="text-slate-400 hover:text-white transition-colors"
   764→                  title="Close"
   765→                >
   766→                  <X size={20} />
   767→                </button>
   768→

   769→

   770→

   771→              {isEditing ? (
   772→                /* Edit Form */
   773→

   774→

   775→                    Name *
   776→                    <input
   777→                      type="text"
   778→                      value={editName}
   779→                      onChange={(e) => setEditName(e.target.value)}
   780→                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
   781→                      placeholder="Task name"
   782→                    />
   783→

   784→

   785→                    Description
   786→                    <textarea
   787→                      value={editDescription}
   788→                      onChange={(e) => setEditDescription(e.target.value)}
   789→                      rows={3}
   790→                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent resize-none"
   791→                      placeholder="Task description"
   792→                    />
   793→

   794→

   795→                    Priority
   796→                    <select
   797→                      value={editPriority}
   798→                      onChange={(e) => setEditPriority(Number(e.target.value))}
   799→                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
   800→                    >
   801→                      <option value={0}>Low</option>
   802→                      <option value={1}>Medium</option>
   803→                      <option value={2}>High</option>
   804→                      <option value={3}>Critical</option>
   805→                    </select>
   806→

   807→

   808→                    <button
   809→                      onClick={handleCancelEdit}
   810→                      className="flex-1 px-3 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
   811→                    >
   812→                      Cancel
   813→                    </button>
   814→                    <button
   815→                      onClick={handleSaveEdit}
   816→                      disabled={isSaving || !editName.trim()}
   817→                      className="flex-1 flex items-center justify-center gap-2 px-3 py-2 text-sm bg-accent hover:bg-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
   818→                    >
   819→                      {isSaving ? 'Saving...' : <><Check size={16} /> Save</>}
   820→                    </button>
   821→

   822→

   823→              ) : (
   824→                /* View Mode */
   825→                <>
   826→                  {/* Task Name */}
   827→

   828→                    Name
   829→
{selectedTask.name}

   830→

   831→
   832→                  {/* Description */}
   833→

   834→                    Description
   835→

   836→                      {selectedTask.description || No description}
   837→

   838→

   839→
   840→                  {/* Status */}
   841→

   842→                    Status
   843→
   850→                      {STATUS_LABELS[selectedTask.status] || selectedTask.status}
   851→
   852→

   853→
   854→                  {/* Priority */}
   855→

   856→                    Priority
   857→
   863→                      {PRIORITY_LABELS[selectedTask.priority] || 'Unknown'}
   864→
   865→

   866→
   867→                  {/* Agent Assignment */}
   868→

   869→
   870→                      <User size={14} />
   871→                      Agent Assignment
   872→
   873→

   874→                      {selectedTask.agent_type ? (
   875→                        {selectedTask.agent_type.replace('_', ' ')}
   876→                      ) : (
   877→                        Not assigned
   878→                      )}
   879→

   880→

   881→
   882→                  {/* Iteration Count */}
   883→

   884→
   885→                      <RefreshCw size={14} />
   886→                      Iteration Count
   887→
   888→
{selectedTask.iteration_count}

   889→

   890→
   891→                  {/* Flagged for Review */}
   892→

   893→
   894→                      <Flag size={14} />
   895→                      Flagged for Review
   896→
   897→

   898→                      {selectedTask.flagged_for_review ? 'Yes' : 'No'}
   899→

   900→

   901→
   902→                  {/* Time Estimates */}
   903→                  {(selectedTask.estimated_time || selectedTask.actual_time) && (
   904→

   905→
   906→                        <Clock size={14} />
   907→                        Time
   908→
   909→

   910→                        {selectedTask.estimated_time &&
Estimated: {selectedTask.estimated_time} min
}
   911→                        {selectedTask.actual_time &&
Actual: {selectedTask.actual_time} min
}
   912→

   913→

   914→                  )}
   915→
   916→                  {/* Created/Updated timestamps */}
   917→

   918→
Created: {new Date(selectedTask.created_at).toLocaleString()}

   919→
Updated: {new Date(selectedTask.updated_at).toLocaleString()}

   920→

   921→                </>
   922→              )}
   923→

   924→

   925→        )}
   926→
   927→        {/* Unsaved Changes Warning Dialog */}
   928→        <AlertDialog.Root open={showUnsavedDialog} onOpenChange={setShowUnsavedDialog}>
   929→          <AlertDialog.Portal>
   930→            <AlertDialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
   931→            <AlertDialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-slate-800 border border-slate-700 rounded-lg p-4 md:p-6 w-[calc(100%-2rem)] max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto z-50 shadow-xl">
   932→              <AlertDialog.Title className="text-xl font-semibold text-white">
   933→                Unsaved Changes
   934→              </AlertDialog.Title>
   935→              <AlertDialog.Description className="mt-3 text-slate-400">
   936→                You have unsaved changes. Are you sure you want to discard them?
   937→              </AlertDialog.Description>
   938→

   939→                <AlertDialog.Cancel asChild>
   940→                  <button
   941→                    onClick={handleKeepEditing}
   942→                    className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
   943→                  >
   944→                    Keep Editing
   945→                  </button>
   946→                </AlertDialog.Cancel>
   947→                <AlertDialog.Action asChild>
   948→                  <button
   949→                    onClick={handleDiscardChanges}
   950→                    className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors"
   951→                  >
   952→                    Discard Changes
   953→                  </button>
   954→                </AlertDialog.Action>
   955→

   956→            </AlertDialog.Content>
   957→          </AlertDialog.Portal>
   958→        </AlertDialog.Root>
   959→

   960→

   961→  )
   962→}
   963→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

import { useEffect, useState, useMemo } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Plus, X, GripVertical, Clock, User, RefreshCw, Flag, Pencil, Check, Trash2, Filter, ArrowUpDown, LayoutGrid, List, ChevronLeft, ChevronRight } from 'lucide-react'
import * as Dialog from '@radix-ui/react-dialog'
import * as AlertDialog from '@radix-ui/react-alert-dialog'
import { useProjectStore } from '../stores/projectStore'
import { useTaskStore, Task, TaskCreate, TaskUpdate } from '../stores/taskStore'
import { useToastStore } from '../components/Toast'

const ITEMS_PER_PAGE = 10

const COLUMNS = [
  { id: 'backlog', title: 'Backlog', color: 'border-slate-500' },
  { id: 'in_progress', title: 'In Progress', color: 'border-accent' },
  { id: 'qa', title: 'QA', color: 'border-primary-400' },
  { id: 'done', title: 'Done', color: 'border-green-400' },
  { id: 'blocked', title: 'Blocked', color: 'border-destructive' },
]

const PRIORITY_LABELS: Record<number, string> = {
  0: 'Low',
  1: 'Medium',
  2: 'High',
  3: 'Critical',
}

const STATUS_LABELS: Record<string, string> = {
  backlog: 'Backlog',
  in_progress: 'In Progress',
  qa: 'QA',
  done: 'Done',
  blocked: 'Blocked',
}

export default function KanbanBoard() {
  const [searchParams, setSearchParams] = useSearchParams()
  const { currentProject } = useProjectStore()
  const { tasks, fetchTasks, createTask, updateTask, updateTaskStatus, deleteTask, isTaskDeleting, isLoading } = useTaskStore()
  const { addToast } = useToastStore()
  const [showAddDialog, setShowAddDialog] = useState(false)
  const [newTaskName, setNewTaskName] = useState('')
  const [newTaskDescription, setNewTaskDescription] = useState('')
  const [newTaskPriority, setNewTaskPriority] = useState(0)
  const [isCreating, setIsCreating] = useState(false)
  const [draggedTask, setDraggedTask] = useState<number | null>(null)
  const [selectedTask, setSelectedTask] = useState<Task | null>(null)
  const [isEditing, setIsEditing] = useState(false)
  const [editName, setEditName] = useState('')
  const [editDescription, setEditDescription] = useState('')
  const [editPriority, setEditPriority] = useState(0)
  const [isSaving, setIsSaving] = useState(false)
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [isDeleting, setIsDeleting] = useState(false)
  const [showUnsavedDialog, setShowUnsavedDialog] = useState(false)
  const [pendingCloseAction, setPendingCloseAction] = useState<'close' | 'cancel' | null>(null)
  // Filter and Sort state - initialize from URL params
  const getInitialPriorityFilter = (): number | 'all' => {
    const param = searchParams.get('priority')
    if (param === 'all' || param === null) return 'all'
    const num = parseInt(param, 10)
    return [0, 1, 2, 3].includes(num) ? num : 'all'
  }
  const getInitialSortOrder = (): 'newest' | 'oldest' | 'priority' => {
    const param = searchParams.get('sort')
    if (param === 'newest' || param === 'oldest' || param === 'priority') return param
    return 'newest'
  }
  const getInitialViewMode = (): 'kanban' | 'list' => {
    const param = searchParams.get('view')
    if (param === 'list') return 'list'
    return 'kanban'
  }

  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>(getInitialPriorityFilter)
  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>(getInitialSortOrder)
  // View mode and pagination state
  const [viewMode, setViewMode] = useState<'kanban' | 'list'>(getInitialViewMode)
  const [currentPage, setCurrentPage] = useState(1)

  useEffect(() => {
    if (currentProject?.id) {
      fetchTasks(currentProject.id)
    }
  }, [currentProject?.id, fetchTasks])

  // Handle deep linking - select task from URL param after tasks are loaded
  useEffect(() => {
    const taskIdParam = searchParams.get('task')
    if (taskIdParam && tasks.length > 0) {
      const taskId = parseInt(taskIdParam, 10)
      const task = tasks.find(t => t.id === taskId)
      if (task) {
        setSelectedTask(task)
      }
    }
  }, [searchParams, tasks])

  // Update URL when task is selected
  const handleSelectTask = (task: Task) => {
    setSelectedTask(task)
    const newParams = new URLSearchParams(searchParams)
    newParams.set('task', task.id.toString())
    setSearchParams(newParams)
  }

  // Clear task from URL when panel is closed
  const clearTaskFromUrl = () => {
    const newParams = new URLSearchParams(searchParams)
    newParams.delete('task')
    setSearchParams(newParams)
  }

  // Update URL when filter changes
  const handlePriorityFilterChange = (value: number | 'all') => {
    setPriorityFilter(value)
    const newParams = new URLSearchParams(searchParams)
    if (value === 'all') {
      newParams.delete('priority')
    } else {
      newParams.set('priority', value.toString())
    }
    setSearchParams(newParams)
  }

  // Update URL when sort changes
  const handleSortOrderChange = (value: 'newest' | 'oldest' | 'priority') => {
    setSortOrder(value)
    const newParams = new URLSearchParams(searchParams)
    if (value === 'newest') {
      newParams.delete('sort') // default value, no need to store
    } else {
      newParams.set('sort', value)
    }
    setSearchParams(newParams)
  }

  // Update URL when view mode changes
  const handleViewModeChange = (value: 'kanban' | 'list') => {
    setViewMode(value)
    const newParams = new URLSearchParams(searchParams)
    if (value === 'kanban') {
      newParams.delete('view') // default value, no need to store
    } else {
      newParams.set('view', value)
    }
    setSearchParams(newParams)
  }

  // Reset all filters to defaults
  const handleResetFilters = () => {
    setPriorityFilter('all')
    setSortOrder('newest')
    setCurrentPage(1)
    const newParams = new URLSearchParams(searchParams)
    newParams.delete('priority')
    newParams.delete('sort')
    setSearchParams(newParams)
  }

  // Check if filters are active (non-default)
  const hasActiveFilters = priorityFilter !== 'all' || sortOrder !== 'newest'

  // Filtered and sorted tasks
  const filteredAndSortedTasks = useMemo(() => {
    let result = [...tasks]

    // Apply priority filter
    if (priorityFilter !== 'all') {
      result = result.filter(task => task.priority === priorityFilter)
    }

    // Apply sort
    result.sort((a, b) => {
      if (sortOrder === 'newest') {
        return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
      } else if (sortOrder === 'oldest') {
        return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
      } else {
        // priority - highest first
        return b.priority - a.priority
      }
    })

    return result
  }, [tasks, priorityFilter, sortOrder])

  // Pagination calculations
  const totalPages = Math.ceil(filteredAndSortedTasks.length / ITEMS_PER_PAGE)
  const paginatedTasks = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
    return filteredAndSortedTasks.slice(startIndex, startIndex + ITEMS_PER_PAGE)
  }, [filteredAndSortedTasks, currentPage])

  // Reset page when filter changes
  useEffect(() => {
    setCurrentPage(1)
  }, [priorityFilter, sortOrder])

  const getTasksByStatus = (status: string) => {
    return filteredAndSortedTasks.filter((task) => task.status === status)
  }

  const handleCreateTask = async () => {
    if (!currentProject || !newTaskName.trim()) return
    setIsCreating(true)
    try {
      const taskData: TaskCreate = {
        name: newTaskName.trim(),
        description: newTaskDescription.trim() || undefined,
        priority: newTaskPriority,
      }
      await createTask(currentProject.id, taskData)
      setNewTaskName('')
      setNewTaskDescription('')
      setNewTaskPriority(0)
      setShowAddDialog(false)
    } catch (error) {
      console.error('Failed to create task:', error)
      addToast('error', 'Create Failed', 'Failed to create task. Please try again.')
    } finally {
      setIsCreating(false)
    }
  }

  const handleDragStart = (taskId: number) => {
    setDraggedTask(taskId)
  }

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
  }

  const handleDrop = async (targetStatus: string) => {
    if (draggedTask === null) return
    try {
      await updateTaskStatus(draggedTask, targetStatus)
    } catch (error) {
      console.error('Failed to update task status:', error)
      addToast('error', 'Update Failed', 'Failed to update task status. Please try again.')
    }
    setDraggedTask(null)
  }

  const handleStartEdit = () => {
    if (!selectedTask) return
    setEditName(selectedTask.name)
    setEditDescription(selectedTask.description || '')
    setEditPriority(selectedTask.priority)
    setIsEditing(true)
  }

  // Check if edit form has unsaved changes
  const hasUnsavedChanges = () => {
    if (!selectedTask || !isEditing) return false
    return (
      editName.trim() !== selectedTask.name ||
      (editDescription.trim() || '') !== (selectedTask.description || '') ||
      editPriority !== selectedTask.priority
    )
  }

  const handleCancelEdit = () => {
    if (hasUnsavedChanges()) {
      setPendingCloseAction('cancel')
      setShowUnsavedDialog(true)
    } else {
      setIsEditing(false)
    }
  }

  const handleClosePanel = () => {
    if (hasUnsavedChanges()) {
      setPendingCloseAction('close')
      setShowUnsavedDialog(true)
    } else {
      setSelectedTask(null)
      setIsEditing(false)
      clearTaskFromUrl()
    }
  }

  const handleDiscardChanges = () => {
    setShowUnsavedDialog(false)
    if (pendingCloseAction === 'close') {
      setSelectedTask(null)
      clearTaskFromUrl()
    }
    setIsEditing(false)
    setPendingCloseAction(null)
  }

  const handleKeepEditing = () => {
    setShowUnsavedDialog(false)
    setPendingCloseAction(null)
  }

  const handleSaveEdit = async () => {
    if (!selectedTask) return
    setIsSaving(true)
    try {
      const updates: TaskUpdate = {
        name: editName.trim(),
        description: editDescription.trim() || undefined,
        priority: editPriority,
      }
      const updatedTask = await updateTask(selectedTask.id, updates)
      setSelectedTask(updatedTask)
      setIsEditing(false)
    } catch (error) {
      console.error('Failed to update task:', error)
      addToast('error', 'Save Failed', 'Failed to save task changes. Please try again.')
    } finally {
      setIsSaving(false)
    }
  }

  const handleDeleteTask = async () => {
    if (!selectedTask) return
    // Check if already being deleted (prevents rapid clicks)
    if (isTaskDeleting(selectedTask.id)) return

    const taskIdToDelete = selectedTask.id
    const taskName = selectedTask.name
    setIsDeleting(true)
    // Close dialog immediately to prevent additional clicks
    setShowDeleteDialog(false)

    try {
      await deleteTask(taskIdToDelete)
      setSelectedTask(null)
      clearTaskFromUrl()
    } catch (error) {
      console.error('Failed to delete task:', error)
      addToast('error', 'Delete Failed', `Failed to delete task "${taskName}". Please try again.`)
      // Re-open dialog if delete failed so user can retry
      setShowDeleteDialog(true)
    } finally {
      setIsDeleting(false)
    }
  }

  if (!currentProject) {
    return (

Select a project to view its Kanban board

    )
  }

  return (

      {/* Header */}

Kanban Board

          {/* Priority Filter */}

            <Filter size={16} className="text-slate-400" />
            <select
              value={priorityFilter === 'all' ? 'all' : priorityFilter.toString()}
              onChange={(e) => handlePriorityFilterChange(e.target.value === 'all' ? 'all' : Number(e.target.value))}
              className="px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-accent"
            >
              <option value="all">All Priorities</option>
              <option value="3">Critical</option>
              <option value="2">High</option>
              <option value="1">Medium</option>
              <option value="0">Low</option>
            </select>

          {/* Sort Order */}

            <ArrowUpDown size={16} className="text-slate-400" />
            <select
              value={sortOrder}
              onChange={(e) => handleSortOrderChange(e.target.value as 'newest' | 'oldest' | 'priority')}
              className="px-3 py-1.5 bg-slate-800 border border-slate-700 rounded-lg text-sm text-white focus:outline-none focus:ring-2 focus:ring-accent"
            >
              <option value="newest">Newest First</option>
              <option value="oldest">Oldest First</option>
              <option value="priority">By Priority</option>
            </select>

          {/* Reset Filters Button */}
          {hasActiveFilters && (
            <button
              onClick={handleResetFilters}
              className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-slate-400 hover:text-white hover:bg-slate-700 rounded-lg transition-colors"
              title="Reset Filters"
            >
              <RefreshCw size={14} />
              Reset
            </button>
          )}

          {/* View Mode Toggle */}

            <button
              onClick={() => handleViewModeChange('kanban')}
              className={`p-1.5 rounded ${viewMode === 'kanban' ? 'bg-accent text-white' : 'text-slate-400 hover:text-white'}`}
              title="Kanban View"
            >
              <LayoutGrid size={18} />
            </button>
            <button
              onClick={() => handleViewModeChange('list')}
              className={`p-1.5 rounded ${viewMode === 'list' ? 'bg-accent text-white' : 'text-slate-400 hover:text-white'}`}
              title="List View"
            >
              <List size={18} />
            </button>

        <Dialog.Root open={showAddDialog} onOpenChange={setShowAddDialog}>
          <Dialog.Trigger asChild>
            <button className="btn-accent flex items-center gap-2">
              <Plus size={18} />
              Add Task
            </button>
          </Dialog.Trigger>
          <Dialog.Portal>
            <Dialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
            <Dialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-slate-800 border border-slate-700 rounded-lg p-4 md:p-6 w-[calc(100%-2rem)] max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto z-50 shadow-xl">

                <Dialog.Title className="text-xl font-semibold text-white">
                  Add New Task
                </Dialog.Title>
                <Dialog.Close asChild>
                  <button className="text-slate-400 hover:text-white" aria-label="Close dialog">
                    <X size={20} />
                  </button>
                </Dialog.Close>

              <Dialog.Description className="text-slate-400 mb-4">
                Create a new task for this project.
              </Dialog.Description>

                    Task Name *

                  <input
                    type="text"
                    value={newTaskName}
                    onChange={(e) => setNewTaskName(e.target.value)}
                    className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
                    placeholder="Enter task name"
                  />

                    Description

                  <textarea
                    value={newTaskDescription}
                    onChange={(e) => setNewTaskDescription(e.target.value)}
                    rows={3}
                    className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent resize-none"
                    placeholder="Enter task description"
                  />

                    Priority

                  <select
                    value={newTaskPriority}
                    onChange={(e) => setNewTaskPriority(Number(e.target.value))}
                    className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
                  >
                    <option value={0}>Low</option>
                    <option value={1}>Medium</option>
                    <option value={2}>High</option>
                    <option value={3}>Critical</option>
                  </select>

                <Dialog.Close asChild>
                  <button className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors">
                    Cancel
                  </button>
                </Dialog.Close>
                <button
                  onClick={handleCreateTask}
                  disabled={isCreating || !newTaskName.trim()}
                  className="px-4 py-2 text-sm bg-accent hover:bg-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
                >
                  {isCreating ? 'Creating...' : 'Create Task'}
                </button>

            </Dialog.Content>
          </Dialog.Portal>
        </Dialog.Root>

      {/* Main Content Area */}

        {viewMode === 'list' ? (
          /* List View with Pagination */

            {/* Task List Table */}

                    Task Name
                    Status
                    Priority
                    Created

                  {isLoading && tasks.length === 0 ? (

                        Loading...

                  ) : paginatedTasks.length === 0 ? (

                        No tasks found

                  ) : (
                    paginatedTasks.map((task) => (

 handleSelectTask(task)}
                        className={`border-t border-slate-700 hover:bg-slate-700/50 cursor-pointer ${
                          selectedTask?.id === task.id ? 'bg-slate-700' : ''
                        }`}
                      >

{task.name}

                          {task.description && (

                              {task.description}

                          )}

                            {STATUS_LABELS[task.status] || task.status}

                            {PRIORITY_LABELS[task.priority] || 'Unknown'}

                          {new Date(task.created_at).toLocaleDateString()}

                    ))
                  )}

            {/* Pagination Controls */}
            {totalPages > 1 && (

                  Showing {((currentPage - 1) * ITEMS_PER_PAGE) + 1} to {Math.min(currentPage * ITEMS_PER_PAGE, filteredAndSortedTasks.length)} of {filteredAndSortedTasks.length} tasks

                  <button
                    onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
                    disabled={currentPage === 1}
                    className="p-2 rounded-lg bg-slate-800 border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <ChevronLeft size={18} />
                  </button>

                    {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page)}
                        className={`w-8 h-8 rounded-lg text-sm ${
                          page === currentPage
                            ? 'bg-accent text-white'
                            : 'bg-slate-800 border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700'
                        }`}
                      >
                        {page}
                      </button>
                    ))}

                  <button
                    onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
                    disabled={currentPage === totalPages}
                    className="p-2 rounded-lg bg-slate-800 border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <ChevronRight size={18} />
                  </button>

            )}

        ) : (
        /* Kanban Columns */
        <div className={`flex-1 flex gap-4 overflow-x-auto pb-4 ${selectedTask ? 'mr-0' : ''}`}>
          {COLUMNS.map((column) => (
          <div
            key={column.id}
            className={`flex-shrink-0 w-72 bg-slate-800 rounded-lg border-t-2 ${column.color}`}
            onDragOver={handleDragOver}
            onDrop={() => handleDrop(column.id)}
          >
            {/* Column Header */}

{column.title}

                  {getTasksByStatus(column.id).length}

            {/* Column Content */}

              {isLoading && tasks.length === 0 ? (

                  Loading...

              ) : getTasksByStatus(column.id).length === 0 ? (

                  No tasks

              ) : (
                getTasksByStatus(column.id).map((task) => (

 handleDragStart(task.id)}
                    onClick={() => handleSelectTask(task)}
                    className={`kanban-card bg-slate-900 rounded-lg p-4 border border-slate-700 cursor-pointer hover:border-slate-600 ${
                      draggedTask === task.id ? 'opacity-50' : ''
                    } ${selectedTask?.id === task.id ? 'ring-2 ring-accent' : ''}`}
                  >

                      <GripVertical size={16} className="text-slate-600 mt-0.5 flex-shrink-0" />

{task.name}

                        {task.description && (

                            {task.description}

                        )}

                          <span
                            className={`badge ${
                              column.id === 'backlog'
                                ? 'badge-backlog'
                                : column.id === 'in_progress'
                                ? 'badge-in-progress'
                                : column.id === 'qa'
                                ? 'badge-qa'
                                : column.id === 'done'
                                ? 'badge-done'
                                : 'badge-blocked'
                            }`}
                          >
                            {column.title}

                            {task.priority === 3 ? 'Critical' :
                             task.priority === 2 ? 'High' :
                             task.priority === 1 ? 'Medium' : 'Low'}

                ))
              )}

          ))}

        )}

        {/* Task Details Panel */}
        {selectedTask && (

Task Details

                {!isEditing && (
                  <>
                    <button
                      onClick={handleStartEdit}
                      className="text-slate-400 hover:text-accent transition-colors"
                      title="Edit Task"
                    >
                      <Pencil size={18} />
                    </button>
                    <AlertDialog.Root open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
                      <AlertDialog.Trigger asChild>
                        <button
                          className="text-slate-400 hover:text-destructive transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                          title="Delete Task"
                          disabled={isDeleting || (selectedTask ? isTaskDeleting(selectedTask.id) : false)}
                        >
                          <Trash2 size={18} />
                        </button>
                      </AlertDialog.Trigger>
                      <AlertDialog.Portal>
                        <AlertDialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
                        <AlertDialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-slate-800 border border-slate-700 rounded-lg p-4 md:p-6 w-[calc(100%-2rem)] max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto z-50 shadow-xl">
                          <AlertDialog.Title className="text-xl font-semibold text-white">
                            Delete Task
                          </AlertDialog.Title>
                          <AlertDialog.Description className="mt-3 text-slate-400">
                            Are you sure you want to delete {selectedTask.name}?
                            This action cannot be undone.
                          </AlertDialog.Description>

                            <AlertDialog.Cancel asChild>
                              <button className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors">
                                Cancel
                              </button>
                            </AlertDialog.Cancel>
                            <AlertDialog.Action asChild>
                              <button
                                onClick={handleDeleteTask}
                                disabled={isDeleting || (selectedTask ? isTaskDeleting(selectedTask.id) : false)}
                                className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors disabled:opacity-50"
                              >
                                {isDeleting || (selectedTask && isTaskDeleting(selectedTask.id)) ? 'Deleting...' : 'Delete Task'}
                              </button>
                            </AlertDialog.Action>

                        </AlertDialog.Content>
                      </AlertDialog.Portal>
                    </AlertDialog.Root>
                  </>
                )}
                <button
                  onClick={handleClosePanel}
                  className="text-slate-400 hover:text-white transition-colors"
                  title="Close"
                >
                  <X size={20} />
                </button>

              {isEditing ? (
                /* Edit Form */

                    Name *
                    <input
                      type="text"
                      value={editName}
                      onChange={(e) => setEditName(e.target.value)}
                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
                      placeholder="Task name"
                    />

                    Description
                    <textarea
                      value={editDescription}
                      onChange={(e) => setEditDescription(e.target.value)}
                      rows={3}
                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent resize-none"
                      placeholder="Task description"
                    />

                    Priority
                    <select
                      value={editPriority}
                      onChange={(e) => setEditPriority(Number(e.target.value))}
                      className="w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-accent focus:border-transparent"
                    >
                      <option value={0}>Low</option>
                      <option value={1}>Medium</option>
                      <option value={2}>High</option>
                      <option value={3}>Critical</option>
                    </select>

                    <button
                      onClick={handleCancelEdit}
                      className="flex-1 px-3 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
                    >
                      Cancel
                    </button>
                    <button
                      onClick={handleSaveEdit}
                      disabled={isSaving || !editName.trim()}
                      className="flex-1 flex items-center justify-center gap-2 px-3 py-2 text-sm bg-accent hover:bg-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
                    >
                      {isSaving ? 'Saving...' : <><Check size={16} /> Save</>}
                    </button>

              ) : (
                /* View Mode */
                <>
                  {/* Task Name */}

                    Name

{selectedTask.name}

                  {/* Description */}

                    Description

                      {selectedTask.description || No description}

                  {/* Status */}

                    Status

                      {STATUS_LABELS[selectedTask.status] || selectedTask.status}

                  {/* Priority */}

                    Priority

                      {PRIORITY_LABELS[selectedTask.priority] || 'Unknown'}

                  {/* Agent Assignment */}

                      <User size={14} />
                      Agent Assignment

                      {selectedTask.agent_type ? (
                        {selectedTask.agent_type.replace('_', ' ')}
                      ) : (
                        Not assigned
                      )}

                  {/* Iteration Count */}

                      <RefreshCw size={14} />
                      Iteration Count

{selectedTask.iteration_count}

                  {/* Flagged for Review */}

                      <Flag size={14} />
                      Flagged for Review

                      {selectedTask.flagged_for_review ? 'Yes' : 'No'}

                  {/* Time Estimates */}
                  {(selectedTask.estimated_time || selectedTask.actual_time) && (

                        <Clock size={14} />
                        Time

                        {selectedTask.estimated_time &&
Estimated: {selectedTask.estimated_time} min
}
                        {selectedTask.actual_time &&
Actual: {selectedTask.actual_time} min
}

                  )}

                  {/* Created/Updated timestamps */}

Created: {new Date(selectedTask.created_at).toLocaleString()}

Updated: {new Date(selectedTask.updated_at).toLocaleString()}

                </>
              )}

        )}

        {/* Unsaved Changes Warning Dialog */}
        <AlertDialog.Root open={showUnsavedDialog} onOpenChange={setShowUnsavedDialog}>
          <AlertDialog.Portal>
            <AlertDialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
            <AlertDialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 bg-slate-800 border border-slate-700 rounded-lg p-4 md:p-6 w-[calc(100%-2rem)] max-w-md max-h-[calc(100vh-2rem)] overflow-y-auto z-50 shadow-xl">
              <AlertDialog.Title className="text-xl font-semibold text-white">
                Unsaved Changes
              </AlertDialog.Title>
              <AlertDialog.Description className="mt-3 text-slate-400">
                You have unsaved changes. Are you sure you want to discard them?
              </AlertDialog.Description>

                <AlertDialog.Cancel asChild>
                  <button
                    onClick={handleKeepEditing}
                    className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
                  >
                    Keep Editing
                  </button>
                </AlertDialog.Cancel>
                <AlertDialog.Action asChild>
                  <button
                    onClick={handleDiscardChanges}
                    className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors"
                  >
                    Discard Changes
                  </button>
                </AlertDialog.Action>

            </AlertDialog.Content>
          </AlertDialog.Portal>
        </AlertDialog.Root>

  )
}