// TASKS PLATFORM — Enterprise task management (multi-tab)
const { useState: useTkState, useMemo: useTkMemo, useCallback: useTkCb, useEffect: useTkEff } = React;
const T = window.ArbiterTokens;

const tStyles = {
  container: { flex: 1, overflow: 'auto', background: T.color.bg.primary },
  body:      { padding: '20px 24px' },
  statsRow:  { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' },
  toolbar:   { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' },
  searchInput: { height: '32px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 12px', fontSize: T.font.size.base, fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.primary, outline: 'none', width: '220px' },
  viewToggle: { marginLeft: 'auto', display: 'flex', gap: '2px', background: T.color.bg.secondary, borderRadius: T.radius.md, padding: '2px', border: `1px solid ${T.color.border.light}` },
  viewBtn: { padding: '4px 12px', borderRadius: T.radius.sm, border: 'none', fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, cursor: 'pointer', fontFamily: T.font.family, transition: 'all 0.1s' },
  filterBtn: { padding: '4px 10px', borderRadius: T.radius.md, border: `1px solid ${T.color.border.light}`, fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, cursor: 'pointer', fontFamily: T.font.family },
  selectInput: { height: '28px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 8px', fontSize: T.font.size.xs, fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.secondary, cursor: 'pointer' },
  listContainer: { background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.lg, overflow: 'hidden' },
  listHeaderRow: { display: 'grid', gridTemplateColumns: '28px 22px 1fr 140px 120px 70px 90px 70px 60px', padding: '6px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, gap: '8px', alignItems: 'center' },
  listRow: { display: 'grid', gridTemplateColumns: '28px 22px 1fr 140px 120px 70px 90px 70px 60px', padding: '9px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.sm, cursor: 'pointer', transition: 'background 0.1s', gap: '8px', alignItems: 'center' },
  groupHeader: { padding: '8px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`, fontSize: T.font.size.xs, fontWeight: T.font.weight.semibold, color: T.color.text.secondary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, display: 'flex', alignItems: 'center', gap: '8px' },
  kanban: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', alignItems: 'start' },
  kanbanCol: { background: T.color.bg.secondary, borderRadius: T.radius.lg, padding: '12px', minHeight: '200px' },
  kanbanColHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '10px', padding: '0 4px' },
  kanbanColTitle: { fontSize: T.font.size.sm, fontWeight: T.font.weight.semibold, color: T.color.text.primary },
  kanbanCount: { fontSize: T.font.size.xs, color: T.color.text.tertiary, background: T.color.bg.card, padding: '1px 7px', borderRadius: '10px' },
  kanbanCard: { background: T.color.bg.card, border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '10px 12px', marginBottom: '8px', cursor: 'pointer', transition: 'box-shadow 0.15s, border-color 0.15s' },
  detailOverlay: { position: 'fixed', inset: 0, background: 'rgba(10,22,40,0.3)', zIndex: 100, display: 'flex', justifyContent: 'flex-end' },
  detailPanel: { width: '520px', maxWidth: '100vw', background: T.color.bg.card, height: '100%', overflow: 'auto', boxShadow: '-4px 0 24px rgba(10,22,40,0.12)', padding: '24px', animation: 'slideInRight 0.2s ease-out' },
  detailTitle: { fontSize: T.font.size.lg, fontWeight: T.font.weight.bold, color: T.color.text.primary, lineHeight: 1.3, marginBottom: '16px' },
  detailMeta: { display: 'grid', gridTemplateColumns: '100px 1fr', gap: '8px 12px', fontSize: T.font.size.sm, marginBottom: '20px' },
  detailLabel: { color: T.color.text.tertiary, fontWeight: T.font.weight.medium, fontSize: T.font.size.xs, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, paddingTop: '2px' },
  detailValue: { color: T.color.text.primary },
  subtaskRow: { display: 'flex', alignItems: 'center', gap: '8px', padding: '5px 0', fontSize: T.font.size.sm, color: T.color.text.primary, cursor: 'pointer', borderRadius: T.radius.sm, transition: 'background 0.1s' },
  progressBar: { width: '100%', height: '4px', borderRadius: '2px', background: T.color.border.light },
  progressFill: { height: '100%', borderRadius: '2px', transition: 'width 0.3s ease' },
};

if (!document.getElementById('task-animations')) {
  const style = document.createElement('style');
  style.id = 'task-animations';
  style.textContent = `@keyframes slideInRight { from { transform: translateX(100%); opacity: 0.8; } to { transform: translateX(0); opacity: 1; } }`;
  document.head.appendChild(style);
}

const priorityColors = { high: T.color.status.critical, medium: T.color.status.warning, low: T.color.status.active };
const priorityOrder = { high: 0, medium: 1, low: 2 };
const statusColors = { 'To Do': T.color.status.pending, 'In Progress': T.color.accent.blue, 'In Review': T.color.status.warning, 'Done': T.color.status.active };

function dueDateUrgency(dateStr, status) {
  if (status === 'Done') return 'none';
  const d = new Date(dateStr), now = new Date();
  const days = Math.ceil((d - now) / 86400000);
  if (days < 0) return 'overdue';
  if (days <= 3) return 'urgent';
  return 'none';
}
function dueDateColor(dateStr, status) {
  const u = dueDateUrgency(dateStr, status);
  if (u === 'overdue') return T.color.status.critical;
  if (u === 'urgent') return T.color.status.warning;
  return T.color.text.tertiary;
}

function TaskCategoryBadge({ category }) {
  const c = window.CATEGORY_COLORS[category] || { bg: T.color.status.pendingBg, color: T.color.status.pending };
  return <span style={{ ...window.sharedStyles.tag, background: c.bg, color: c.color, fontSize: T.font.size.xs }}>{category}</span>;
}

function TaskStatusTag({ status }) {
  const c = statusColors[status] || T.color.status.pending;
  return <span style={{ ...window.sharedStyles.tag, background: `${c}14`, color: c }}>{status}</span>;
}

function AssigneeAvatar({ name, size = 22 }) {
  const initials = window.ASSIGNEE_INITIALS[name] || name.charAt(0);
  const color = window.ASSIGNEE_COLORS[name] || T.color.navy500;
  return (
    <span title={name} style={{
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
      width: `${size}px`, height: `${size}px`, borderRadius: '50%',
      background: `${color}18`, color: color,
      fontSize: `${Math.round(size * 0.45)}px`, fontWeight: T.font.weight.semibold,
      flexShrink: 0, letterSpacing: '-0.02em',
    }}>{initials}</span>
  );
}

function LinkedEntityRow({ icon, label, sublabel, color, onClick }) {
  const [hov, setHov] = useTkState(false);
  return (
    <div onClick={onClick} onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 8px', borderRadius: T.radius.sm, cursor: onClick ? 'pointer' : 'default', background: hov && onClick ? T.color.bg.hover : 'transparent', transition: 'background 0.1s' }}>
      <span style={{ width: '24px', height: '24px', borderRadius: T.radius.sm, background: `${color}12`, color: color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '11px', fontWeight: 700, flexShrink: 0 }}>{icon}</span>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: T.font.size.sm, color: T.color.text.primary, fontWeight: T.font.weight.medium, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</div>
        {sublabel && <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{sublabel}</div>}
      </div>
      {onClick && <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>→</span>}
    </div>
  );
}

function TaskDetailPanel({ task, onClose, onNavigate }) {
  const tk = window.__tk;
  const [commentDraft, setCommentDraft] = useTkState('');
  const [logOpen, setLogOpen] = useTkState(false);
  const data = window.useTaskStore ? window.useTaskStore(['updated','subtask.toggled','comment.added','time.logged','timer.started','timer.stopped']) : { tasks: [], activeTimer: null };

  // Always resolve the latest task from the store
  const t = data.tasks.find(x => x.id === task.id) || task;
  const isTiming = data.activeTimer && data.activeTimer.taskId === t.id;

  const done = t.subtasks.filter(s => s.done).length;
  const total = t.subtasks.length;
  const pct = total > 0 ? Math.round((done / total) * 100) : 0;
  const dueDate = new Date(t.dueDate);
  const urgency = dueDateUrgency(t.dueDate, t.status);
  const daysLeft = Math.ceil((dueDate - new Date()) / 86400000);
  const hoursPct = t.estimatedHours > 0 ? Math.min(100, Math.round((t.loggedHours / t.estimatedHours) * 100)) : 0;
  const overHours = t.loggedHours > t.estimatedHours;

  const linkedDeadlines = (t.linkedDeadlines || []).map(id => window.DOCKET_DEADLINES?.find(d => d.id === id)).filter(Boolean);
  const linkedDocs = (t.linkedDocs || []).map(id => window.ALL_DOCS_REF?.find(d => d.id === id)).filter(Boolean);
  const linkedEvidence = (t.linkedEvidence || []).map(id => {
    const ev = window.EVIDENCE_DATA?.['M-2024-0312'];
    return ev?.vault?.find(e => e.id === id);
  }).filter(Boolean);
  const hasLinks = linkedDeadlines.length > 0 || linkedDocs.length > 0 || linkedEvidence.length > 0;

  useTkEff(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);

  const toggleSub = (i) => window.TaskStore.toggleSubtask(t.id, i);
  const submitComment = () => {
    if (!commentDraft.trim()) return;
    window.TaskStore.addComment(t.id, commentDraft.trim());
    setCommentDraft('');
  };
  const toggleTimer = () => {
    if (isTiming) window.TaskStore.stopTimer();
    else window.TaskStore.startTimer(t.id);
  };
  const completeOrReopen = () => {
    if (t.status === 'Done') window.TaskStore.setStatus(t.id, 'To Do');
    else window.TaskStore.completeTask(t.id);
  };

  return (
    <div style={tStyles.detailOverlay} onClick={onClose}>
      <div style={tStyles.detailPanel} onClick={e => e.stopPropagation()}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: '4px' }}>
          <span style={{ fontSize: T.font.size.xs, fontFamily: T.font.mono, color: T.color.text.tertiary }}>{t.id}</span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: '18px', color: T.color.text.tertiary, cursor: 'pointer', padding: '0 4px' }}>×</button>
        </div>
        <div style={tStyles.detailTitle}>{t.title}</div>

        <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
          <TaskStatusTag status={t.status} />
          <span style={{ ...window.sharedStyles.tag, background: `${priorityColors[t.priority]}14`, color: priorityColors[t.priority] }}>{t.priority} priority</span>
          <TaskCategoryBadge category={t.category} />
          {t.blockedBy && t.blockedBy.length > 0 && (
            <span style={{ ...window.sharedStyles.tag, background: T.color.status.criticalBg, color: T.color.status.critical }}>⊘ Blocked by {t.blockedBy.join(', ')}</span>
          )}
          {t.blocks && t.blocks.length > 0 && (
            <span style={{ ...window.sharedStyles.tag, background: tk.cobaltBg, color: tk.cobalt }}>→ Blocks {t.blocks.join(', ')}</span>
          )}
        </div>

        <div style={tStyles.detailMeta}>
          <span style={tStyles.detailLabel}>Matter</span>
          <span style={{ ...tStyles.detailValue, cursor: 'pointer', color: T.color.accent.blue, fontWeight: T.font.weight.medium }}
            onClick={() => { onClose(); onNavigate && onNavigate('matter', t.matterId); }}>
            {t.matter} →
          </span>
          <span style={tStyles.detailLabel}>Assignee</span>
          <span style={{ ...tStyles.detailValue, display: 'flex', alignItems: 'center', gap: '8px' }}>
            <AssigneeAvatar name={t.assignee} size={20} />{t.assignee}
          </span>
          <span style={tStyles.detailLabel}>Due Date</span>
          <span style={{ ...tStyles.detailValue, color: urgency === 'overdue' ? T.color.status.critical : urgency === 'urgent' ? T.color.status.warning : T.color.text.primary, fontWeight: urgency !== 'none' ? T.font.weight.medium : T.font.weight.normal }}>
            {dueDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
            {urgency === 'overdue' ? ' (overdue)' : daysLeft <= 3 && t.status !== 'Done' ? ` (${daysLeft}d left)` : ''}
          </span>
        </div>

        {/* Time tracking */}
        <div style={{ marginBottom: '16px' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
            <span style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps }}>Time Tracked</span>
            <span style={{ fontSize: T.font.size.xs, fontFamily: T.font.mono, color: overHours ? T.color.status.critical : T.color.text.secondary }}>
              {t.loggedHours}h / {t.estimatedHours}h
            </span>
          </div>
          <div style={{ ...tStyles.progressBar, height: '6px' }}>
            <div style={{ ...tStyles.progressFill, height: '100%', width: `${hoursPct}%`, background: overHours ? T.color.status.critical : hoursPct > 75 ? T.color.status.warning : T.color.accent.blue }} />
          </div>
          <div style={{ display: 'flex', gap: '6px', marginTop: '8px' }}>
            <button onClick={toggleTimer}
              style={{ ...tk.btnPrimary, background: isTiming ? tk.crimson : tk.emerald, fontSize: '11px' }}>
              {isTiming ? '■ Stop timer' : '▶ Start timer'}
            </button>
            <button onClick={() => setLogOpen(true)} style={tk.btnSecondary}>+ Log time</button>
          </div>
        </div>

        <div style={{ marginBottom: '16px' }}>
          <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '6px' }}>Description</div>
          <div style={{ fontSize: T.font.size.sm, color: T.color.text.secondary, lineHeight: 1.5 }}>{t.description}</div>
        </div>

        {hasLinks && (
          <div style={{ marginBottom: '16px' }}>
            <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '8px' }}>Linked Items</div>
            <div style={{ background: T.color.bg.secondary, borderRadius: T.radius.md, padding: '4px', border: `1px solid ${T.color.border.light}` }}>
              {linkedDeadlines.map(dl => (
                <LinkedEntityRow key={dl.id} icon="▦" color="#D97706" label={dl.label}
                  sublabel={`${dl.matter} · ${new Date(dl.date).toLocaleDateString('en-US',{month:'short',day:'numeric'})} · ${dl.priority}`}
                  onClick={() => { onClose(); onNavigate && onNavigate('calendar'); }} />
              ))}
              {linkedDocs.map(doc => (
                <LinkedEntityRow key={doc.id} icon="▤" color="#2563EB" label={doc.name}
                  sublabel={`${doc.type} · ${doc.ext} · ${doc.size}`}
                  onClick={() => { onClose(); onNavigate && onNavigate('documents'); }} />
              ))}
              {linkedEvidence.map(ev => (
                <LinkedEntityRow key={ev.id} icon="◈" color="#6B21A8" label={ev.name}
                  sublabel={`${ev.bates} · ${ev.type} · ${ev.status}`}
                  onClick={() => { onClose(); onNavigate && onNavigate('evidence', t.matterId); }} />
              ))}
            </div>
          </div>
        )}

        {total > 0 && (
          <div style={{ marginBottom: '16px' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
              <span style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps }}>Subtasks</span>
              <span style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, fontFamily: T.font.mono }}>{done}/{total}</span>
            </div>
            <div style={tStyles.progressBar}>
              <div style={{ ...tStyles.progressFill, width: `${pct}%`, background: pct === 100 ? T.color.status.active : T.color.accent.blue }} />
            </div>
            <div style={{ marginTop: '8px' }}>
              {t.subtasks.map((s, i) => (
                <div key={i} style={{ ...tStyles.subtaskRow, padding: '5px 4px' }} onClick={() => toggleSub(i)}>
                  <span style={{ fontSize: '14px', color: s.done ? T.color.status.active : T.color.border.medium }}>{s.done ? 'ok' : ''}</span>
                  <span style={{ textDecoration: s.done ? 'line-through' : 'none', color: s.done ? T.color.text.tertiary : T.color.text.primary }}>{s.t}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Comments */}
        <div style={{ marginBottom: '16px' }}>
          <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '8px' }}>Comments · @mentions</div>
          {(t.comments || []).length === 0 && <div style={{ fontSize: '11px', color: T.color.text.tertiary, marginBottom: '8px' }}>No comments yet.</div>}
          {(t.comments || []).map(c => (
            <div key={c.id} style={{ padding: '8px 10px', borderLeft: `2px solid ${tk.cobalt}`, background: tk.cobaltBg, borderRadius: '4px', marginBottom: '6px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                <span style={{ fontSize: '11px', fontWeight: 700 }}>{c.actor}</span>
                <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{c.ts}</span>
              </div>
              <div style={{ fontSize: '12px', color: T.color.text.primary }}>{c.body}</div>
            </div>
          ))}
          <div style={{ display: 'flex', gap: '6px', marginTop: '6px' }}>
            <input value={commentDraft} onChange={e => setCommentDraft(e.target.value)}
              placeholder="Add a comment (use @M. Kirkland to mention)..."
              onKeyDown={e => { if (e.key === 'Enter') submitComment(); }}
              style={{ flex: 1, padding: '6px 10px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', fontSize: '11px', fontFamily: T.font.family }} />
            <button onClick={submitComment} style={tk.btnPrimary}>Post</button>
          </div>
        </div>

        {/* Activity */}
        {t.activity && t.activity.length > 0 && (
          <div style={{ marginBottom: '20px' }}>
            <div style={{ fontSize: T.font.size.xs, fontWeight: T.font.weight.medium, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: T.font.tracking.caps, marginBottom: '8px' }}>Activity</div>
            {t.activity.slice(0, 6).map((a, i) => (
              <div key={i} style={{ display: 'flex', gap: '8px', padding: '6px 0', borderBottom: i < Math.min(t.activity.length, 6) - 1 ? `1px solid ${T.color.border.light}` : 'none' }}>
                <AssigneeAvatar name={a.user} size={20} />
                <div style={{ flex: 1 }}>
                  <span style={{ fontSize: T.font.size.sm, color: T.color.text.primary }}><strong style={{ fontWeight: T.font.weight.medium }}>{a.user}</strong> {a.action}</span>
                  <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, marginTop: '1px' }}>{a.time}</div>
                </div>
              </div>
            ))}
          </div>
        )}

        <div style={{ display: 'flex', gap: '8px', marginTop: '20px', borderTop: `1px solid ${T.color.border.light}`, paddingTop: '16px' }}>
          <button onClick={completeOrReopen} style={{ ...window.sharedStyles.btn, ...window.sharedStyles.btnPrimary, flex: 1, justifyContent: 'center' }}>
            {t.status === 'Done' ? 'Reopen' : t.status === 'In Review' ? 'Approve & Complete' : 'Mark Complete'}
          </button>
          <button onClick={() => { if (confirm('Delete task?')) { window.TaskStore.deleteTask(t.id); onClose(); } }} style={{ ...window.sharedStyles.btn }}>Delete</button>
        </div>

        {logOpen && <window.TkLogTimeModal open={logOpen} onClose={() => setLogOpen(false)} taskId={t.id} />}
      </div>
    </div>
  );
}

