1	import { useState, useEffect, useCallback } from 'react';
2	import {
3	  DndContext, DragOverlay, useDroppable, useDraggable,
4	  PointerSensor, TouchSensor, useSensor, useSensors, closestCenter
5	} from '@dnd-kit/core';
6	import {
7	  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
8	  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical
9	} from 'lucide-react';
10	import { Link, useNavigate } from 'react-router-dom';
11	import toast from 'react-hot-toast';
12	import api from '../api';
13	import TaskModal from './TaskModal';
14	import ConfirmDialog from './ConfirmDialog';
15	import { getCategoryClass, getPriorityClass, CATEGORIES, formatDate, isOverdue } from '../utils';
16
17	// ── Column config ────────────────────────────────────────────────────────────
18	const COLUMNS = [
19	  { id: 'focus',      title: "Today's Focus", color: 'text-primary',    bg: 'bg-primary/10',  border: 'border-l-primary'  },
20	  { id: 'inprogress', title: 'In Progress',   color: 'text-blue-600',   bg: 'bg-blue-50 dark:bg-blue-900/20',   border: 'border-l-blue-400'   },
21	  { id: 'followups',  title: 'Follow-ups',    color: 'text-amber-600',  bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-l-amber-400'  },
22	  { id: 'open',       title: 'Open',          color: 'text-gray-500',   bg: 'bg-gray-100 dark:bg-gray-800',     border: 'border-l-gray-300'   },
23	];
24
25	const PRIORITY_BORDER = { Urgent:'border-l-red-500', High:'border-l-amber-400', Medium:'border-l-blue-400', Low:'border-l-green-400' };
26
27	function getColumnId(task) {
28	  if (task.status === 'Done') return null;
29	  if (task.is_today_focus)    return 'focus';
30	  if (task.status === 'In Progress') return 'inprogress';
31	  if (task.is_follow_up)      return 'followups';
32	  return 'open';
33	}
34
35	function columnUpdates(col, task) {
36	  const base = { ...task };
37	  if (col === 'focus')      return { ...base, is_today_focus: 1 };
38	  if (col === 'inprogress') return { ...base, status: 'In Progress', is_today_focus: 0 };
39	  if (col === 'followups')  return { ...base, is_follow_up: 1,  is_today_focus: 0 };
40	  if (col === 'open')       return { ...base, is_today_focus: 0, status: 'Open' };
41	  return base;
42	}
43
44	// ── Draggable card ───────────────────────────────────────────────────────────
45	function DraggableCard({ task, onEdit, onDelete, onMarkDone }) {
46	  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: task.id });
47	  const overdue = isOverdue(task.due_date);
48
49	  return (
50

58

59

60	          {/* Drag handle */}

import { useState, useEffect, useCallback } from 'react';
import {
  DndContext, DragOverlay, useDroppable, useDraggable,
  PointerSensor, TouchSensor, useSensor, useSensors, closestCenter
} from '@dnd-kit/core';
import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical
} from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import api from '../api';
import TaskModal from './TaskModal';
import ConfirmDialog from './ConfirmDialog';
import { getCategoryClass, getPriorityClass, CATEGORIES, formatDate, isOverdue } from '../utils';

// ── Column config ────────────────────────────────────────────────────────────
const COLUMNS = [
  { id: 'focus',      title: "Today's Focus", color: 'text-primary',    bg: 'bg-primary/10',  border: 'border-l-primary'  },
  { id: 'inprogress', title: 'In Progress',   color: 'text-blue-600',   bg: 'bg-blue-50 dark:bg-blue-900/20',   border: 'border-l-blue-400'   },
  { id: 'followups',  title: 'Follow-ups',    color: 'text-amber-600',  bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-l-amber-400'  },
  { id: 'open',       title: 'Open',          color: 'text-gray-500',   bg: 'bg-gray-100 dark:bg-gray-800',     border: 'border-l-gray-300'   },
];

const PRIORITY_BORDER = { Urgent:'border-l-red-500', High:'border-l-amber-400', Medium:'border-l-blue-400', Low:'border-l-green-400' };

function getColumnId(task) {
  if (task.status === 'Done') return null;
  if (task.is_today_focus)    return 'focus';
  if (task.status === 'In Progress') return 'inprogress';
  if (task.is_follow_up)      return 'followups';
  return 'open';
}

function columnUpdates(col, task) {
  const base = { ...task };
  if (col === 'focus')      return { ...base, is_today_focus: 1 };
  if (col === 'inprogress') return { ...base, status: 'In Progress', is_today_focus: 0 };
  if (col === 'followups')  return { ...base, is_follow_up: 1,  is_today_focus: 0 };
  if (col === 'open')       return { ...base, is_today_focus: 0, status: 'Open' };
  return base;
}

// ── Draggable card ───────────────────────────────────────────────────────────
function DraggableCard({ task, onEdit, onDelete, onMarkDone }) {
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: task.id });
  const overdue = isOverdue(task.due_date);

  return (

          {/* Drag handle */}


60	          {/* Drag handle */}
61	          <button {...listeners} {...attributes}
62	            className="shrink-0 mt-0.5 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing touch-none">
63	            <GripVertical size={14} />
64	          </button>
65
66

67

68
{task.title}

69	              <button onClick={() => onEdit(task)}
70	                className="shrink-0 opacity-0 group-hover:opacity-100 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-400 transition-all">
71	                <MoreHorizontal size={13} />
72	              </button>
73

74
75	            {task.notes &&
{task.notes}
}
76
77

78	              <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
79	                {CATEGORIES[task.category]?.label?.split(' ')[0] || task.category}
80
81	              <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
82	              {task.is_follow_up === 1 && Follow-up}
83

84
85

86

87	                {task.assignee ? (
88

89	                    {task.assignee[0].toUpperCase()}
90

91	                ) :
<User size={9} className="text-gray-400" />
}
92	                {task.assignee && {task.assignee}}
93

94

95	                {task.due_date && (
96	                  <span className={`flex items-center gap-0.5 text-[10px] ${overdue ? 'text-red-500 font-semibold' : 'text-gray-400'}`}>
97	                    {overdue && <AlertTriangle size={9} />}{formatDate(task.due_date)}
98
99	                )}
100	                <button onClick={() => onMarkDone(task)}
101	                  className="opacity-0 group-hover:opacity-100 text-[10px] px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 rounded-full hover:bg-green-200 transition-all font-medium">
102	                  Done
103	                </button>
104

105

106

107

108

109

110	  );
111	}
112
113	// ── Drag overlay card (ghost while dragging) ─────────────────────────────────
114	function OverlayCard({ task }) {
115	  return (
116

118
{task.title}

119

120	        <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
121	        <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
122	          {CATEGORIES[task.category]?.label?.split(' ')[0]}
123
124

125

126	  );
127	}
128
129	// ── Droppable column ─────────────────────────────────────────────────────────
130	function DroppableColumn({ col, tasks, stats, onAddTask, onEdit, onDelete, onMarkDone }) {
131	  const { setNodeRef, isOver } = useDroppable({ id: col.id });
132
133	  return (
134

138	      {/* Column header */}
139

140

141
{col.title}

142	          <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${col.bg} ${col.color}`}>{tasks.length}
143

144	        <button onClick={onAddTask}
145	          className="w-6 h-6 rounded-lg bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-all shadow-sm">
146	          <Plus size={12} />
147	        </button>
148

149
150	      {/* Cards */}
151

152	        {tasks.length === 0 ? (
153

155
Drop here

156

157	        ) : (
158	          tasks.map(task => (
159	            <DraggableCard key={task.id} task={task} onEdit={onEdit} onDelete={onDelete} onMarkDone={onMarkDone} />

{/* Drag handle */}
          <button {...listeners} {...attributes}
            className="shrink-0 mt-0.5 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing touch-none">
            <GripVertical size={14} />
          </button>

{task.title}

              <button onClick={() => onEdit(task)}
                className="shrink-0 opacity-0 group-hover:opacity-100 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-400 transition-all">
                <MoreHorizontal size={13} />
              </button>

            {task.notes &&
{task.notes}
}

              <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                {CATEGORIES[task.category]?.label?.split(' ')[0] || task.category}

              <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
              {task.is_follow_up === 1 && Follow-up}

                {task.assignee ? (

                    {task.assignee[0].toUpperCase()}

                ) :
<User size={9} className="text-gray-400" />
}
                {task.assignee && {task.assignee}}

                {task.due_date && (
                  <span className={`flex items-center gap-0.5 text-[10px] ${overdue ? 'text-red-500 font-semibold' : 'text-gray-400'}`}>
                    {overdue && <AlertTriangle size={9} />}{formatDate(task.due_date)}

                )}
                <button onClick={() => onMarkDone(task)}
                  className="opacity-0 group-hover:opacity-100 text-[10px] px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 rounded-full hover:bg-green-200 transition-all font-medium">
                  Done
                </button>

  );
}

// ── Drag overlay card (ghost while dragging) ─────────────────────────────────
function OverlayCard({ task }) {
  return (

{task.title}

        <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
        <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
          {CATEGORIES[task.category]?.label?.split(' ')[0]}

  );
}

// ── Droppable column ─────────────────────────────────────────────────────────
function DroppableColumn({ col, tasks, stats, onAddTask, onEdit, onDelete, onMarkDone }) {
  const { setNodeRef, isOver } = useDroppable({ id: col.id });

  return (

      {/* Column header */}

{col.title}

          <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${col.bg} ${col.color}`}>{tasks.length}

        <button onClick={onAddTask}
          className="w-6 h-6 rounded-lg bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-all shadow-sm">
          <Plus size={12} />
        </button>

      {/* Cards */}

        {tasks.length === 0 ? (

Drop here

        ) : (
          tasks.map(task => (
            <DraggableCard key={task.id} task={task} onEdit={onEdit} onDelete={onDelete} onMarkDone={onMarkDone} />


160	          ))
161	        )}
162

163

164	  );
165	}
166
167	// ── Main Dashboard ───────────────────────────────────────────────────────────
168	export default function Today() {
169	  const [allTasks, setAllTasks]     = useState([]);
170	  const [stats, setStats]           = useState(null);
171	  const [projects, setProjects]     = useState([]);
172	  const [loading, setLoading]       = useState(true);
173	  const [editTask, setEditTask]     = useState(null);
174	  const [deleteTask, setDeleteTask] = useState(null);
175	  const [showNew, setShowNew]       = useState(false);
176	  const [newDefaults, setNewDefaults] = useState({});
177	  const [activeTask, setActiveTask] = useState(null);
178	  const [activeTab, setActiveTab]   = useState('dashboard');
179	  const navigate = useNavigate();
180
181	  const today = new Date();
182	  const dateLabel = today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
183
184	  const load = useCallback(async () => {
185	    try {
186	      const [tasks, st, pr] = await Promise.all([api.get('/tasks'), api.get('/tasks/stats'), api.get('/projects')]);
187	      setAllTasks(tasks); setStats(st); setProjects(pr);
188	    } finally { setLoading(false); }
189	  }, []);
190
191	  useEffect(() => { load(); }, [load]);
192
193	  // Bucket tasks into columns
194	  const columns = COLUMNS.map(col => ({
195	    ...col,
196	    tasks: allTasks.filter(t => getColumnId(t) === col.id),
197	  }));
198
199	  // DnD sensors — support mouse, touch (mobile), delay to prevent accidental drags
200	  const sensors = useSensors(
201	    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
202	    useSensor(TouchSensor,   { activationConstraint: { delay: 180, tolerance: 6 } })
203	  );
204
205	  const onDragStart = ({ active }) => {
206	    setActiveTask(allTasks.find(t => t.id === active.id) || null);
207	  };
208
209	  const onDragEnd = async ({ active, over }) => {
210	    setActiveTask(null);
211	    if (!over) return;
212	    const task = allTasks.find(t => t.id === active.id);
213	    if (!task) return;
214	    const targetCol = COLUMNS.find(c => c.id === over.id);
215	    if (!targetCol || getColumnId(task) === targetCol.id) return;
216
217	    // Optimistic update
218	    const updated = columnUpdates(targetCol.id, task);
219	    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, ...updated } : t));
220	    try {
221	      await api.put(`/tasks/${task.id}`, updated);
222	      toast.success(`Moved to "${targetCol.title}"`);
223	    } catch (e) {
224	      toast.error('Failed to move task'); load();
225	    }
226	  };
227
228	  const markDone = async (task) => {
229	    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'Done' } : t));
230	    await api.patch(`/tasks/${task.id}/status`, { status: 'Done' });
231	    toast.success('Marked as done');
232	  };
233
234	  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); };
235
236	  const handleSave = async (form) => {
237	    try {
238	      if (editTask?.id) { await api.put(`/tasks/${editTask.id}`, form); toast.success('Task updated'); }
239	      else { await api.post('/tasks', { ...form, ...newDefaults }); toast.success('Task added'); }
240	      setEditTask(null); setShowNew(false); load();
241	    } catch (e) { toast.error(e.message); }
242	  };
243
244	  const handleDelete = async () => {
245	    await api.delete(`/tasks/${deleteTask.id}`);
246	    toast.success('Deleted'); setDeleteTask(null); load();
247	  };
248
249	  const TABS = [
250	    { id: 'dashboard', label: 'Dashboard' },
251	    { id: 'all',       label: 'All Tasks'      },
252	    { id: 'projects',  label: 'Projects'       },
253	  ];
254
255	  return (
256

257
258	      {/* Hero banner */}
259

260

261

262

263

264

265

266	              <Zap size={17} className="text-violet-600" />
267

268

269
DEWA AI Workspace

270
{dateLabel}

271

272

273

274	            {[
275	              { label: 'Projects',     value: stats?.activeProjects ?? '—', Icon: FolderKanban },
276	              { label: 'Open Tasks',   value: stats?.openTasks      ?? '—', Icon: CheckSquare  },
277	              { label: 'Follow-ups',   value: stats?.openFollowUps  ?? '—', Icon: Bell         },
278	              { label: "Today's Focus",value: stats?.todayFocus     ?? '—', Icon: Target       },
279	            ].map(({ label, value, Icon }) => (

))
        )}

  );
}

