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→
     9→const ITEMS_PER_PAGE = 10
    10→
    11→const COLUMNS = [
    12→  { id: 'backlog', title: 'Backlog', color: 'border-slate-500' },
    13→  { id: 'in_progress', title: 'In Progress', color: 'border-accent' },
    14→  { id: 'qa', title: 'QA', color: 'border-primary-400' },
    15→  { id: 'done', title: 'Done', color: 'border-green-400' },
    16→  { id: 'blocked', title: 'Blocked', color: 'border-destructive' },
    17→]
    18→
    19→const PRIORITY_LABELS: Record<number, string> = {
    20→  0: 'Low',
    21→  1: 'Medium',
    22→  2: 'High',
    23→  3: 'Critical',
    24→}
    25→
    26→const STATUS_LABELS: Record<string, string> = {
    27→  backlog: 'Backlog',
    28→  in_progress: 'In Progress',
    29→  qa: 'QA',
    30→  done: 'Done',
    31→  blocked: 'Blocked',
    32→}
    33→
    34→export default function KanbanBoard() {
    35→  const [searchParams, setSearchParams] = useSearchParams()
    36→  const { currentProject } = useProjectStore()
    37→  const { tasks, fetchTasks, createTask, updateTask, updateTaskStatus, deleteTask, isLoading } = useTaskStore()
    38→  const [showAddDialog, setShowAddDialog] = useState(false)
    39→  const [newTaskName, setNewTaskName] = useState('')
    40→  const [newTaskDescription, setNewTaskDescription] = useState('')
    41→  const [newTaskPriority, setNewTaskPriority] = useState(0)
    42→  const [isCreating, setIsCreating] = useState(false)
    43→  const [draggedTask, setDraggedTask] = useState<number | null>(null)
    44→  const [selectedTask, setSelectedTask] = useState<Task | null>(null)
    45→  const [isEditing, setIsEditing] = useState(false)
    46→  const [editName, setEditName] = useState('')
    47→  const [editDescription, setEditDescription] = useState('')
    48→  const [editPriority, setEditPriority] = useState(0)
    49→  const [isSaving, setIsSaving] = useState(false)
    50→  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
    51→  const [isDeleting, setIsDeleting] = useState(false)
    52→  const [showUnsavedDialog, setShowUnsavedDialog] = useState(false)
    53→  const [pendingCloseAction, setPendingCloseAction] = useState<'close' | 'cancel' | null>(null)
    54→  // Filter and Sort state
    55→  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>('all')
    56→  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>('newest')
    57→  // View mode and pagination state
    58→  const [viewMode, setViewMode] = useState<'kanban' | 'list'>('kanban')
    59→  const [currentPage, setCurrentPage] = useState(1)
    60→
    61→  useEffect(() => {
    62→    if (currentProject?.id) {
    63→      fetchTasks(currentProject.id)
    64→    }
    65→  }, [currentProject?.id, fetchTasks])
    66→
    67→  // Handle deep linking - select task from URL param after tasks are loaded
    68→  useEffect(() => {
    69→    const taskIdParam = searchParams.get('task')
    70→    if (taskIdParam && tasks.length > 0) {
    71→      const taskId = parseInt(taskIdParam, 10)
    72→      const task = tasks.find(t => t.id === taskId)
    73→      if (task) {
    74→        setSelectedTask(task)
    75→      }
    76→    }
    77→  }, [searchParams, tasks])
    78→
    79→  // Update URL when task is selected
    80→  const handleSelectTask = (task: Task) => {
    81→    setSelectedTask(task)
    82→    const newParams = new URLSearchParams(searchParams)
    83→    newParams.set('task', task.id.toString())
    84→    setSearchParams(newParams)
    85→  }
    86→
    87→  // Clear task from URL when panel is closed
    88→  const clearTaskFromUrl = () => {
    89→    const newParams = new URLSearchParams(searchParams)
    90→    newParams.delete('task')
    91→    setSearchParams(newParams)
    92→  }
    93→
    94→  // Filtered and sorted tasks
    95→  const filteredAndSortedTasks = useMemo(() => {
    96→    let result = [...tasks]
    97→
    98→    // Apply priority filter
    99→    if (priorityFilter !== 'all') {
   100→      result = result.filter(task => task.priority === priorityFilter)
   101→    }
   102→
   103→    // Apply sort
   104→    result.sort((a, b) => {
   105→      if (sortOrder === 'newest') {
   106→        return new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
   107→      } else if (sortOrder === 'oldest') {
   108→        return new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
   109→      } else {
   110→        // priority - highest first
   111→        return b.priority - a.priority
   112→      }
   113→    })
   114→
   115→    return result
   116→  }, [tasks, priorityFilter, sortOrder])
   117→
   118→  // Pagination calculations
   119→  const totalPages = Math.ceil(filteredAndSortedTasks.length / ITEMS_PER_PAGE)
   120→  const paginatedTasks = useMemo(() => {
   121→    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE
   122→    return filteredAndSortedTasks.slice(startIndex, startIndex + ITEMS_PER_PAGE)
   123→  }, [filteredAndSortedTasks, currentPage])
   124→
   125→  // Reset page when filter changes
   126→  useEffect(() => {
   127→    setCurrentPage(1)
   128→  }, [priorityFilter, sortOrder])
   129→
   130→  const getTasksByStatus = (status: string) => {
   131→    return filteredAndSortedTasks.filter((task) => task.status === status)
   132→  }
   133→
   134→  const handleCreateTask = async () => {
   135→    if (!currentProject || !newTaskName.trim()) return
   136→    setIsCreating(true)
   137→    try {
   138→      const taskData: TaskCreate = {
   139→        name: newTaskName.trim(),
   140→        description: newTaskDescription.trim() || undefined,
   141→        priority: newTaskPriority,
   142→      }
   143→      await createTask(currentProject.id, taskData)
   144→      setNewTaskName('')
   145→      setNewTaskDescription('')
   146→      setNewTaskPriority(0)
   147→      setShowAddDialog(false)
   148→    } catch (error) {
   149→      console.error('Failed to create task:', error)
   150→    } finally {
   151→      setIsCreating(false)
   152→    }
   153→  }
   154→
   155→  const handleDragStart = (taskId: number) => {
   156→    setDraggedTask(taskId)
   157→  }
   158→
   159→  const handleDragOver = (e: React.DragEvent) => {
   160→    e.preventDefault()
   161→  }
   162→
   163→  const handleDrop = async (targetStatus: string) => {
   164→    if (draggedTask === null) return
   165→    try {
   166→      await updateTaskStatus(draggedTask, targetStatus)
   167→    } catch (error) {
   168→      console.error('Failed to update task status:', error)
   169→    }
   170→    setDraggedTask(null)
   171→  }
   172→
   173→  const handleStartEdit = () => {
   174→    if (!selectedTask) return
   175→    setEditName(selectedTask.name)
   176→    setEditDescription(selectedTask.description || '')
   177→    setEditPriority(selectedTask.priority)
   178→    setIsEditing(true)
   179→  }
   180→
   181→  // Check if edit form has unsaved changes
   182→  const hasUnsavedChanges = () => {
   183→    if (!selectedTask || !isEditing) return false
   184→    return (
   185→      editName.trim() !== selectedTask.name ||
   186→      (editDescription.trim() || '') !== (selectedTask.description || '') ||
   187→      editPriority !== selectedTask.priority
   188→    )
   189→  }
   190→
   191→  const handleCancelEdit = () => {
   192→    if (hasUnsavedChanges()) {
   193→      setPendingCloseAction('cancel')
   194→      setShowUnsavedDialog(true)
   195→    } else {
   196→      setIsEditing(false)
   197→    }
   198→  }
   199→
   200→  const handleClosePanel = () => {
   201→    if (hasUnsavedChanges()) {
   202→      setPendingCloseAction('close')
   203→      setShowUnsavedDialog(true)
   204→    } else {
   205→      setSelectedTask(null)
   206→      setIsEditing(false)
   207→      clearTaskFromUrl()
   208→    }
   209→  }
   210→
   211→  const handleDiscardChanges = () => {
   212→    setShowUnsavedDialog(false)
   213→    if (pendingCloseAction === 'close') {
   214→      setSelectedTask(null)
   215→      clearTaskFromUrl()
   216→    }
   217→    setIsEditing(false)
   218→    setPendingCloseAction(null)
   219→  }
   220→
   221→  const handleKeepEditing = () => {
   222→    setShowUnsavedDialog(false)
   223→    setPendingCloseAction(null)
   224→  }
   225→
   226→  const handleSaveEdit = async () => {
   227→    if (!selectedTask) return
   228→    setIsSaving(true)
   229→    try {
   230→      const updates: TaskUpdate = {
   231→        name: editName.trim(),
   232→        description: editDescription.trim() || undefined,
   233→        priority: editPriority,
   234→      }
   235→      const updatedTask = await updateTask(selectedTask.id, updates)
   236→      setSelectedTask(updatedTask)
   237→      setIsEditing(false)
   238→    } catch (error) {
   239→      console.error('Failed to update task:', error)
   240→    } finally {
   241→      setIsSaving(false)
   242→    }
   243→  }
   244→
   245→  const handleDeleteTask = async () => {
   246→    if (!selectedTask) return
   247→    setIsDeleting(true)
   248→    try {
   249→      await deleteTask(selectedTask.id)
   250→      setSelectedTask(null)
   251→      setShowDeleteDialog(false)
   252→    } catch (error) {
   253→      console.error('Failed to delete task:', error)
   254→    } finally {
   255→      setIsDeleting(false)
   256→    }
   257→  }
   258→
   259→  if (!currentProject) {
   260→    return (
   261→

   262→
Select a project to view its Kanban board

   263→

   264→    )
   265→  }
   266→
   267→  return (
   268→

   269→      {/* Header */}
   270→

   271→
Kanban Board

   272→

   273→          {/* Priority Filter */}
   274→

   275→            <Filter size={16} className="text-slate-400" />
   276→            <select
   277→              value={priorityFilter === 'all' ? 'all' : priorityFilter.toString()}
   278→              onChange={(e) => setPriorityFilter(e.target.value === 'all' ? 'all' : Number(e.target.value))}
   279→              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"
   280→            >
   281→              <option value="all">All Priorities</option>
   282→              <option value="3">Critical</option>
   283→              <option value="2">High</option>
   284→              <option value="1">Medium</option>
   285→              <option value="0">Low</option>
   286→            </select>
   287→

   288→
   289→          {/* Sort Order */}
   290→

   291→            <ArrowUpDown size={16} className="text-slate-400" />
   292→            <select
   293→              value={sortOrder}
   294→              onChange={(e) => setSortOrder(e.target.value as 'newest' | 'oldest' | 'priority')}
   295→              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"
   296→            >
   297→              <option value="newest">Newest First</option>
   298→              <option value="oldest">Oldest First</option>
   299→              <option value="priority">By Priority</option>
   300→            </select>
   301→

   302→
   303→          {/* View Mode Toggle */}
   304→

   305→            <button
   306→              onClick={() => setViewMode('kanban')}
   307→              className={`p-1.5 rounded ${viewMode === 'kanban' ? 'bg-accent text-white' : 'text-slate-400 hover:text-white'}`}
   308→              title="Kanban View"
   309→            >
   310→              <LayoutGrid size={18} />
   311→            </button>
   312→            <button
   313→              onClick={() => setViewMode('list')}
   314→              className={`p-1.5 rounded ${viewMode === 'list' ? 'bg-accent text-white' : 'text-slate-400 hover:text-white'}`}
   315→              title="List View"
   316→            >
   317→              <List size={18} />
   318→            </button>
   319→

   320→
   321→        <Dialog.Root open={showAddDialog} onOpenChange={setShowAddDialog}>
   322→          <Dialog.Trigger asChild>
   323→            <button className="btn-accent flex items-center gap-2">
   324→              <Plus size={18} />
   325→              Add Task
   326→            </button>
   327→          </Dialog.Trigger>
   328→          <Dialog.Portal>
   329→            <Dialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
   330→            <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-6 w-full max-w-md z-50 shadow-xl">
   331→

   332→                <Dialog.Title className="text-xl font-semibold text-white">
   333→                  Add New Task
   334→                </Dialog.Title>
   335→                <Dialog.Close asChild>
   336→                  <button className="text-slate-400 hover:text-white">
   337→                    <X size={20} />
   338→                  </button>
   339→                </Dialog.Close>
   340→

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

   345→

   346→
   347→                    Task Name *
   348→
   349→                  <input
   350→                    type="text"
   351→                    value={newTaskName}
   352→                    onChange={(e) => setNewTaskName(e.target.value)}
   353→                    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"
   354→                    placeholder="Enter task name"
   355→                  />
   356→

   357→

   358→
   359→                    Description
   360→
   361→                  <textarea
   362→                    value={newTaskDescription}
   363→                    onChange={(e) => setNewTaskDescription(e.target.value)}
   364→                    rows={3}
   365→                    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"
   366→                    placeholder="Enter task description"
   367→                  />
   368→

   369→

   370→
   371→                    Priority
   372→
   373→                  <select
   374→                    value={newTaskPriority}
   375→                    onChange={(e) => setNewTaskPriority(Number(e.target.value))}
   376→                    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"
   377→                  >
   378→                    <option value={0}>Low</option>
   379→                    <option value={1}>Medium</option>
   380→                    <option value={2}>High</option>
   381→                    <option value={3}>Critical</option>
   382→                  </select>
   383→

   384→

   385→

   386→                <Dialog.Close asChild>
   387→                  <button className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors">
   388→                    Cancel
   389→                  </button>
   390→                </Dialog.Close>
   391→                <button
   392→                  onClick={handleCreateTask}
   393→                  disabled={isCreating || !newTaskName.trim()}
   394→                  className="px-4 py-2 text-sm bg-accent hover:bg-accent/80 text-white rounded-lg transition-colors disabled:opacity-50"
   395→                >
   396→                  {isCreating ? 'Creating...' : 'Create Task'}
   397→                </button>
   398→

   399→            </Dialog.Content>
   400→          </Dialog.Portal>
   401→        </Dialog.Root>
   402→

   403→

   404→
   405→      {/* Main Content Area */}
   406→

   407→        {viewMode === 'list' ? (
   408→          /* List View with Pagination */
   409→

   410→            {/* Task List Table */}
   411→

   412→

   413→

   414→

   415→                    Task Name
   416→                    Status
   417→                    Priority
   418→                    Created
   419→

   420→

   421→

   422→                  {isLoading && tasks.length === 0 ? (
   423→

   424→
   425→                        Loading...
   426→
   427→

   428→                  ) : paginatedTasks.length === 0 ? (
   429→

   430→
   431→                        No tasks found
   432→
   433→

   434→                  ) : (
   435→                    paginatedTasks.map((task) => (
   436→
 handleSelectTask(task)}
   439→                        className={`border-t border-slate-700 hover:bg-slate-700/50 cursor-pointer ${
   440→                          selectedTask?.id === task.id ? 'bg-slate-700' : ''
   441→                        }`}
   442→                      >
   443→
   444→
{task.name}

   445→                          {task.description && (
   446→

   447→                              {task.description}
   448→

   449→                          )}
   450→
   451→
   452→
   459→                            {STATUS_LABELS[task.status] || task.status}
   460→
   461→
   462→
   463→
   469→                            {PRIORITY_LABELS[task.priority] || 'Unknown'}
   470→
   471→
   472→
   473→                          {new Date(task.created_at).toLocaleDateString()}
   474→
   475→

   476→                    ))
   477→                  )}
   478→

   479→

   480→

   481→
   482→            {/* Pagination Controls */}
   483→            {totalPages > 1 && (
   484→

   485→

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

   488→

   489→                  <button
   490→                    onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
   491→                    disabled={currentPage === 1}
   492→                    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"
   493→                  >
   494→                    <ChevronLeft size={18} />
   495→                  </button>
   496→

   497→                    {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
   498→                      <button
   499→                        key={page}
   500→                        onClick={() => setCurrentPage(page)}
   501→                        className={`w-8 h-8 rounded-lg text-sm ${
   502→                          page === currentPage
   503→                            ? 'bg-accent text-white'
   504→                            : 'bg-slate-800 border border-slate-700 text-slate-400 hover:text-white hover:bg-slate-700'
   505→                        }`}
   506→                      >
   507→                        {page}
   508→                      </button>
   509→                    ))}
   510→

   511→                  <button
   512→                    onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
   513→                    disabled={currentPage === totalPages}
   514→                    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"
   515→                  >
   516→                    <ChevronRight size={18} />
   517→                  </button>
   518→

   519→

   520→            )}
   521→

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

   534→

   535→
{column.title}

   536→
   537→                  {getTasksByStatus(column.id).length}
   538→
   539→

   540→

   541→
   542→            {/* Column Content */}
   543→

   544→              {isLoading && tasks.length === 0 ? (
   545→

   546→                  Loading...
   547→

   548→              ) : getTasksByStatus(column.id).length === 0 ? (
   549→

   550→                  No tasks
   551→

   552→              ) : (
   553→                getTasksByStatus(column.id).map((task) => (
   554→
 handleDragStart(task.id)}
   558→                    onClick={() => handleSelectTask(task)}
   559→                    className={`kanban-card bg-slate-900 rounded-lg p-4 border border-slate-700 cursor-pointer hover:border-slate-600 ${
   560→                      draggedTask === task.id ? 'opacity-50' : ''
   561→                    } ${selectedTask?.id === task.id ? 'ring-2 ring-accent' : ''}`}
   562→                  >
   563→

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

   566→
{task.name}

   567→                        {task.description && (
   568→

   569→                            {task.description}
   570→

   571→                        )}
   572→

   573→                          <span
   574→                            className={`badge ${
   575→                              column.id === 'backlog'
   576→                                ? 'badge-backlog'
   577→                                : column.id === 'in_progress'
   578→                                ? 'badge-in-progress'
   579→                                : column.id === 'qa'
   580→                                ? 'badge-qa'
   581→                                : column.id === 'done'
   582→                                ? 'badge-done'
   583→                                : 'badge-blocked'
   584→                            }`}
   585→                          >
   586→                            {column.title}
   587→
   588→
   594→                            {task.priority === 3 ? 'Critical' :
   595→                             task.priority === 2 ? 'High' :
   596→                             task.priority === 1 ? 'Medium' : 'Low'}
   597→
   598→

   599→

   600→

   601→

   602→                ))
   603→              )}
   604→

   605→

   606→          ))}
   607→

   608→        )}
   609→
   610→        {/* Task Details Panel */}
   611→        {selectedTask && (
   612→

   613→

   614→
Task Details

   615→

   616→                {!isEditing && (
   617→                  <>
   618→                    <button
   619→                      onClick={handleStartEdit}
   620→                      className="text-slate-400 hover:text-accent transition-colors"
   621→                      title="Edit Task"
   622→                    >
   623→                      <Pencil size={18} />
   624→                    </button>
   625→                    <AlertDialog.Root open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
   626→                      <AlertDialog.Trigger asChild>
   627→                        <button
   628→                          className="text-slate-400 hover:text-destructive transition-colors"
   629→                          title="Delete Task"
   630→                        >
   631→                          <Trash2 size={18} />
   632→                        </button>
   633→                      </AlertDialog.Trigger>
   634→                      <AlertDialog.Portal>
   635→                        <AlertDialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
   636→                        <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-6 w-full max-w-md z-50 shadow-xl">
   637→                          <AlertDialog.Title className="text-xl font-semibold text-white">
   638→                            Delete Task
   639→                          </AlertDialog.Title>
   640→                          <AlertDialog.Description className="mt-3 text-slate-400">
   641→                            Are you sure you want to delete {selectedTask.name}?
   642→                            This action cannot be undone.
   643→                          </AlertDialog.Description>
   644→

   645→                            <AlertDialog.Cancel asChild>
   646→                              <button className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors">
   647→                                Cancel
   648→                              </button>
   649→                            </AlertDialog.Cancel>
   650→                            <AlertDialog.Action asChild>
   651→                              <button
   652→                                onClick={handleDeleteTask}
   653→                                disabled={isDeleting}
   654→                                className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors disabled:opacity-50"
   655→                              >
   656→                                {isDeleting ? 'Deleting...' : 'Delete Task'}
   657→                              </button>
   658→                            </AlertDialog.Action>
   659→

   660→                        </AlertDialog.Content>
   661→                      </AlertDialog.Portal>
   662→                    </AlertDialog.Root>
   663→                  </>
   664→                )}
   665→                <button
   666→                  onClick={handleClosePanel}
   667→                  className="text-slate-400 hover:text-white transition-colors"
   668→                  title="Close"
   669→                >
   670→                  <X size={20} />
   671→                </button>
   672→

   673→

   674→

   675→              {isEditing ? (
   676→                /* Edit Form */
   677→

   678→

   679→                    Name *
   680→                    <input
   681→                      type="text"
   682→                      value={editName}
   683→                      onChange={(e) => setEditName(e.target.value)}
   684→                      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"
   685→                      placeholder="Task name"
   686→                    />
   687→

   688→

   689→                    Description
   690→                    <textarea
   691→                      value={editDescription}
   692→                      onChange={(e) => setEditDescription(e.target.value)}
   693→                      rows={3}
   694→                      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"
   695→                      placeholder="Task description"
   696→                    />
   697→

   698→

   699→                    Priority
   700→                    <select
   701→                      value={editPriority}
   702→                      onChange={(e) => setEditPriority(Number(e.target.value))}
   703→                      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"
   704→                    >
   705→                      <option value={0}>Low</option>
   706→                      <option value={1}>Medium</option>
   707→                      <option value={2}>High</option>
   708→                      <option value={3}>Critical</option>
   709→                    </select>
   710→

   711→

   712→                    <button
   713→                      onClick={handleCancelEdit}
   714→                      className="flex-1 px-3 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
   715→                    >
   716→                      Cancel
   717→                    </button>
   718→                    <button
   719→                      onClick={handleSaveEdit}
   720→                      disabled={isSaving || !editName.trim()}
   721→                      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"
   722→                    >
   723→                      {isSaving ? 'Saving...' : <><Check size={16} /> Save</>}
   724→                    </button>
   725→

   726→

   727→              ) : (
   728→                /* View Mode */
   729→                <>
   730→                  {/* Task Name */}
   731→

   732→                    Name
   733→
{selectedTask.name}

   734→

   735→
   736→                  {/* Description */}
   737→

   738→                    Description
   739→

   740→                      {selectedTask.description || No description}
   741→

   742→

   743→
   744→                  {/* Status */}
   745→

   746→                    Status
   747→
   754→                      {STATUS_LABELS[selectedTask.status] || selectedTask.status}
   755→
   756→

   757→
   758→                  {/* Priority */}
   759→

   760→                    Priority
   761→
   767→                      {PRIORITY_LABELS[selectedTask.priority] || 'Unknown'}
   768→
   769→

   770→
   771→                  {/* Agent Assignment */}
   772→

   773→
   774→                      <User size={14} />
   775→                      Agent Assignment
   776→
   777→

   778→                      {selectedTask.agent_type ? (
   779→                        {selectedTask.agent_type.replace('_', ' ')}
   780→                      ) : (
   781→                        Not assigned
   782→                      )}
   783→

   784→

   785→
   786→                  {/* Iteration Count */}
   787→

   788→
   789→                      <RefreshCw size={14} />
   790→                      Iteration Count
   791→
   792→
{selectedTask.iteration_count}

   793→

   794→
   795→                  {/* Flagged for Review */}
   796→

   797→
   798→                      <Flag size={14} />
   799→                      Flagged for Review
   800→
   801→

   802→                      {selectedTask.flagged_for_review ? 'Yes' : 'No'}
   803→

   804→

   805→
   806→                  {/* Time Estimates */}
   807→                  {(selectedTask.estimated_time || selectedTask.actual_time) && (
   808→

   809→
   810→                        <Clock size={14} />
   811→                        Time
   812→
   813→

   814→                        {selectedTask.estimated_time &&
Estimated: {selectedTask.estimated_time} min
}
   815→                        {selectedTask.actual_time &&
Actual: {selectedTask.actual_time} min
}
   816→

   817→

   818→                  )}
   819→
   820→                  {/* Created/Updated timestamps */}
   821→

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

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

   824→

   825→                </>
   826→              )}
   827→

   828→

   829→        )}
   830→
   831→        {/* Unsaved Changes Warning Dialog */}
   832→        <AlertDialog.Root open={showUnsavedDialog} onOpenChange={setShowUnsavedDialog}>
   833→          <AlertDialog.Portal>
   834→            <AlertDialog.Overlay className="fixed inset-0 bg-black/50 z-50" />
   835→            <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-6 w-full max-w-md z-50 shadow-xl">
   836→              <AlertDialog.Title className="text-xl font-semibold text-white">
   837→                Unsaved Changes
   838→              </AlertDialog.Title>
   839→              <AlertDialog.Description className="mt-3 text-slate-400">
   840→                You have unsaved changes. Are you sure you want to discard them?
   841→              </AlertDialog.Description>
   842→

   843→                <AlertDialog.Cancel asChild>
   844→                  <button
   845→                    onClick={handleKeepEditing}
   846→                    className="px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 rounded-lg transition-colors"
   847→                  >
   848→                    Keep Editing
   849→                  </button>
   850→                </AlertDialog.Cancel>
   851→                <AlertDialog.Action asChild>
   852→                  <button
   853→                    onClick={handleDiscardChanges}
   854→                    className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors"
   855→                  >
   856→                    Discard Changes
   857→                  </button>
   858→                </AlertDialog.Action>
   859→

   860→            </AlertDialog.Content>
   861→          </AlertDialog.Portal>
   862→        </AlertDialog.Root>
   863→

   864→

   865→  )
   866→}
   867→