function TasksPlatform({ onNavigate: onNav }) {
  const tk = window.__tk;
  const data = window.useTaskStore
    ? window.useTaskStore(['created','updated','deleted','completed','subtask.toggled','time.logged','comment.added','bulk.updated','view.saved','view.deleted','timer.started','timer.stopped'])
    : { tasks: window.TASKS, savedViews: [], templates: [], auditLog: [], mentions: [] };

  const [activeTab, setActiveTab] = useTkState('tasks');
  const [search, setSearch] = useTkState('');
  const [catFilter, setCatFilter] = useTkState('All');
  const [assigneeFilter, setAssigneeFilter] = useTkState('All');
  const [priorityFilter, setPriorityFilter] = useTkState('All');
  const [view, setView] = useTkState('list');
  const [selectedTask, setSelectedTask] = useTkState(null);
  const [hoveredRow, setHoveredRow] = useTkState(null);
  const [hoveredCard, setHoveredCard] = useTkState(null);
  const [myTasksOnly, setMyTasksOnly] = useTkState(false);
  const [hideCompleted, setHideCompleted] = useTkState(false);
  const [sortBy, setSortBy] = useTkState('due');
  const [sortAsc, setSortAsc] = useTkState(true);
  const [newTaskOpen, setNewTaskOpen] = useTkState(false);
  const [templateSeed, setTemplateSeed] = useTkState('');
  const [selectedIds, setSelectedIds] = useTkState([]);
  const [bulkOpen, setBulkOpen] = useTkState(false);

  const tasks = data.tasks;
  const ME = 'M. Kirkland';

  const applyFilter = (f) => {
    if (!f) return;
    if (f.assignee) setAssigneeFilter(f.assignee);
    if (f.status) { /* no direct status filter, leave to user */ }
    if (f.priority) setPriorityFilter(f.priority);
    if (f.overdue || f.thisWeek || f.blocked) setHideCompleted(true);
    setActiveTab('tasks');
  };

  const filtered = useTkMemo(() => {
    let t = tasks;
    if (hideCompleted) t = t.filter(x => x.status !== 'Done');
    if (myTasksOnly) t = t.filter(x => x.assignee === ME);
    if (catFilter !== 'All') t = t.filter(x => x.category === catFilter);
    if (assigneeFilter !== 'All') t = t.filter(x => x.assignee === assigneeFilter);
    if (priorityFilter !== 'All') t = t.filter(x => x.priority === priorityFilter);
    if (search) {
      const q = search.toLowerCase();
      t = t.filter(x => x.title.toLowerCase().includes(q) || x.matter.toLowerCase().includes(q) || x.assignee.toLowerCase().includes(q) || x.id.toLowerCase().includes(q));
    }
    return t;
  }, [tasks, search, catFilter, assigneeFilter, priorityFilter, myTasksOnly, hideCompleted]);

  const sorted = useTkMemo(() => {
    const arr = [...filtered];
    const dir = sortAsc ? 1 : -1;
    arr.sort((a, b) => {
      switch (sortBy) {
        case 'priority': return dir * (priorityOrder[a.priority] - priorityOrder[b.priority]);
        case 'due': return dir * (new Date(a.dueDate) - new Date(b.dueDate));
        case 'hours': return dir * (a.loggedHours - b.loggedHours);
        case 'status': return dir * (window.TASK_STATUSES.indexOf(a.status) - window.TASK_STATUSES.indexOf(b.status));
        case 'assignee': return dir * a.assignee.localeCompare(b.assignee);
        default: return 0;
      }
    });
    return arr;
  }, [filtered, sortBy, sortAsc]);

  const grouped = useTkMemo(() => {
    const groups = { overdue: [], today: [], thisWeek: [], later: [] };
    const now = new Date();
    const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
    const weekEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7);
    sorted.forEach(t => {
      const d = new Date(t.dueDate);
      if (t.status === 'Done') groups.later.push(t);
      else if (d < now) groups.overdue.push(t);
      else if (d < todayEnd) groups.today.push(t);
      else if (d < weekEnd) groups.thisWeek.push(t);
      else groups.later.push(t);
    });
    return groups;
  }, [sorted]);

  const activeTasks = filtered.filter(t => t.status !== 'Done');
  const overdue = activeTasks.filter(t => new Date(t.dueDate) < new Date());
  const totalEstimated = activeTasks.reduce((s, t) => s + t.estimatedHours, 0);
  const totalLogged = filtered.reduce((s, t) => s + t.loggedHours, 0);

  // Global KPIs (not filtered — for header)
  const kpi = {
    total:  tasks.length,
    active: tasks.filter(t => t.status !== 'Done').length,
    overdue:tasks.filter(t => t.status !== 'Done' && new Date(t.dueDate) < new Date()).length,
    review: tasks.filter(t => t.status === 'In Review').length,
    mentions: (data.mentions || []).filter(m => !m.read).length,
  };

  const handleSort = (col) => {
    if (sortBy === col) setSortAsc(!sortAsc);
    else { setSortBy(col); setSortAsc(true); }
  };
  const sortArrow = (col) => sortBy === col ? (sortAsc ? ' ↑' : ' ↓') : '';

  const toggleSelect = (id, e) => {
    e && e.stopPropagation();
    setSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };
  const clearSelection = () => setSelectedIds([]);

  const useTemplate = (id) => { setTemplateSeed(id); setNewTaskOpen(true); setActiveTab('tasks'); };

  const renderTaskRow = (t) => {
    const due = new Date(t.dueDate);
    const subtaskDone = t.subtasks.filter(s => s.done).length;
    const subtaskTotal = t.subtasks.length;
    const sel = selectedIds.includes(t.id);
    return (
      <div key={t.id} style={{ ...tStyles.listRow, background: sel ? tk.cobaltBg : hoveredRow === t.id ? T.color.bg.hover : 'transparent' }}
        onMouseEnter={() => setHoveredRow(t.id)} onMouseLeave={() => setHoveredRow(null)}
        onClick={() => setSelectedTask(t)}>
        <span style={{ width: '7px', height: '7px', borderRadius: '50%', background: priorityColors[t.priority] }} />
        <input type="checkbox" checked={sel} onChange={(e) => toggleSelect(t.id, e)} onClick={e => e.stopPropagation()}
          style={{ accentColor: tk.cobalt, cursor: 'pointer' }} />
        <div>
          <div style={{ fontWeight: T.font.weight.medium, color: T.color.text.primary, marginBottom: '1px', display: 'flex', alignItems: 'center' }}>
            {t.title}
            {t.blockedBy && t.blockedBy.length > 0 && (
              <span style={{ marginLeft: '6px', fontSize: T.font.size.xs, color: T.color.status.critical }}>⊘ {t.blockedBy.join(',')}</span>
            )}
          </div>
          {subtaskTotal > 0 && <span style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{subtaskDone}/{subtaskTotal} subtasks</span>}
        </div>
        <span style={{ color: T.color.text.tertiary, fontSize: T.font.size.xs }}>{t.matter}</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: '6px', color: T.color.text.secondary, fontSize: T.font.size.xs }}>
          <AssigneeAvatar name={t.assignee} size={20} />{t.assignee}
        </span>
        <span style={{ fontSize: T.font.size.xs, color: priorityColors[t.priority], fontWeight: T.font.weight.medium, textTransform: 'capitalize' }}>{t.priority}</span>
        <TaskStatusTag status={t.status} />
        <span style={{ fontFamily: T.font.mono, fontSize: T.font.size.xs, color: dueDateColor(t.dueDate, t.status), fontWeight: dueDateUrgency(t.dueDate, t.status) !== 'none' ? T.font.weight.medium : T.font.weight.normal }}>
          {due.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
        </span>
        <span style={{ fontFamily: T.font.mono, fontSize: T.font.size.xs, color: T.color.text.tertiary }}>{t.loggedHours}h</span>
      </div>
    );
  };

  const renderListView = () => (
    <div style={tStyles.listContainer}>
      <div style={tStyles.listHeaderRow}>
        <span></span>
        <span>
          <input type="checkbox"
            checked={selectedIds.length > 0 && selectedIds.length === filtered.length}
            onChange={e => setSelectedIds(e.target.checked ? filtered.map(t => t.id) : [])}
            style={{ accentColor: tk.cobalt, cursor: 'pointer' }} />
        </span>
        <span style={{ cursor: 'pointer' }} onClick={() => handleSort('due')}>Task</span>
        <span>Matter</span>
        <span style={{ cursor: 'pointer' }} onClick={() => handleSort('assignee')}>Assignee{sortArrow('assignee')}</span>
        <span style={{ cursor: 'pointer' }} onClick={() => handleSort('priority')}>Priority{sortArrow('priority')}</span>
        <span style={{ cursor: 'pointer' }} onClick={() => handleSort('status')}>Status{sortArrow('status')}</span>
        <span style={{ cursor: 'pointer' }} onClick={() => handleSort('due')}>Due{sortArrow('due')}</span>
        <span style={{ cursor: 'pointer' }} onClick={() => handleSort('hours')}>Hours{sortArrow('hours')}</span>
      </div>
      {[
        { key: 'overdue', label: 'Overdue', color: T.color.status.critical, tasks: grouped.overdue },
        { key: 'today', label: 'Today', color: T.color.status.warning, tasks: grouped.today },
        { key: 'thisWeek', label: 'This Week', color: T.color.accent.blue, tasks: grouped.thisWeek },
        { key: 'later', label: 'Later', color: T.color.text.tertiary, tasks: grouped.later },
      ].filter(g => g.tasks.length > 0).map(g => (
        <React.Fragment key={g.key}>
          <div style={tStyles.groupHeader}>
            <span style={{ width: '6px', height: '6px', borderRadius: '50%', background: g.color }} />
            {g.label}
            <span style={{ fontSize: '10px', color: T.color.text.tertiary, fontWeight: T.font.weight.normal }}>{g.tasks.length}</span>
          </div>
          {g.tasks.map(renderTaskRow)}
        </React.Fragment>
      ))}
      {filtered.length === 0 && (
        window.Arbiter?.EmptyState
          ? React.createElement(window.Arbiter.EmptyState, {
              title: 'No tasks match',
              description: 'Adjust filters or clear the search to see more results.',
            })
          : <div role="status" style={{ padding: '32px', textAlign: 'center', color: T.color.text.tertiary, fontSize: T.font.size.sm }}>No tasks match filters</div>
      )}
    </div>
  );

  const renderKanbanView = () => (
    <div style={tStyles.kanban}>
      {window.TASK_STATUSES.map(status => {
        const col = filtered.filter(t => t.status === status);
        return (
          <div key={status} style={tStyles.kanbanCol}>
            <div style={tStyles.kanbanColHeader}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: statusColors[status] }} />
                <span style={tStyles.kanbanColTitle}>{status}</span>
              </div>
              <span style={tStyles.kanbanCount}>{col.length}</span>
            </div>
            {col.map(t => {
              const subtaskDone = t.subtasks.filter(s => s.done).length;
              const subtaskTotal = t.subtasks.length;
              const due = new Date(t.dueDate);
              const isHovered = hoveredCard === t.id;
              return (
                <div key={t.id} style={{ ...tStyles.kanbanCard, borderColor: isHovered ? T.color.border.medium : T.color.border.light, boxShadow: isHovered ? T.shadow.md : 'none' }}
                  onMouseEnter={() => setHoveredCard(t.id)} onMouseLeave={() => setHoveredCard(null)}
                  onClick={() => setSelectedTask(t)}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                    <span style={{ fontSize: T.font.size.xs, fontFamily: T.font.mono, color: T.color.text.tertiary }}>{t.id}</span>
                    <span style={{ width: '7px', height: '7px', borderRadius: '50%', background: priorityColors[t.priority] }} />
                  </div>
                  <div style={{ fontSize: T.font.size.sm, fontWeight: T.font.weight.medium, color: T.color.text.primary, lineHeight: 1.35, marginBottom: '6px' }}>
                    {t.title}
                    {t.blockedBy && t.blockedBy.length > 0 && <span style={{ fontSize: '10px', color: T.color.status.critical, marginLeft: '4px' }}>⊘</span>}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '6px' }}>
                    <TaskCategoryBadge category={t.category} />
                  </div>
                  <div style={{ fontSize: T.font.size.xs, color: T.color.text.tertiary, marginBottom: '6px' }}>{t.matter}</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <AssigneeAvatar name={t.assignee} size={20} />
                    <span style={{ fontSize: T.font.size.xs, fontFamily: T.font.mono, color: dueDateColor(t.dueDate, t.status), fontWeight: dueDateUrgency(t.dueDate, t.status) !== 'none' ? T.font.weight.medium : T.font.weight.normal }}>
                      {due.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                    </span>
                  </div>
                  {subtaskTotal > 0 && (
                    <div style={{ marginTop: '8px' }}>
                      <div style={{ ...tStyles.progressBar, height: '3px' }}>
                        <div style={{ ...tStyles.progressFill, height: '100%', width: `${(subtaskDone / subtaskTotal) * 100}%`, background: subtaskDone === subtaskTotal ? T.color.status.active : T.color.accent.blue }} />
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );

  const renderTasksTab = () => (
    <>
      <div style={tStyles.statsRow}>
        <StatCard label="Active Tasks" value={activeTasks.length} delta={`${overdue.length} overdue`} deltaType={overdue.length > 0 ? 'down' : ''} />
        <StatCard label="Completed" value={filtered.filter(t => t.status === 'Done').length} delta="This month" deltaType="" />
        <StatCard label="Hours Logged" value={`${totalLogged}h`} delta={`${totalEstimated}h estimated`} deltaType="" />
        <StatCard label="In Review" value={filtered.filter(t => t.status === 'In Review').length} delta="Awaiting approval" deltaType="" />
      </div>

      <div style={tStyles.toolbar}>
        <input style={tStyles.searchInput} placeholder="Filter tasks..." value={search} onChange={e => setSearch(e.target.value)} />
        {window.TASK_CATEGORIES.map(c => (
          <button key={c} onClick={() => setCatFilter(c)} style={{
            ...tStyles.filterBtn,
            background: catFilter === c ? T.color.navy800 : T.color.bg.card,
            color: catFilter === c ? T.color.ivory100 : T.color.text.secondary,
          }}>{c}</button>
        ))}
        <select value={assigneeFilter} onChange={e => setAssigneeFilter(e.target.value)} style={tStyles.selectInput}>
          {window.TASK_ASSIGNEES.map(a => <option key={a} value={a}>{a === 'All' ? 'All Assignees' : a}</option>)}
        </select>
        <select value={priorityFilter} onChange={e => setPriorityFilter(e.target.value)} style={tStyles.selectInput}>
          <option value="All">All Priorities</option>
          <option value="high">High</option>
          <option value="medium">Medium</option>
          <option value="low">Low</option>
        </select>
        <label style={{ display: 'flex', alignItems: 'center', gap: '5px', fontSize: T.font.size.xs, color: T.color.text.tertiary, cursor: 'pointer' }}>
          <input type="checkbox" checked={hideCompleted} onChange={e => setHideCompleted(e.target.checked)} style={{ accentColor: T.color.navy800 }} />
          Hide done
        </label>
        <button onClick={() => setMyTasksOnly(!myTasksOnly)} style={{
          ...tStyles.filterBtn,
          background: myTasksOnly ? T.color.navy800 : T.color.bg.card,
          color: myTasksOnly ? T.color.ivory100 : T.color.text.secondary,
        }}>My Tasks</button>
        <div style={tStyles.viewToggle}>
          {['list', 'board'].map(v => (
            <button key={v} onClick={() => setView(v)} style={{
              ...tStyles.viewBtn,
              background: view === v ? T.color.bg.card : 'transparent',
              color: view === v ? T.color.text.primary : T.color.text.tertiary,
              boxShadow: view === v ? T.shadow.sm : 'none',
            }}>{v === 'list' ? ' List' : '▦ Board'}</button>
          ))}
        </div>
      </div>

      {/* Bulk-action bar */}
      {selectedIds.length > 0 && (
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 14px', marginBottom: '12px', background: tk.cobaltBg, border: `1px solid ${tk.cobaltBorder}`, borderRadius: '6px' }}>
          <span style={{ fontSize: '12px', fontWeight: 700, color: tk.cobalt }}>{selectedIds.length} selected</span>
          <button onClick={() => setBulkOpen(true)} style={tk.btnPrimary}> Bulk action</button>
          <button onClick={clearSelection} style={tk.btnSecondary}>Clear</button>
        </div>
      )}

      {view === 'list' ? renderListView() : renderKanbanView()}
    </>
  );

  const renderTab = () => {
    switch (activeTab) {
      case 'tasks':       return renderTasksTab();
      case 'myday':       return <window.TkMyDayHub me={ME} onSelectTask={setSelectedTask} />;
      case 'deps':        return <window.TkDependencyGraph onSelectTask={setSelectedTask} />;
      case 'analytics':   return <window.TkAnalyticsHub onSelectTask={setSelectedTask} />;
      case 'templates':   return <window.TkTemplatesPanel onUse={useTemplate} />;
      case 'views':       return <window.TkSavedViewsPanel onApply={applyFilter} />;
      case 'activity':    return <window.TkActivityHub onSelectTask={setSelectedTask} />;
      default:            return null;
    }
  };

  const tabs = [
    { id: 'tasks',     label: 'Tasks' },
    { id: 'myday',     label: 'My Day' },
    { id: 'deps',      label: 'Dependencies' },
    { id: 'analytics', label: 'Analytics' },
    { id: 'templates', label: 'Templates' },
    { id: 'views',     label: 'Saved Views' },
    { id: 'activity',  label: 'Activity', badge: kpi.mentions },
  ];

  return (
    <div style={tStyles.container}>
      {/* Header */}
      <div style={tk.header}>
        <div style={tk.headerTitle}>
          <div style={tk.tkIcon}><Icons.Check size={11}/></div>
          <div>
            <div style={tk.title}>Tasks</div>
            <div style={tk.subtitle}>Matter-Linked Workload · Dependencies · Time Tracking · Analytics</div>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <window.TkTimerChip />
          {[
            { l: 'Active',   v: kpi.active,   bg: tk.cobaltBg,   c: tk.cobalt },
            { l: 'Overdue',  v: kpi.overdue,  bg: kpi.overdue ? tk.crimsonBg : tk.emeraldBg, c: kpi.overdue ? tk.crimson : tk.emerald },
            { l: 'Review',   v: kpi.review,   bg: tk.amberBg,    c: tk.amber },
            { l: 'Mentions', v: kpi.mentions, bg: kpi.mentions ? tk.violetBg : T.color.bg.secondary, c: kpi.mentions ? tk.violet : T.color.text.tertiary },
          ].map(s => (
            <div key={s.l} style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '6px 14px', borderRadius: '8px', background: s.bg, border: `1px solid ${T.color.border.light}` }}>
              <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.l}</span>
              <span style={{ fontSize: '14px', fontWeight: 700, color: s.c, fontFamily: T.font.mono }}>{s.v}</span>
            </div>
          ))}
          <button style={tk.btnPrimary} onClick={() => { setTemplateSeed(''); setNewTaskOpen(true); }}>+ New Task</button>
        </div>
      </div>

      {/* Tabs */}
      <div style={tk.tabs}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            style={{ ...tk.tab, ...(activeTab === t.id ? tk.tabActive : {}) }}>
            {t.label}
            {t.badge > 0 && (
              <span style={{ marginLeft: '6px', padding: '1px 6px', borderRadius: '8px', background: tk.violetBg, color: tk.violet, fontSize: '9px', fontWeight: 800, fontFamily: T.font.mono }}>{t.badge}</span>
            )}
          </button>
        ))}
      </div>

      {/* Body */}
      <div style={tk.body}>{renderTab()}</div>

      {selectedTask && <TaskDetailPanel task={selectedTask} onClose={() => setSelectedTask(null)} onNavigate={(view, id) => onNav && onNav(view, id)} />}
      {newTaskOpen && <window.TkNewTaskModal open={newTaskOpen} onClose={() => { setNewTaskOpen(false); setTemplateSeed(''); }} onCreated={t => setSelectedTask(t)} templateId={templateSeed} />}
      {bulkOpen && <window.TkBulkModal open={bulkOpen} onClose={() => { setBulkOpen(false); clearSelection(); }} ids={selectedIds} />}
    </div>
  );
}

window.TasksPlatform = TasksPlatform;