// ── Main Dashboard ───────────────────────────────────────────────────────────
export default function Today() {
  const [allTasks, setAllTasks]     = useState([]);
  const [stats, setStats]           = useState(null);
  const [projects, setProjects]     = useState([]);
  const [loading, setLoading]       = useState(true);
  const [editTask, setEditTask]     = useState(null);
  const [deleteTask, setDeleteTask] = useState(null);
  const [showNew, setShowNew]       = useState(false);
  const [newDefaults, setNewDefaults] = useState({});
  const [activeTask, setActiveTask] = useState(null);
  const [activeTab, setActiveTab]   = useState('dashboard');
  const navigate = useNavigate();

  const today = new Date();
  const dateLabel = today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  const load = useCallback(async () => {
    try {
      const [tasks, st, pr] = await Promise.all([api.get('/tasks'), api.get('/tasks/stats'), api.get('/projects')]);
      setAllTasks(tasks); setStats(st); setProjects(pr);
    } finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  // Bucket tasks into columns
  const columns = COLUMNS.map(col => ({
    ...col,
    tasks: allTasks.filter(t => getColumnId(t) === col.id),
  }));

  // DnD sensors — support mouse, touch (mobile), delay to prevent accidental drags
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(TouchSensor,   { activationConstraint: { delay: 180, tolerance: 6 } })
  );

  const onDragStart = ({ active }) => {
    setActiveTask(allTasks.find(t => t.id === active.id) || null);
  };

  const onDragEnd = async ({ active, over }) => {
    setActiveTask(null);
    if (!over) return;
    const task = allTasks.find(t => t.id === active.id);
    if (!task) return;
    const targetCol = COLUMNS.find(c => c.id === over.id);
    if (!targetCol || getColumnId(task) === targetCol.id) return;

    // Optimistic update
    const updated = columnUpdates(targetCol.id, task);
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, ...updated } : t));
    try {
      await api.put(`/tasks/${task.id}`, updated);
      toast.success(`Moved to "${targetCol.title}"`);
    } catch (e) {
      toast.error('Failed to move task'); load();
    }
  };

  const markDone = async (task) => {
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'Done' } : t));
    await api.patch(`/tasks/${task.id}/status`, { status: 'Done' });
    toast.success('Marked as done');
  };

  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); };

  const handleSave = async (form) => {
    try {
      if (editTask?.id) { await api.put(`/tasks/${editTask.id}`, form); toast.success('Task updated'); }
      else { await api.post('/tasks', { ...form, ...newDefaults }); toast.success('Task added'); }
      setEditTask(null); setShowNew(false); load();
    } catch (e) { toast.error(e.message); }
  };

  const handleDelete = async () => {
    await api.delete(`/tasks/${deleteTask.id}`);
    toast.success('Deleted'); setDeleteTask(null); load();
  };

  const TABS = [
    { id: 'dashboard', label: 'Dashboard' },
    { id: 'all',       label: 'All Tasks'      },
    { id: 'projects',  label: 'Projects'       },
  ];

  return (

      {/* Hero banner */}

              <Zap size={17} className="text-violet-600" />

DEWA AI Workspace

{dateLabel}

            {[
              { label: 'Projects',     value: stats?.activeProjects ?? '—', Icon: FolderKanban },
              { label: 'Open Tasks',   value: stats?.openTasks      ?? '—', Icon: CheckSquare  },
              { label: 'Follow-ups',   value: stats?.openFollowUps  ?? '—', Icon: Bell         },
              { label: "Today's Focus",value: stats?.todayFocus     ?? '—', Icon: Target       },
            ].map(({ label, value, Icon }) => (


280

281
{value}

282

283	                  <Icon size={9} />{label}
284

285

286	            ))}
287

288

289

290
291	      {/* Tabs */}
292

293	        {TABS.map(t => (
294	          <button key={t.id} onClick={() => setActiveTab(t.id)}
295	            className={`px-3.5 py-1.5 rounded-xl text-sm font-medium transition-all duration-150 ${
296	              activeTab === t.id
297	                ? 'bg-primary text-white shadow-sm'
298	                : 'text-gray-500 dark:text-gray-400 hover:bg-white dark:hover:bg-gray-800 hover:text-gray-800 dark:hover:text-white'
299	            }`}>
300	            {t.label}
301	          </button>
302	        ))}
303

304	        <button onClick={() => openNew({ is_today_focus: 1 })} className="btn-primary flex items-center gap-1 py-1.5 text-xs">
305	          <Plus size={12} /> New Task
306	        </button>
307

308
309	      {/* ── Kanban Board (drag & drop) ─────────────────────────────────── */}
310	      {loading ? (
311

312	          {[1,2,3,4].map(i =>
)}
313

314	      ) : (
315	        <>
316	          {activeTab === 'dashboard' && (
317	            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragEnd={onDragEnd}>
318	              {/* Horizontal scrollable kanban — snaps on mobile */}
319

321	                {columns.map(col => (
322	                  <DroppableColumn
323	                    key={col.id} col={col} tasks={col.tasks}
324	                    onAddTask={() => openNew(
325	                      col.id === 'focus'      ? { is_today_focus: 1 } :
326	                      col.id === 'inprogress' ? { status: 'In Progress' } :
327	                      col.id === 'followups'  ? { is_follow_up: 1 } : {}
328	                    )}
329	                    onEdit={setEditTask}
330	                    onDelete={setDeleteTask}
331	                    onMarkDone={markDone}
332	                  />
333	                ))}
334

335	              {/* Drag overlay */}
336	              <DragOverlay dropAnimation={{ duration: 180, easing: 'cubic-bezier(0.18,0.67,0.6,1.22)' }}>
337	                {activeTask && <OverlayCard task={activeTask} />}
338	              </DragOverlay>
339	            </DndContext>
340	          )}
341
342	          {/* ALL TASKS — horizontal grid */}
343	          {activeTab === 'all' && (
344

345

346	                {allTasks.filter(t => t.status !== 'Done').map(task => (
347
 setEditTask(task)}>
351
{task.title}

352

353	                      <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
354	                      <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
355	                        {CATEGORIES[task.category]?.label?.split(' ')[0]}
356
357

358	                    {task.assignee && (
359

360

361	                          {task.assignee[0].toUpperCase()}
362

363	                        {task.assignee}
364

365	                    )}
366

367	                ))}
368

369

370	          )}
371
372	          {/* PROJECTS — horizontal grid */}
373	          {activeTab === 'projects' && (
374

375

376	                {projects.filter(p => p.status !== 'Done').map(p => (
377	                  <button key={p.id} onClick={() => navigate(`/projects/${p.id}`)}
378	                    className="card-hover text-left p-4 group">
379

{value}

                  <Icon size={9} />{label}

            ))}

      {/* Tabs */}

        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            className={`px-3.5 py-1.5 rounded-xl text-sm font-medium transition-all duration-150 ${
              activeTab === t.id
                ? 'bg-primary text-white shadow-sm'
                : 'text-gray-500 dark:text-gray-400 hover:bg-white dark:hover:bg-gray-800 hover:text-gray-800 dark:hover:text-white'
            }`}>
            {t.label}
          </button>
        ))}

        <button onClick={() => openNew({ is_today_focus: 1 })} className="btn-primary flex items-center gap-1 py-1.5 text-xs">
          <Plus size={12} /> New Task
        </button>

      {/* ── Kanban Board (drag & drop) ─────────────────────────────────── */}
      {loading ? (

          {[1,2,3,4].map(i =>
)}

      ) : (
        <>
          {activeTab === 'dashboard' && (
            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragEnd={onDragEnd}>
              {/* Horizontal scrollable kanban — snaps on mobile */}

                {columns.map(col => (
                  <DroppableColumn
                    key={col.id} col={col} tasks={col.tasks}
                    onAddTask={() => openNew(
                      col.id === 'focus'      ? { is_today_focus: 1 } :
                      col.id === 'inprogress' ? { status: 'In Progress' } :
                      col.id === 'followups'  ? { is_follow_up: 1 } : {}
                    )}
                    onEdit={setEditTask}
                    onDelete={setDeleteTask}
                    onMarkDone={markDone}
                  />
                ))}

              {/* Drag overlay */}
              <DragOverlay dropAnimation={{ duration: 180, easing: 'cubic-bezier(0.18,0.67,0.6,1.22)' }}>
                {activeTask && <OverlayCard task={activeTask} />}
              </DragOverlay>
            </DndContext>
          )}

          {/* ALL TASKS — horizontal grid */}
          {activeTab === 'all' && (

                {allTasks.filter(t => t.status !== 'Done').map(task => (

 setEditTask(task)}>

{task.title}

                      <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
                      <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                        {CATEGORIES[task.category]?.label?.split(' ')[0]}

                    {task.assignee && (

                          {task.assignee[0].toUpperCase()}

                        {task.assignee}

                    )}

                ))}

          )}

          {/* PROJECTS — horizontal grid */}
          {activeTab === 'projects' && (

                {projects.filter(p => p.status !== 'Done').map(p => (
                  <button key={p.id} onClick={() => navigate(`/projects/${p.id}`)}
                    className="card-hover text-left p-4 group">


380	                      <span className={`badge text-[10px] ${getCategoryClass(p.category)}`}>
381	                        {CATEGORIES[p.category]?.label?.split(' ')[0] || p.category}
382
383	                      <ArrowRight size={12} className="text-gray-300 group-hover:text-primary transition-colors" />
384

385
{p.name}

386

387	                      <span className={`font-semibold ${p.priority === 'Urgent' ? 'text-red-500' : p.priority === 'High' ? 'text-amber-500' : ''}`}>{p.priority}
388	                      {p.open_task_count || 0} tasks
389

390	                  </button>
391	                ))}
392

393

394	          )}
395	        </>
396	      )}
397
398	      {/* Modals */}
399	      {(showNew || editTask) && (
400	        <TaskModal task={editTask} projects={projects} onSave={handleSave} onClose={() => { setShowNew(false); setEditTask(null); }} />
401	      )}
402	      {deleteTask && (
403	        <ConfirmDialog title="Delete task?" message={`"${deleteTask.title}"`} onConfirm={handleDelete} onCancel={() => setDeleteTask(null)} />
404	      )}
405