<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'

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, isLoading } = useTaskStore()
  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
  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>('all')
  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>('newest')
  // View mode and pagination state
  const [viewMode, setViewMode] = useState<'kanban' | 'list'>('kanban')
  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)
  }

  // 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)
    } 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)
    }
    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)
    } finally {
      setIsSaving(false)
    }
  }

  const handleDeleteTask = async () => {
    if (!selectedTask) return
    setIsDeleting(true)
    try {
      await deleteTask(selectedTask.id)
      setSelectedTask(null)
      setShowDeleteDialog(false)
    } catch (error) {
      console.error('Failed to delete task:', error)
    } 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) => setPriorityFilter(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) => setSortOrder(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>

          {/* View Mode Toggle */}

            <button
              onClick={() => setViewMode('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={() => setViewMode('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-6 w-full max-w-md 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">
                    <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"
                          title="Delete Task"
                        >
                          <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-6 w-full max-w-md 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}
                                className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors disabled:opacity-50"
                              >
                                {isDeleting ? '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-6 w-full max-w-md 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>

  )
}


Now I need to add URL filter params. I'll modify the code to:
1. Read filter/sort params from URL on load
2. Update URL when filter/sort changes
3. Support view mode in URL as well


Edit

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

  // 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)


The file C:\Users\MikeSwanson\AutoBuilder\My-Auto-Builder\frontend\src\pages\KanbanBoard.tsx has been updated. Here's the result of running `cat -n` on a snippet of the edited file:
    50→  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
    51→  const [isDeleting, setIsDeleting] = useState(false)
    52→  const [showUnsavedDialog, setShowUnsavedDialog] = useState(false)
    53→  const [pendingCloseAction, setPendingCloseAction] = useState<'close' | 'cancel' | null>(null)
    54→  // Filter and Sort state - initialize from URL params
    55→  const getInitialPriorityFilter = (): number | 'all' => {
    56→    const param = searchParams.get('priority')
    57→    if (param === 'all' || param === null) return 'all'
    58→    const num = parseInt(param, 10)
    59→    return [0, 1, 2, 3].includes(num) ? num : 'all'
    60→  }
    61→  const getInitialSortOrder = (): 'newest' | 'oldest' | 'priority' => {
    62→    const param = searchParams.get('sort')
    63→    if (param === 'newest' || param === 'oldest' || param === 'priority') return param
    64→    return 'newest'
    65→  }
    66→  const getInitialViewMode = (): 'kanban' | 'list' => {
    67→    const param = searchParams.get('view')
    68→    if (param === 'list') return 'list'
    69→    return 'kanban'
    70→  }
    71→
    72→  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>(getInitialPriorityFilter)
    73→  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>(getInitialSortOrder)
    74→  // View mode and pagination state
    75→  const [viewMode, setViewMode] = useState<'kanban' | 'list'>(getInitialViewMode)
    76→  const [currentPage, setCurrentPage] = useState(1)
    77→
    78→  useEffect(() => {
    79→    if (currentProject?.id) {
    80→      fetchTasks(currentProject.id)

  // 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)

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'

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, isLoading } = useTaskStore()
  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
  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>('all')
  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>('newest')
  // View mode and pagination state
  const [viewMode, setViewMode] = useState<'kanban' | 'list'>('kanban')
  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)
  }

  // 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)
    } 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)
    }
    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)
    } finally {
      setIsSaving(false)
    }
  }

  const handleDeleteTask = async () => {
    if (!selectedTask) return
    setIsDeleting(true)
    try {
      await deleteTask(selectedTask.id)
      setSelectedTask(null)
      setShowDeleteDialog(false)
    } catch (error) {
      console.error('Failed to delete task:', error)
    } 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) => setPriorityFilter(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) => setSortOrder(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>

          {/* View Mode Toggle */}

            <button
              onClick={() => setViewMode('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={() => setViewMode('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-6 w-full max-w-md 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">
                    <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"
                          title="Delete Task"
                        >
                          <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-6 w-full max-w-md 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}
                                className="px-4 py-2 text-sm bg-destructive hover:bg-destructive/80 text-white rounded-lg transition-colors disabled:opacity-50"
                              >
                                {isDeleting ? '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-6 w-full max-w-md 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>

  )
}

-  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>('all')

-  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>('newest')

+  // Filter and Sort state - initialize from URL params

+  const getInitialPriorityFilter = (): number | 'all' => {

+    const param = searchParams.get('priority')

+    if (param === 'all' || param === null) return 'all'

+    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

+  const getInitialViewMode = (): 'kanban' | 'list' => {

+    const param = searchParams.get('view')

+    if (param === 'list') return 'list'

+  const [priorityFilter, setPriorityFilter] = useState<number | 'all'>(getInitialPriorityFilter)

+  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest' | 'priority'>(getInitialSortOrder)

-  const [viewMode, setViewMode] = useState<'kanban' | 'list'>('kanban')

+  const [viewMode, setViewMode] = useState<'kanban' | 'list'>(getInitialViewMode)


Now I need to add functions to update URL when filters change. Let me add those helper functions and update the filter change handlers:


  // Clear task from URL when panel is closed
  const clearTaskFromUrl = () => {
    const newParams = new URLSearchParams(searchParams)
    newParams.delete('task')
    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)
  }