406	  );
407	}
408

<span className={`badge text-[10px] ${getCategoryClass(p.category)}`}>
                        {CATEGORIES[p.category]?.label?.split(' ')[0] || p.category}

                      <ArrowRight size={12} className="text-gray-300 group-hover:text-primary transition-colors" />

{p.name}

                      <span className={`font-semibold ${p.priority === 'Urgent' ? 'text-red-500' : p.priority === 'High' ? 'text-amber-500' : ''}`}>{p.priority}
                      {p.open_task_count || 0} tasks

                  </button>
                ))}

          )}
        </>
      )}

      {/* Modals */}
      {(showNew || editTask) && (
        <TaskModal task={editTask} projects={projects} onSave={handleSave} onClose={() => { setShowNew(false); setEditTask(null); }} />
      )}
      {deleteTask && (
        <ConfirmDialog title="Delete task?" message={`"${deleteTask.title}"`} onConfirm={handleDelete} onCancel={() => setDeleteTask(null)} />
      )}

  );
}


Now I have everything I need. I'll add a Quick Capture bar between the hero and tabs in Today.jsx:


Edit

import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical
} from 'lucide-react';

import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical, PenLine, Send
} from 'lucide-react';


The file /Users/khalidbinkalban/my-workspace/client/src/components/Today.jsx has been updated successfully.

import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical, PenLine, Send
} from 'lucide-react';

import { useState, useEffect, useCallback } from 'react';
import {
  DndContext, DragOverlay, useDroppable, useDraggable,
  PointerSensor, TouchSensor, useSensor, useSensors, closestCenter
} from '@dnd-kit/core';
import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical
} from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import api from '../api';
import TaskModal from './TaskModal';
import ConfirmDialog from './ConfirmDialog';
import { getCategoryClass, getPriorityClass, CATEGORIES, formatDate, isOverdue } from '../utils';

// ── Column config ────────────────────────────────────────────────────────────
const COLUMNS = [
  { id: 'focus',      title: "Today's Focus", color: 'text-primary',    bg: 'bg-primary/10',  border: 'border-l-primary'  },
  { id: 'inprogress', title: 'In Progress',   color: 'text-blue-600',   bg: 'bg-blue-50 dark:bg-blue-900/20',   border: 'border-l-blue-400'   },
  { id: 'followups',  title: 'Follow-ups',    color: 'text-amber-600',  bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-l-amber-400'  },
  { id: 'open',       title: 'Open',          color: 'text-gray-500',   bg: 'bg-gray-100 dark:bg-gray-800',     border: 'border-l-gray-300'   },
];

const PRIORITY_BORDER = { Urgent:'border-l-red-500', High:'border-l-amber-400', Medium:'border-l-blue-400', Low:'border-l-green-400' };

function getColumnId(task) {
  if (task.status === 'Done') return null;
  if (task.is_today_focus)    return 'focus';
  if (task.status === 'In Progress') return 'inprogress';
  if (task.is_follow_up)      return 'followups';
  return 'open';
}

function columnUpdates(col, task) {
  const base = { ...task };
  if (col === 'focus')      return { ...base, is_today_focus: 1 };
  if (col === 'inprogress') return { ...base, status: 'In Progress', is_today_focus: 0 };
  if (col === 'followups')  return { ...base, is_follow_up: 1,  is_today_focus: 0 };
  if (col === 'open')       return { ...base, is_today_focus: 0, status: 'Open' };
  return base;
}

// ── Draggable card ───────────────────────────────────────────────────────────
function DraggableCard({ task, onEdit, onDelete, onMarkDone }) {
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: task.id });
  const overdue = isOverdue(task.due_date);

  return (

          {/* Drag handle */}
          <button {...listeners} {...attributes}
            className="shrink-0 mt-0.5 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing touch-none">
            <GripVertical size={14} />
          </button>

{task.title}

              <button onClick={() => onEdit(task)}
                className="shrink-0 opacity-0 group-hover:opacity-100 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-400 transition-all">
                <MoreHorizontal size={13} />
              </button>

            {task.notes &&
{task.notes}
}

              <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                {CATEGORIES[task.category]?.label?.split(' ')[0] || task.category}

              <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
              {task.is_follow_up === 1 && Follow-up}

                {task.assignee ? (

                    {task.assignee[0].toUpperCase()}

                ) :
<User size={9} className="text-gray-400" />
}
                {task.assignee && {task.assignee}}

                {task.due_date && (
                  <span className={`flex items-center gap-0.5 text-[10px] ${overdue ? 'text-red-500 font-semibold' : 'text-gray-400'}`}>
                    {overdue && <AlertTriangle size={9} />}{formatDate(task.due_date)}

                )}
                <button onClick={() => onMarkDone(task)}
                  className="opacity-0 group-hover:opacity-100 text-[10px] px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 rounded-full hover:bg-green-200 transition-all font-medium">
                  Done
                </button>

  );
}

// ── Drag overlay card (ghost while dragging) ─────────────────────────────────
function OverlayCard({ task }) {
  return (

{task.title}

        <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
        <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
          {CATEGORIES[task.category]?.label?.split(' ')[0]}

  );
}

// ── Droppable column ─────────────────────────────────────────────────────────
function DroppableColumn({ col, tasks, stats, onAddTask, onEdit, onDelete, onMarkDone }) {
  const { setNodeRef, isOver } = useDroppable({ id: col.id });

  return (

      {/* Column header */}

{col.title}

          <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${col.bg} ${col.color}`}>{tasks.length}

        <button onClick={onAddTask}
          className="w-6 h-6 rounded-lg bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-all shadow-sm">
          <Plus size={12} />
        </button>

      {/* Cards */}

        {tasks.length === 0 ? (

Drop here

        ) : (
          tasks.map(task => (
            <DraggableCard key={task.id} task={task} onEdit={onEdit} onDelete={onDelete} onMarkDone={onMarkDone} />
          ))
        )}

  );
}

// ── Main Dashboard ───────────────────────────────────────────────────────────
export default function Today() {
  const [allTasks, setAllTasks]     = useState([]);
  const [stats, setStats]           = useState(null);
  const [projects, setProjects]     = useState([]);
  const [loading, setLoading]       = useState(true);
  const [editTask, setEditTask]     = useState(null);
  const [deleteTask, setDeleteTask] = useState(null);
  const [showNew, setShowNew]       = useState(false);
  const [newDefaults, setNewDefaults] = useState({});
  const [activeTask, setActiveTask] = useState(null);
  const [activeTab, setActiveTab]   = useState('dashboard');
  const navigate = useNavigate();

  const today = new Date();
  const dateLabel = today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  const load = useCallback(async () => {
    try {
      const [tasks, st, pr] = await Promise.all([api.get('/tasks'), api.get('/tasks/stats'), api.get('/projects')]);
      setAllTasks(tasks); setStats(st); setProjects(pr);
    } finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  // Bucket tasks into columns
  const columns = COLUMNS.map(col => ({
    ...col,
    tasks: allTasks.filter(t => getColumnId(t) === col.id),
  }));

  // DnD sensors — support mouse, touch (mobile), delay to prevent accidental drags
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(TouchSensor,   { activationConstraint: { delay: 180, tolerance: 6 } })
  );

  const onDragStart = ({ active }) => {
    setActiveTask(allTasks.find(t => t.id === active.id) || null);
  };

  const onDragEnd = async ({ active, over }) => {
    setActiveTask(null);
    if (!over) return;
    const task = allTasks.find(t => t.id === active.id);
    if (!task) return;
    const targetCol = COLUMNS.find(c => c.id === over.id);
    if (!targetCol || getColumnId(task) === targetCol.id) return;

    // Optimistic update
    const updated = columnUpdates(targetCol.id, task);
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, ...updated } : t));
    try {
      await api.put(`/tasks/${task.id}`, updated);
      toast.success(`Moved to "${targetCol.title}"`);
    } catch (e) {
      toast.error('Failed to move task'); load();
    }
  };

  const markDone = async (task) => {
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'Done' } : t));
    await api.patch(`/tasks/${task.id}/status`, { status: 'Done' });
    toast.success('Marked as done');
  };

  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); };

  const handleSave = async (form) => {
    try {
      if (editTask?.id) { await api.put(`/tasks/${editTask.id}`, form); toast.success('Task updated'); }
      else { await api.post('/tasks', { ...form, ...newDefaults }); toast.success('Task added'); }
      setEditTask(null); setShowNew(false); load();
    } catch (e) { toast.error(e.message); }
  };

  const handleDelete = async () => {
    await api.delete(`/tasks/${deleteTask.id}`);
    toast.success('Deleted'); setDeleteTask(null); load();
  };

  const TABS = [
    { id: 'dashboard', label: 'Dashboard' },
    { id: 'all',       label: 'All Tasks'      },
    { id: 'projects',  label: 'Projects'       },
  ];

  return (

      {/* Hero banner */}

              <Zap size={17} className="text-violet-600" />

DEWA AI Workspace

{dateLabel}

            {[
              { label: 'Projects',     value: stats?.activeProjects ?? '—', Icon: FolderKanban },
              { label: 'Open Tasks',   value: stats?.openTasks      ?? '—', Icon: CheckSquare  },
              { label: 'Follow-ups',   value: stats?.openFollowUps  ?? '—', Icon: Bell         },
              { label: "Today's Focus",value: stats?.todayFocus     ?? '—', Icon: Target       },
            ].map(({ label, value, Icon }) => (

{value}

                  <Icon size={9} />{label}

            ))}

      {/* Tabs */}

        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            className={`px-3.5 py-1.5 rounded-xl text-sm font-medium transition-all duration-150 ${
              activeTab === t.id
                ? 'bg-primary text-white shadow-sm'
                : 'text-gray-500 dark:text-gray-400 hover:bg-white dark:hover:bg-gray-800 hover:text-gray-800 dark:hover:text-white'
            }`}>
            {t.label}
          </button>
        ))}

        <button onClick={() => openNew({ is_today_focus: 1 })} className="btn-primary flex items-center gap-1 py-1.5 text-xs">
          <Plus size={12} /> New Task
        </button>

      {/* ── Kanban Board (drag & drop) ─────────────────────────────────── */}
      {loading ? (

          {[1,2,3,4].map(i =>
)}

      ) : (
        <>
          {activeTab === 'dashboard' && (
            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragEnd={onDragEnd}>
              {/* Horizontal scrollable kanban — snaps on mobile */}

                {columns.map(col => (
                  <DroppableColumn
                    key={col.id} col={col} tasks={col.tasks}
                    onAddTask={() => openNew(
                      col.id === 'focus'      ? { is_today_focus: 1 } :
                      col.id === 'inprogress' ? { status: 'In Progress' } :
                      col.id === 'followups'  ? { is_follow_up: 1 } : {}
                    )}
                    onEdit={setEditTask}
                    onDelete={setDeleteTask}
                    onMarkDone={markDone}
                  />
                ))}

              {/* Drag overlay */}
              <DragOverlay dropAnimation={{ duration: 180, easing: 'cubic-bezier(0.18,0.67,0.6,1.22)' }}>
                {activeTask && <OverlayCard task={activeTask} />}
              </DragOverlay>
            </DndContext>
          )}

          {/* ALL TASKS — horizontal grid */}
          {activeTab === 'all' && (

                {allTasks.filter(t => t.status !== 'Done').map(task => (

 setEditTask(task)}>

{task.title}

                      <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
                      <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                        {CATEGORIES[task.category]?.label?.split(' ')[0]}

                    {task.assignee && (

                          {task.assignee[0].toUpperCase()}

                        {task.assignee}

                    )}

                ))}

          )}

          {/* PROJECTS — horizontal grid */}
          {activeTab === 'projects' && (

                {projects.filter(p => p.status !== 'Done').map(p => (
                  <button key={p.id} onClick={() => navigate(`/projects/${p.id}`)}
                    className="card-hover text-left p-4 group">

                      <span className={`badge text-[10px] ${getCategoryClass(p.category)}`}>
                        {CATEGORIES[p.category]?.label?.split(' ')[0] || p.category}

                      <ArrowRight size={12} className="text-gray-300 group-hover:text-primary transition-colors" />

{p.name}

                      <span className={`font-semibold ${p.priority === 'Urgent' ? 'text-red-500' : p.priority === 'High' ? 'text-amber-500' : ''}`}>{p.priority}
                      {p.open_task_count || 0} tasks

                  </button>
                ))}

          )}
        </>
      )}

      {/* Modals */}
      {(showNew || editTask) && (
        <TaskModal task={editTask} projects={projects} onSave={handleSave} onClose={() => { setShowNew(false); setEditTask(null); }} />
      )}
      {deleteTask && (
        <ConfirmDialog title="Delete task?" message={`"${deleteTask.title}"`} onConfirm={handleDelete} onCancel={() => setDeleteTask(null)} />
      )}

  );
}

-  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical

+  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical, PenLine, Send


  const [activeTab, setActiveTab]   = useState('dashboard');
  const navigate = useNavigate();

  const [activeTab, setActiveTab]   = useState('dashboard');
  const [quickInput, setQuickInput] = useState('');
  const navigate = useNavigate();


  const [activeTab, setActiveTab]   = useState('dashboard');
  const [quickInput, setQuickInput] = useState('');
  const navigate = useNavigate();

import { useState, useEffect, useCallback } from 'react';
import {
  DndContext, DragOverlay, useDroppable, useDraggable,
  PointerSensor, TouchSensor, useSensor, useSensors, closestCenter
} from '@dnd-kit/core';
import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical, PenLine, Send
} from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import api from '../api';
import TaskModal from './TaskModal';
import ConfirmDialog from './ConfirmDialog';
import { getCategoryClass, getPriorityClass, CATEGORIES, formatDate, isOverdue } from '../utils';

// ── Column config ────────────────────────────────────────────────────────────
const COLUMNS = [
  { id: 'focus',      title: "Today's Focus", color: 'text-primary',    bg: 'bg-primary/10',  border: 'border-l-primary'  },
  { id: 'inprogress', title: 'In Progress',   color: 'text-blue-600',   bg: 'bg-blue-50 dark:bg-blue-900/20',   border: 'border-l-blue-400'   },
  { id: 'followups',  title: 'Follow-ups',    color: 'text-amber-600',  bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-l-amber-400'  },
  { id: 'open',       title: 'Open',          color: 'text-gray-500',   bg: 'bg-gray-100 dark:bg-gray-800',     border: 'border-l-gray-300'   },
];

const PRIORITY_BORDER = { Urgent:'border-l-red-500', High:'border-l-amber-400', Medium:'border-l-blue-400', Low:'border-l-green-400' };

function getColumnId(task) {
  if (task.status === 'Done') return null;
  if (task.is_today_focus)    return 'focus';
  if (task.status === 'In Progress') return 'inprogress';
  if (task.is_follow_up)      return 'followups';
  return 'open';
}

function columnUpdates(col, task) {
  const base = { ...task };
  if (col === 'focus')      return { ...base, is_today_focus: 1 };
  if (col === 'inprogress') return { ...base, status: 'In Progress', is_today_focus: 0 };
  if (col === 'followups')  return { ...base, is_follow_up: 1,  is_today_focus: 0 };
  if (col === 'open')       return { ...base, is_today_focus: 0, status: 'Open' };
  return base;
}

// ── Draggable card ───────────────────────────────────────────────────────────
function DraggableCard({ task, onEdit, onDelete, onMarkDone }) {
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: task.id });
  const overdue = isOverdue(task.due_date);

  return (

          {/* Drag handle */}
          <button {...listeners} {...attributes}
            className="shrink-0 mt-0.5 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing touch-none">
            <GripVertical size={14} />
          </button>

{task.title}

              <button onClick={() => onEdit(task)}
                className="shrink-0 opacity-0 group-hover:opacity-100 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-400 transition-all">
                <MoreHorizontal size={13} />
              </button>

            {task.notes &&
{task.notes}
}

              <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                {CATEGORIES[task.category]?.label?.split(' ')[0] || task.category}

              <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
              {task.is_follow_up === 1 && Follow-up}

                {task.assignee ? (

                    {task.assignee[0].toUpperCase()}

                ) :
<User size={9} className="text-gray-400" />
}
                {task.assignee && {task.assignee}}

                {task.due_date && (
                  <span className={`flex items-center gap-0.5 text-[10px] ${overdue ? 'text-red-500 font-semibold' : 'text-gray-400'}`}>
                    {overdue && <AlertTriangle size={9} />}{formatDate(task.due_date)}

                )}
                <button onClick={() => onMarkDone(task)}
                  className="opacity-0 group-hover:opacity-100 text-[10px] px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 rounded-full hover:bg-green-200 transition-all font-medium">
                  Done
                </button>

  );
}

// ── Drag overlay card (ghost while dragging) ─────────────────────────────────
function OverlayCard({ task }) {
  return (

{task.title}

        <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
        <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
          {CATEGORIES[task.category]?.label?.split(' ')[0]}

  );
}

// ── Droppable column ─────────────────────────────────────────────────────────
function DroppableColumn({ col, tasks, stats, onAddTask, onEdit, onDelete, onMarkDone }) {
  const { setNodeRef, isOver } = useDroppable({ id: col.id });

  return (

      {/* Column header */}

{col.title}

          <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${col.bg} ${col.color}`}>{tasks.length}

        <button onClick={onAddTask}
          className="w-6 h-6 rounded-lg bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-all shadow-sm">
          <Plus size={12} />
        </button>

      {/* Cards */}

        {tasks.length === 0 ? (

Drop here

        ) : (
          tasks.map(task => (
            <DraggableCard key={task.id} task={task} onEdit={onEdit} onDelete={onDelete} onMarkDone={onMarkDone} />
          ))
        )}

  );
}

// ── Main Dashboard ───────────────────────────────────────────────────────────
export default function Today() {
  const [allTasks, setAllTasks]     = useState([]);
  const [stats, setStats]           = useState(null);
  const [projects, setProjects]     = useState([]);
  const [loading, setLoading]       = useState(true);
  const [editTask, setEditTask]     = useState(null);
  const [deleteTask, setDeleteTask] = useState(null);
  const [showNew, setShowNew]       = useState(false);
  const [newDefaults, setNewDefaults] = useState({});
  const [activeTask, setActiveTask] = useState(null);
  const [activeTab, setActiveTab]   = useState('dashboard');
  const navigate = useNavigate();

  const today = new Date();
  const dateLabel = today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  const load = useCallback(async () => {
    try {
      const [tasks, st, pr] = await Promise.all([api.get('/tasks'), api.get('/tasks/stats'), api.get('/projects')]);
      setAllTasks(tasks); setStats(st); setProjects(pr);
    } finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  // Bucket tasks into columns
  const columns = COLUMNS.map(col => ({
    ...col,
    tasks: allTasks.filter(t => getColumnId(t) === col.id),
  }));

  // DnD sensors — support mouse, touch (mobile), delay to prevent accidental drags
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(TouchSensor,   { activationConstraint: { delay: 180, tolerance: 6 } })
  );

  const onDragStart = ({ active }) => {
    setActiveTask(allTasks.find(t => t.id === active.id) || null);
  };

  const onDragEnd = async ({ active, over }) => {
    setActiveTask(null);
    if (!over) return;
    const task = allTasks.find(t => t.id === active.id);
    if (!task) return;
    const targetCol = COLUMNS.find(c => c.id === over.id);
    if (!targetCol || getColumnId(task) === targetCol.id) return;

    // Optimistic update
    const updated = columnUpdates(targetCol.id, task);
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, ...updated } : t));
    try {
      await api.put(`/tasks/${task.id}`, updated);
      toast.success(`Moved to "${targetCol.title}"`);
    } catch (e) {
      toast.error('Failed to move task'); load();
    }
  };

  const markDone = async (task) => {
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'Done' } : t));
    await api.patch(`/tasks/${task.id}/status`, { status: 'Done' });
    toast.success('Marked as done');
  };

  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); };

  const handleSave = async (form) => {
    try {
      if (editTask?.id) { await api.put(`/tasks/${editTask.id}`, form); toast.success('Task updated'); }
      else { await api.post('/tasks', { ...form, ...newDefaults }); toast.success('Task added'); }
      setEditTask(null); setShowNew(false); load();
    } catch (e) { toast.error(e.message); }
  };

  const handleDelete = async () => {
    await api.delete(`/tasks/${deleteTask.id}`);
    toast.success('Deleted'); setDeleteTask(null); load();
  };

  const TABS = [
    { id: 'dashboard', label: 'Dashboard' },
    { id: 'all',       label: 'All Tasks'      },
    { id: 'projects',  label: 'Projects'       },
  ];

  return (

      {/* Hero banner */}

              <Zap size={17} className="text-violet-600" />

DEWA AI Workspace

{dateLabel}

            {[
              { label: 'Projects',     value: stats?.activeProjects ?? '—', Icon: FolderKanban },
              { label: 'Open Tasks',   value: stats?.openTasks      ?? '—', Icon: CheckSquare  },
              { label: 'Follow-ups',   value: stats?.openFollowUps  ?? '—', Icon: Bell         },
              { label: "Today's Focus",value: stats?.todayFocus     ?? '—', Icon: Target       },
            ].map(({ label, value, Icon }) => (

{value}

                  <Icon size={9} />{label}

            ))}

      {/* Tabs */}

        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            className={`px-3.5 py-1.5 rounded-xl text-sm font-medium transition-all duration-150 ${
              activeTab === t.id
                ? 'bg-primary text-white shadow-sm'
                : 'text-gray-500 dark:text-gray-400 hover:bg-white dark:hover:bg-gray-800 hover:text-gray-800 dark:hover:text-white'
            }`}>
            {t.label}
          </button>
        ))}

        <button onClick={() => openNew({ is_today_focus: 1 })} className="btn-primary flex items-center gap-1 py-1.5 text-xs">
          <Plus size={12} /> New Task
        </button>

      {/* ── Kanban Board (drag & drop) ─────────────────────────────────── */}
      {loading ? (

          {[1,2,3,4].map(i =>
)}

      ) : (
        <>
          {activeTab === 'dashboard' && (
            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragEnd={onDragEnd}>
              {/* Horizontal scrollable kanban — snaps on mobile */}

                {columns.map(col => (
                  <DroppableColumn
                    key={col.id} col={col} tasks={col.tasks}
                    onAddTask={() => openNew(
                      col.id === 'focus'      ? { is_today_focus: 1 } :
                      col.id === 'inprogress' ? { status: 'In Progress' } :
                      col.id === 'followups'  ? { is_follow_up: 1 } : {}
                    )}
                    onEdit={setEditTask}
                    onDelete={setDeleteTask}
                    onMarkDone={markDone}
                  />
                ))}

              {/* Drag overlay */}
              <DragOverlay dropAnimation={{ duration: 180, easing: 'cubic-bezier(0.18,0.67,0.6,1.22)' }}>
                {activeTask && <OverlayCard task={activeTask} />}
              </DragOverlay>
            </DndContext>
          )}

          {/* ALL TASKS — horizontal grid */}
          {activeTab === 'all' && (

                {allTasks.filter(t => t.status !== 'Done').map(task => (

 setEditTask(task)}>

{task.title}

                      <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
                      <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                        {CATEGORIES[task.category]?.label?.split(' ')[0]}

                    {task.assignee && (

                          {task.assignee[0].toUpperCase()}

                        {task.assignee}

                    )}

                ))}

          )}

          {/* PROJECTS — horizontal grid */}
          {activeTab === 'projects' && (

                {projects.filter(p => p.status !== 'Done').map(p => (
                  <button key={p.id} onClick={() => navigate(`/projects/${p.id}`)}
                    className="card-hover text-left p-4 group">

                      <span className={`badge text-[10px] ${getCategoryClass(p.category)}`}>
                        {CATEGORIES[p.category]?.label?.split(' ')[0] || p.category}

                      <ArrowRight size={12} className="text-gray-300 group-hover:text-primary transition-colors" />

{p.name}

                      <span className={`font-semibold ${p.priority === 'Urgent' ? 'text-red-500' : p.priority === 'High' ? 'text-amber-500' : ''}`}>{p.priority}
                      {p.open_task_count || 0} tasks

                  </button>
                ))}

          )}
        </>
      )}

      {/* Modals */}
      {(showNew || editTask) && (
        <TaskModal task={editTask} projects={projects} onSave={handleSave} onClose={() => { setShowNew(false); setEditTask(null); }} />
      )}
      {deleteTask && (
        <ConfirmDialog title="Delete task?" message={`"${deleteTask.title}"`} onConfirm={handleDelete} onCancel={() => setDeleteTask(null)} />
      )}

  );
}

+  const [quickInput, setQuickInput] = useState('');


Now add the `quickCapture` handler and the bar UI:


const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); }

  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); }

  const quickCapture = async (e) => {
    e.preventDefault();
    const title = quickInput.trim();
    if (!title) return;
    try {
      await api.post('/tasks', { title, priority: 'Medium', status: 'Open', category: 'adhoc', is_today_focus: 1 });
      setQuickInput('');
      toast.success('Task added to Today\'s Focus');
      load();
    } catch { toast.error('Failed to add task'); }
  };


  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); }

  const quickCapture = async (e) => {
    e.preventDefault();
    const title = quickInput.trim();
    if (!title) return;
    try {
      await api.post('/tasks', { title, priority: 'Medium', status: 'Open', category: 'adhoc', is_today_focus: 1 });
      setQuickInput('');
      toast.success('Task added to Today\'s Focus');
      load();
    } catch { toast.error('Failed to add task'); }
  };

import { useState, useEffect, useCallback } from 'react';
import {
  DndContext, DragOverlay, useDroppable, useDraggable,
  PointerSensor, TouchSensor, useSensor, useSensors, closestCenter
} from '@dnd-kit/core';
import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical, PenLine, Send
} from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import api from '../api';
import TaskModal from './TaskModal';
import ConfirmDialog from './ConfirmDialog';
import { getCategoryClass, getPriorityClass, CATEGORIES, formatDate, isOverdue } from '../utils';

// ── Column config ────────────────────────────────────────────────────────────
const COLUMNS = [
  { id: 'focus',      title: "Today's Focus", color: 'text-primary',    bg: 'bg-primary/10',  border: 'border-l-primary'  },
  { id: 'inprogress', title: 'In Progress',   color: 'text-blue-600',   bg: 'bg-blue-50 dark:bg-blue-900/20',   border: 'border-l-blue-400'   },
  { id: 'followups',  title: 'Follow-ups',    color: 'text-amber-600',  bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-l-amber-400'  },
  { id: 'open',       title: 'Open',          color: 'text-gray-500',   bg: 'bg-gray-100 dark:bg-gray-800',     border: 'border-l-gray-300'   },
];

const PRIORITY_BORDER = { Urgent:'border-l-red-500', High:'border-l-amber-400', Medium:'border-l-blue-400', Low:'border-l-green-400' };

function getColumnId(task) {
  if (task.status === 'Done') return null;
  if (task.is_today_focus)    return 'focus';
  if (task.status === 'In Progress') return 'inprogress';
  if (task.is_follow_up)      return 'followups';
  return 'open';
}

function columnUpdates(col, task) {
  const base = { ...task };
  if (col === 'focus')      return { ...base, is_today_focus: 1 };
  if (col === 'inprogress') return { ...base, status: 'In Progress', is_today_focus: 0 };
  if (col === 'followups')  return { ...base, is_follow_up: 1,  is_today_focus: 0 };
  if (col === 'open')       return { ...base, is_today_focus: 0, status: 'Open' };
  return base;
}

// ── Draggable card ───────────────────────────────────────────────────────────
function DraggableCard({ task, onEdit, onDelete, onMarkDone }) {
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: task.id });
  const overdue = isOverdue(task.due_date);

  return (

          {/* Drag handle */}
          <button {...listeners} {...attributes}
            className="shrink-0 mt-0.5 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing touch-none">
            <GripVertical size={14} />
          </button>

{task.title}

              <button onClick={() => onEdit(task)}
                className="shrink-0 opacity-0 group-hover:opacity-100 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-400 transition-all">
                <MoreHorizontal size={13} />
              </button>

            {task.notes &&
{task.notes}
}

              <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                {CATEGORIES[task.category]?.label?.split(' ')[0] || task.category}

              <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
              {task.is_follow_up === 1 && Follow-up}

                {task.assignee ? (

                    {task.assignee[0].toUpperCase()}

                ) :
<User size={9} className="text-gray-400" />
}
                {task.assignee && {task.assignee}}

                {task.due_date && (
                  <span className={`flex items-center gap-0.5 text-[10px] ${overdue ? 'text-red-500 font-semibold' : 'text-gray-400'}`}>
                    {overdue && <AlertTriangle size={9} />}{formatDate(task.due_date)}

                )}
                <button onClick={() => onMarkDone(task)}
                  className="opacity-0 group-hover:opacity-100 text-[10px] px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 rounded-full hover:bg-green-200 transition-all font-medium">
                  Done
                </button>

  );
}

// ── Drag overlay card (ghost while dragging) ─────────────────────────────────
function OverlayCard({ task }) {
  return (

{task.title}

        <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
        <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
          {CATEGORIES[task.category]?.label?.split(' ')[0]}

  );
}

// ── Droppable column ─────────────────────────────────────────────────────────
function DroppableColumn({ col, tasks, stats, onAddTask, onEdit, onDelete, onMarkDone }) {
  const { setNodeRef, isOver } = useDroppable({ id: col.id });

  return (

      {/* Column header */}

{col.title}

          <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${col.bg} ${col.color}`}>{tasks.length}

        <button onClick={onAddTask}
          className="w-6 h-6 rounded-lg bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-all shadow-sm">
          <Plus size={12} />
        </button>

      {/* Cards */}

        {tasks.length === 0 ? (

Drop here

        ) : (
          tasks.map(task => (
            <DraggableCard key={task.id} task={task} onEdit={onEdit} onDelete={onDelete} onMarkDone={onMarkDone} />
          ))
        )}

  );
}

// ── Main Dashboard ───────────────────────────────────────────────────────────
export default function Today() {
  const [allTasks, setAllTasks]     = useState([]);
  const [stats, setStats]           = useState(null);
  const [projects, setProjects]     = useState([]);
  const [loading, setLoading]       = useState(true);
  const [editTask, setEditTask]     = useState(null);
  const [deleteTask, setDeleteTask] = useState(null);
  const [showNew, setShowNew]       = useState(false);
  const [newDefaults, setNewDefaults] = useState({});
  const [activeTask, setActiveTask] = useState(null);
  const [activeTab, setActiveTab]   = useState('dashboard');
  const [quickInput, setQuickInput] = useState('');
  const navigate = useNavigate();

  const today = new Date();
  const dateLabel = today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  const load = useCallback(async () => {
    try {
      const [tasks, st, pr] = await Promise.all([api.get('/tasks'), api.get('/tasks/stats'), api.get('/projects')]);
      setAllTasks(tasks); setStats(st); setProjects(pr);
    } finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  // Bucket tasks into columns
  const columns = COLUMNS.map(col => ({
    ...col,
    tasks: allTasks.filter(t => getColumnId(t) === col.id),
  }));

  // DnD sensors — support mouse, touch (mobile), delay to prevent accidental drags
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(TouchSensor,   { activationConstraint: { delay: 180, tolerance: 6 } })
  );

  const onDragStart = ({ active }) => {
    setActiveTask(allTasks.find(t => t.id === active.id) || null);
  };

  const onDragEnd = async ({ active, over }) => {
    setActiveTask(null);
    if (!over) return;
    const task = allTasks.find(t => t.id === active.id);
    if (!task) return;
    const targetCol = COLUMNS.find(c => c.id === over.id);
    if (!targetCol || getColumnId(task) === targetCol.id) return;

    // Optimistic update
    const updated = columnUpdates(targetCol.id, task);
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, ...updated } : t));
    try {
      await api.put(`/tasks/${task.id}`, updated);
      toast.success(`Moved to "${targetCol.title}"`);
    } catch (e) {
      toast.error('Failed to move task'); load();
    }
  };

  const markDone = async (task) => {
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'Done' } : t));
    await api.patch(`/tasks/${task.id}/status`, { status: 'Done' });
    toast.success('Marked as done');
  };

  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); };

  const handleSave = async (form) => {
    try {
      if (editTask?.id) { await api.put(`/tasks/${editTask.id}`, form); toast.success('Task updated'); }
      else { await api.post('/tasks', { ...form, ...newDefaults }); toast.success('Task added'); }
      setEditTask(null); setShowNew(false); load();
    } catch (e) { toast.error(e.message); }
  };

  const handleDelete = async () => {
    await api.delete(`/tasks/${deleteTask.id}`);
    toast.success('Deleted'); setDeleteTask(null); load();
  };

  const TABS = [
    { id: 'dashboard', label: 'Dashboard' },
    { id: 'all',       label: 'All Tasks'      },
    { id: 'projects',  label: 'Projects'       },
  ];

  return (

      {/* Hero banner */}

              <Zap size={17} className="text-violet-600" />

DEWA AI Workspace

{dateLabel}

            {[
              { label: 'Projects',     value: stats?.activeProjects ?? '—', Icon: FolderKanban },
              { label: 'Open Tasks',   value: stats?.openTasks      ?? '—', Icon: CheckSquare  },
              { label: 'Follow-ups',   value: stats?.openFollowUps  ?? '—', Icon: Bell         },
              { label: "Today's Focus",value: stats?.todayFocus     ?? '—', Icon: Target       },
            ].map(({ label, value, Icon }) => (

{value}

                  <Icon size={9} />{label}

            ))}

      {/* Tabs */}

        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            className={`px-3.5 py-1.5 rounded-xl text-sm font-medium transition-all duration-150 ${
              activeTab === t.id
                ? 'bg-primary text-white shadow-sm'
                : 'text-gray-500 dark:text-gray-400 hover:bg-white dark:hover:bg-gray-800 hover:text-gray-800 dark:hover:text-white'
            }`}>
            {t.label}
          </button>
        ))}

        <button onClick={() => openNew({ is_today_focus: 1 })} className="btn-primary flex items-center gap-1 py-1.5 text-xs">
          <Plus size={12} /> New Task
        </button>

      {/* ── Kanban Board (drag & drop) ─────────────────────────────────── */}
      {loading ? (

          {[1,2,3,4].map(i =>
)}

      ) : (
        <>
          {activeTab === 'dashboard' && (
            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragEnd={onDragEnd}>
              {/* Horizontal scrollable kanban — snaps on mobile */}

                {columns.map(col => (
                  <DroppableColumn
                    key={col.id} col={col} tasks={col.tasks}
                    onAddTask={() => openNew(
                      col.id === 'focus'      ? { is_today_focus: 1 } :
                      col.id === 'inprogress' ? { status: 'In Progress' } :
                      col.id === 'followups'  ? { is_follow_up: 1 } : {}
                    )}
                    onEdit={setEditTask}
                    onDelete={setDeleteTask}
                    onMarkDone={markDone}
                  />
                ))}

              {/* Drag overlay */}
              <DragOverlay dropAnimation={{ duration: 180, easing: 'cubic-bezier(0.18,0.67,0.6,1.22)' }}>
                {activeTask && <OverlayCard task={activeTask} />}
              </DragOverlay>
            </DndContext>
          )}

          {/* ALL TASKS — horizontal grid */}
          {activeTab === 'all' && (

                {allTasks.filter(t => t.status !== 'Done').map(task => (

 setEditTask(task)}>

{task.title}

                      <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
                      <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                        {CATEGORIES[task.category]?.label?.split(' ')[0]}

                    {task.assignee && (

                          {task.assignee[0].toUpperCase()}

                        {task.assignee}

                    )}

                ))}

          )}

          {/* PROJECTS — horizontal grid */}
          {activeTab === 'projects' && (

                {projects.filter(p => p.status !== 'Done').map(p => (
                  <button key={p.id} onClick={() => navigate(`/projects/${p.id}`)}
                    className="card-hover text-left p-4 group">

                      <span className={`badge text-[10px] ${getCategoryClass(p.category)}`}>
                        {CATEGORIES[p.category]?.label?.split(' ')[0] || p.category}

                      <ArrowRight size={12} className="text-gray-300 group-hover:text-primary transition-colors" />

{p.name}

                      <span className={`font-semibold ${p.priority === 'Urgent' ? 'text-red-500' : p.priority === 'High' ? 'text-amber-500' : ''}`}>{p.priority}
                      {p.open_task_count || 0} tasks

                  </button>
                ))}

          )}
        </>
      )}

      {/* Modals */}
      {(showNew || editTask) && (
        <TaskModal task={editTask} projects={projects} onSave={handleSave} onClose={() => { setShowNew(false); setEditTask(null); }} />
      )}
      {deleteTask && (
        <ConfirmDialog title="Delete task?" message={`"${deleteTask.title}"`} onConfirm={handleDelete} onCancel={() => setDeleteTask(null)} />
      )}

  );
}

-  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); };

+  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); }

+      await api.post('/tasks', { title, priority: 'Medium', status: 'Open', category: 'adhoc', is_today_focus: 1 });

+      toast.success('Task added to Today\'s Focus');

+    } catch { toast.error('Failed to add task'); }


Now add the quick capture bar between the hero and tabs:


      {/* Tabs */}
      <div className="flex items-center gap-1 px-3 pt-2.5 pb-0 shrink-0">

{/* Quick Capture bar */}

        <form onSubmit={quickCapture} className="flex items-center gap-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl px-3 py-2 shadow-card focus-within:ring-2 focus-within:ring-primary/30 focus-within:border-primary/50 transition-all">
          <PenLine size={14} className="text-gray-400 shrink-0" />
          <input
            className="flex-1 bg-transparent text-sm text-gray-800 dark:text-gray-100 placeholder-gray-400 outline-none"
            placeholder="Capture a quick task… (Enter to add to Today's Focus)"
            value={quickInput}
            onChange={e => setQuickInput(e.target.value)}
          />
          {quickInput.trim() && (
            <button type="submit" className="shrink-0 flex items-center gap-1 px-2.5 py-1 bg-primary text-white text-xs font-medium rounded-xl hover:bg-primary/90 transition-colors">
              <Send size={11} /> Add
            </button>
          )}
          <button type="button" onClick={() => navigate('/inbox')}
            className="shrink-0 text-[10px] text-gray-400 hover:text-primary transition-colors whitespace-nowrap">
            AI Parse →
          </button>
        </form>

      {/* Tabs */}


      {/* Tabs */}
      <div className="flex items-center gap-1 px-3 pt-2.5 pb-0 shrink-0">

{/* Quick Capture bar */}

        <form onSubmit={quickCapture} className="flex items-center gap-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl px-3 py-2 shadow-card focus-within:ring-2 focus-within:ring-primary/30 focus-within:border-primary/50 transition-all">
          <PenLine size={14} className="text-gray-400 shrink-0" />
          <input
            className="flex-1 bg-transparent text-sm text-gray-800 dark:text-gray-100 placeholder-gray-400 outline-none"
            placeholder="Capture a quick task… (Enter to add to Today's Focus)"
            value={quickInput}
            onChange={e => setQuickInput(e.target.value)}
          />
          {quickInput.trim() && (
            <button type="submit" className="shrink-0 flex items-center gap-1 px-2.5 py-1 bg-primary text-white text-xs font-medium rounded-xl hover:bg-primary/90 transition-colors">
              <Send size={11} /> Add
            </button>
          )}
          <button type="button" onClick={() => navigate('/inbox')}
            className="shrink-0 text-[10px] text-gray-400 hover:text-primary transition-colors whitespace-nowrap">
            AI Parse →
          </button>
        </form>

      {/* Tabs */}

import { useState, useEffect, useCallback } from 'react';
import {
  DndContext, DragOverlay, useDroppable, useDraggable,
  PointerSensor, TouchSensor, useSensor, useSensors, closestCenter
} from '@dnd-kit/core';
import {
  Plus, User, Calendar, Zap, ArrowRight, FolderKanban,
  CheckSquare, Bell, Target, AlertTriangle, MoreHorizontal, GripVertical, PenLine, Send
} from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import api from '../api';
import TaskModal from './TaskModal';
import ConfirmDialog from './ConfirmDialog';
import { getCategoryClass, getPriorityClass, CATEGORIES, formatDate, isOverdue } from '../utils';

// ── Column config ────────────────────────────────────────────────────────────
const COLUMNS = [
  { id: 'focus',      title: "Today's Focus", color: 'text-primary',    bg: 'bg-primary/10',  border: 'border-l-primary'  },
  { id: 'inprogress', title: 'In Progress',   color: 'text-blue-600',   bg: 'bg-blue-50 dark:bg-blue-900/20',   border: 'border-l-blue-400'   },
  { id: 'followups',  title: 'Follow-ups',    color: 'text-amber-600',  bg: 'bg-amber-50 dark:bg-amber-900/20', border: 'border-l-amber-400'  },
  { id: 'open',       title: 'Open',          color: 'text-gray-500',   bg: 'bg-gray-100 dark:bg-gray-800',     border: 'border-l-gray-300'   },
];

const PRIORITY_BORDER = { Urgent:'border-l-red-500', High:'border-l-amber-400', Medium:'border-l-blue-400', Low:'border-l-green-400' };

function getColumnId(task) {
  if (task.status === 'Done') return null;
  if (task.is_today_focus)    return 'focus';
  if (task.status === 'In Progress') return 'inprogress';
  if (task.is_follow_up)      return 'followups';
  return 'open';
}

function columnUpdates(col, task) {
  const base = { ...task };
  if (col === 'focus')      return { ...base, is_today_focus: 1 };
  if (col === 'inprogress') return { ...base, status: 'In Progress', is_today_focus: 0 };
  if (col === 'followups')  return { ...base, is_follow_up: 1,  is_today_focus: 0 };
  if (col === 'open')       return { ...base, is_today_focus: 0, status: 'Open' };
  return base;
}

// ── Draggable card ───────────────────────────────────────────────────────────
function DraggableCard({ task, onEdit, onDelete, onMarkDone }) {
  const { attributes, listeners, setNodeRef, isDragging } = useDraggable({ id: task.id });
  const overdue = isOverdue(task.due_date);

  return (

          {/* Drag handle */}
          <button {...listeners} {...attributes}
            className="shrink-0 mt-0.5 text-gray-300 hover:text-gray-500 cursor-grab active:cursor-grabbing touch-none">
            <GripVertical size={14} />
          </button>

{task.title}

              <button onClick={() => onEdit(task)}
                className="shrink-0 opacity-0 group-hover:opacity-100 p-1 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-400 transition-all">
                <MoreHorizontal size={13} />
              </button>

            {task.notes &&
{task.notes}
}

              <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                {CATEGORIES[task.category]?.label?.split(' ')[0] || task.category}

              <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
              {task.is_follow_up === 1 && Follow-up}

                {task.assignee ? (

                    {task.assignee[0].toUpperCase()}

                ) :
<User size={9} className="text-gray-400" />
}
                {task.assignee && {task.assignee}}

                {task.due_date && (
                  <span className={`flex items-center gap-0.5 text-[10px] ${overdue ? 'text-red-500 font-semibold' : 'text-gray-400'}`}>
                    {overdue && <AlertTriangle size={9} />}{formatDate(task.due_date)}

                )}
                <button onClick={() => onMarkDone(task)}
                  className="opacity-0 group-hover:opacity-100 text-[10px] px-2 py-0.5 bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 rounded-full hover:bg-green-200 transition-all font-medium">
                  Done
                </button>

  );
}

// ── Drag overlay card (ghost while dragging) ─────────────────────────────────
function OverlayCard({ task }) {
  return (

{task.title}

        <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
        <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
          {CATEGORIES[task.category]?.label?.split(' ')[0]}

  );
}

// ── Droppable column ─────────────────────────────────────────────────────────
function DroppableColumn({ col, tasks, stats, onAddTask, onEdit, onDelete, onMarkDone }) {
  const { setNodeRef, isOver } = useDroppable({ id: col.id });

  return (

      {/* Column header */}

{col.title}

          <span className={`text-xs font-bold px-2 py-0.5 rounded-full ${col.bg} ${col.color}`}>{tasks.length}

        <button onClick={onAddTask}
          className="w-6 h-6 rounded-lg bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 flex items-center justify-center text-gray-400 hover:text-primary hover:border-primary transition-all shadow-sm">
          <Plus size={12} />
        </button>

      {/* Cards */}

        {tasks.length === 0 ? (

Drop here

        ) : (
          tasks.map(task => (
            <DraggableCard key={task.id} task={task} onEdit={onEdit} onDelete={onDelete} onMarkDone={onMarkDone} />
          ))
        )}

  );
}

// ── Main Dashboard ───────────────────────────────────────────────────────────
export default function Today() {
  const [allTasks, setAllTasks]     = useState([]);
  const [stats, setStats]           = useState(null);
  const [projects, setProjects]     = useState([]);
  const [loading, setLoading]       = useState(true);
  const [editTask, setEditTask]     = useState(null);
  const [deleteTask, setDeleteTask] = useState(null);
  const [showNew, setShowNew]       = useState(false);
  const [newDefaults, setNewDefaults] = useState({});
  const [activeTask, setActiveTask] = useState(null);
  const [activeTab, setActiveTab]   = useState('dashboard');
  const [quickInput, setQuickInput] = useState('');
  const navigate = useNavigate();

  const today = new Date();
  const dateLabel = today.toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  const load = useCallback(async () => {
    try {
      const [tasks, st, pr] = await Promise.all([api.get('/tasks'), api.get('/tasks/stats'), api.get('/projects')]);
      setAllTasks(tasks); setStats(st); setProjects(pr);
    } finally { setLoading(false); }
  }, []);

  useEffect(() => { load(); }, [load]);

  // Bucket tasks into columns
  const columns = COLUMNS.map(col => ({
    ...col,
    tasks: allTasks.filter(t => getColumnId(t) === col.id),
  }));

  // DnD sensors — support mouse, touch (mobile), delay to prevent accidental drags
  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
    useSensor(TouchSensor,   { activationConstraint: { delay: 180, tolerance: 6 } })
  );

  const onDragStart = ({ active }) => {
    setActiveTask(allTasks.find(t => t.id === active.id) || null);
  };

  const onDragEnd = async ({ active, over }) => {
    setActiveTask(null);
    if (!over) return;
    const task = allTasks.find(t => t.id === active.id);
    if (!task) return;
    const targetCol = COLUMNS.find(c => c.id === over.id);
    if (!targetCol || getColumnId(task) === targetCol.id) return;

    // Optimistic update
    const updated = columnUpdates(targetCol.id, task);
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, ...updated } : t));
    try {
      await api.put(`/tasks/${task.id}`, updated);
      toast.success(`Moved to "${targetCol.title}"`);
    } catch (e) {
      toast.error('Failed to move task'); load();
    }
  };

  const markDone = async (task) => {
    setAllTasks(prev => prev.map(t => t.id === task.id ? { ...t, status: 'Done' } : t));
    await api.patch(`/tasks/${task.id}/status`, { status: 'Done' });
    toast.success('Marked as done');
  };

  const openNew = (defaults = {}) => { setNewDefaults(defaults); setShowNew(true); }

  const quickCapture = async (e) => {
    e.preventDefault();
    const title = quickInput.trim();
    if (!title) return;
    try {
      await api.post('/tasks', { title, priority: 'Medium', status: 'Open', category: 'adhoc', is_today_focus: 1 });
      setQuickInput('');
      toast.success('Task added to Today\'s Focus');
      load();
    } catch { toast.error('Failed to add task'); }
  };;

  const handleSave = async (form) => {
    try {
      if (editTask?.id) { await api.put(`/tasks/${editTask.id}`, form); toast.success('Task updated'); }
      else { await api.post('/tasks', { ...form, ...newDefaults }); toast.success('Task added'); }
      setEditTask(null); setShowNew(false); load();
    } catch (e) { toast.error(e.message); }
  };

  const handleDelete = async () => {
    await api.delete(`/tasks/${deleteTask.id}`);
    toast.success('Deleted'); setDeleteTask(null); load();
  };

  const TABS = [
    { id: 'dashboard', label: 'Dashboard' },
    { id: 'all',       label: 'All Tasks'      },
    { id: 'projects',  label: 'Projects'       },
  ];

  return (

      {/* Hero banner */}

              <Zap size={17} className="text-violet-600" />

DEWA AI Workspace

{dateLabel}

            {[
              { label: 'Projects',     value: stats?.activeProjects ?? '—', Icon: FolderKanban },
              { label: 'Open Tasks',   value: stats?.openTasks      ?? '—', Icon: CheckSquare  },
              { label: 'Follow-ups',   value: stats?.openFollowUps  ?? '—', Icon: Bell         },
              { label: "Today's Focus",value: stats?.todayFocus     ?? '—', Icon: Target       },
            ].map(({ label, value, Icon }) => (

{value}

                  <Icon size={9} />{label}

            ))}

      {/* Tabs */}

        {TABS.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            className={`px-3.5 py-1.5 rounded-xl text-sm font-medium transition-all duration-150 ${
              activeTab === t.id
                ? 'bg-primary text-white shadow-sm'
                : 'text-gray-500 dark:text-gray-400 hover:bg-white dark:hover:bg-gray-800 hover:text-gray-800 dark:hover:text-white'
            }`}>
            {t.label}
          </button>
        ))}

        <button onClick={() => openNew({ is_today_focus: 1 })} className="btn-primary flex items-center gap-1 py-1.5 text-xs">
          <Plus size={12} /> New Task
        </button>

      {/* ── Kanban Board (drag & drop) ─────────────────────────────────── */}
      {loading ? (

          {[1,2,3,4].map(i =>
)}

      ) : (
        <>
          {activeTab === 'dashboard' && (
            <DndContext sensors={sensors} collisionDetection={closestCenter} onDragStart={onDragStart} onDragEnd={onDragEnd}>
              {/* Horizontal scrollable kanban — snaps on mobile */}

                {columns.map(col => (
                  <DroppableColumn
                    key={col.id} col={col} tasks={col.tasks}
                    onAddTask={() => openNew(
                      col.id === 'focus'      ? { is_today_focus: 1 } :
                      col.id === 'inprogress' ? { status: 'In Progress' } :
                      col.id === 'followups'  ? { is_follow_up: 1 } : {}
                    )}
                    onEdit={setEditTask}
                    onDelete={setDeleteTask}
                    onMarkDone={markDone}
                  />
                ))}

              {/* Drag overlay */}
              <DragOverlay dropAnimation={{ duration: 180, easing: 'cubic-bezier(0.18,0.67,0.6,1.22)' }}>
                {activeTask && <OverlayCard task={activeTask} />}
              </DragOverlay>
            </DndContext>
          )}

          {/* ALL TASKS — horizontal grid */}
          {activeTab === 'all' && (

                {allTasks.filter(t => t.status !== 'Done').map(task => (

 setEditTask(task)}>

{task.title}

                      <span className={`badge text-[10px] py-0.5 ${getPriorityClass(task.priority)}`}>{task.priority}
                      <span className={`badge text-[10px] py-0.5 ${getCategoryClass(task.category)}`}>
                        {CATEGORIES[task.category]?.label?.split(' ')[0]}

                    {task.assignee && (

                          {task.assignee[0].toUpperCase()}

                        {task.assignee}

                    )}

                ))}

          )}

          {/* PROJECTS — horizontal grid */}
          {activeTab === 'projects' && (

                {projects.filter(p => p.status !== 'Done').map(p => (
                  <button key={p.id} onClick={() => navigate(`/projects/${p.id}`)}
                    className="card-hover text-left p-4 group">

                      <span className={`badge text-[10px] ${getCategoryClass(p.category)}`}>
                        {CATEGORIES[p.category]?.label?.split(' ')[0] || p.category}

                      <ArrowRight size={12} className="text-gray-300 group-hover:text-primary transition-colors" />

{p.name}

                      <span className={`font-semibold ${p.priority === 'Urgent' ? 'text-red-500' : p.priority === 'High' ? 'text-amber-500' : ''}`}>{p.priority}
                      {p.open_task_count || 0} tasks

                  </button>
                ))}

          )}
        </>
      )}

      {/* Modals */}
      {(showNew || editTask) && (
        <TaskModal task={editTask} projects={projects} onSave={handleSave} onClose={() => { setShowNew(false); setEditTask(null); }} />
      )}
      {deleteTask && (
        <ConfirmDialog title="Delete task?" message={`"${deleteTask.title}"`} onConfirm={handleDelete} onCancel={() => setDeleteTask(null)} />
      )}

  );
}

+      <div className="shrink-0 px-3 pt-2.5">

+        <form onSubmit={quickCapture} className="flex items-center gap-2 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-2xl px-3 py-2 shadow-card focus-within:ring-2 focus-within:ring-primary/30 focus-within:border-primary/50 transition-all">

+          <PenLine size={14} className="text-gray-400 shrink-0" />

+            className="flex-1 bg-transparent text-sm text-gray-800 dark:text-gray-100 placeholder-gray-400 outline-none"

+            placeholder="Capture a quick task… (Enter to add to Today's Focus)"

+            onChange={e => setQuickInput(e.target.value)}

+            <button type="submit" className="shrink-0 flex items-center gap-1 px-2.5 py-1 bg-primary text-white text-xs font-medium rounded-xl hover:bg-primary/90 transition-colors">

+          <button type="button" onClick={() => navigate('/inbox')}

+            className="shrink-0 text-[10px] text-gray-400 hover:text-primary transition-colors whitespace-nowrap">


All three changes are done:

1. **Sidebar.jsx** — "Inbox" → "Quick Note" with `PenLine` icon
2. **BottomNav.jsx** — "Inbox" → "Quick Note" with `PenLine` icon
3. **Today.jsx** — Quick Capture bar added between the hero banner and tabs:
   - Type a task title and press Enter (or click "Add") → instantly adds to Today's Focus
   - "AI Parse →" link opens the Quick Note page for full AI parsing
   - Input has focus ring animation, the Add button only appears when there's text


remove the voice function in Quick note for now