// TASKS PLATFORM — Extra enterprise views: modals, analytics hubs, widgets.
(function () {
  const { useState, useMemo, useEffect } = React;
  const T = window.ArbiterTokens;

  // ── Modal primitive ─────────────────────────────────────────────────────
  function TkModal({ open, onClose, title, children, width = 560, footer }) {
    if (!open) return null;
    const tk = window.__tk;
    return (
      <div onClick={onClose}
        style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)', zIndex: 2000, display: 'flex', alignItems: 'flex-start', justifyContent: 'center', padding: '80px 16px', overflow: 'auto' }}>
        <div onClick={e => e.stopPropagation()}
          style={{ width: '100%', maxWidth: `${width}px`, background: T.color.bg.card, borderRadius: T.radius.lg, boxShadow: '0 20px 60px rgba(15,23,42,0.35)', overflow: 'hidden', border: `1px solid ${T.color.border.light}` }}>
          <div style={{ padding: '14px 20px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: tk.cobaltBg }}>
            <div style={{ fontSize: '14px', fontWeight: 700, color: tk.cobalt, letterSpacing: '-0.01em' }}>{title}</div>
            <button onClick={onClose} style={{ border: 'none', background: 'transparent', fontSize: '18px', cursor: 'pointer', color: T.color.text.tertiary, lineHeight: 1 }}>×</button>
          </div>
          <div style={{ padding: '18px 20px' }}>{children}</div>
          {footer && <div style={{ padding: '12px 20px', borderTop: `1px solid ${T.color.border.light}`, background: T.color.bg.secondary, display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>{footer}</div>}
        </div>
      </div>
    );
  }

  const field = { display: 'flex', flexDirection: 'column', gap: '4px', marginBottom: '12px' };
  const lbl = { fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' };
  const inp = { padding: '8px 10px', borderRadius: '6px', border: `1px solid ${T.color.border.light}`, fontSize: '12px', fontFamily: T.font.family, background: T.color.bg.secondary, color: T.color.text.primary, width: '100%' };

  const ASSIGNEE_OPTS = ['M. Kirkland','S. Chen','R. Vasquez','L. Torres','A. Petrov','J. Park'];
  const CATS = ['Drafting','Filing','Review','Research','Deposition','Admin'];

  // ── Modal: New Task ─────────────────────────────────────────────────────
  function TkNewTaskModal({ open, onClose, onCreated, templateId }) {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore([]) : { templates: [] };
    const [title, setTitle] = useState('');
    const [matter, setMatter] = useState('');
    const [matterId, setMatterId] = useState('');
    const [assignee, setAssignee] = useState('M. Kirkland');
    const [priority, setPriority] = useState('medium');
    const [category, setCategory] = useState('Drafting');
    const [estimatedHours, setEst] = useState(4);
    const [dueDate, setDue] = useState(new Date().toISOString().slice(0, 10));
    const [description, setDesc] = useState('');
    const [recurring, setRecurring] = useState('');
    const [tpl, setTpl] = useState(templateId || '');

    useEffect(() => {
      if (!open) return;
      setTpl(templateId || '');
      if (templateId) {
        const t = (data.templates || []).find(x => x.id === templateId);
        if (t) { setTitle(t.name); setCategory(t.category); setEst(t.estimatedHours); setDesc(t.description); }
      }
    }, [open, templateId]);

    const applyTemplate = (id) => {
      setTpl(id);
      const t = (data.templates || []).find(x => x.id === id);
      if (t) { setTitle(t.name); setCategory(t.category); setEst(t.estimatedHours); setDesc(t.description); }
    };

    const canSubmit = title.trim().length > 1;
    const submit = () => {
      if (!canSubmit) return;
      const payload = {
        title: title.trim(), matter: matter.trim() || 'Unassigned', matterId: matterId.trim(),
        assignee, priority, category, estimatedHours: +estimatedHours, dueDate, description: description.trim(),
        recurrence: recurring ? { cadence: recurring, interval: 1 } : null,
      };
      let task;
      if (tpl) task = window.TaskStore.createFromTemplate(tpl, payload);
      else task = window.TaskStore.createTask(payload);
      onClose();
      onCreated && onCreated(task);
    };

    return (
      <TkModal open={open} onClose={onClose} title="+ New Task" width={640}
        footer={
          <>
            <button onClick={onClose} style={tk.btnSecondary}>Cancel</button>
            <button onClick={submit} disabled={!canSubmit}
              style={{ ...tk.btnPrimary, opacity: canSubmit ? 1 : 0.5, cursor: canSubmit ? 'pointer' : 'not-allowed' }}>
              Create task
            </button>
          </>
        }>
        {(data.templates || []).length > 0 && (
          <div style={field}><label style={lbl}>Start from template (optional)</label>
            <select value={tpl} onChange={e => applyTemplate(e.target.value)} style={inp}>
              <option value="">— None —</option>
              {data.templates.map(t => <option key={t.id} value={t.id}>{t.name} · {t.category} · {t.estimatedHours}h</option>)}
            </select>
          </div>
        )}
        <div style={field}><label style={lbl}>Task title</label>
          <input value={title} onChange={e => setTitle(e.target.value)} placeholder="What needs to be done?" style={inp} autoFocus />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
          <div style={field}><label style={lbl}>Matter</label>
            <input value={matter} onChange={e => setMatter(e.target.value)} placeholder="e.g. Redstone v. Meridian" style={inp} />
          </div>
          <div style={field}><label style={lbl}>Matter ID</label>
            <input value={matterId} onChange={e => setMatterId(e.target.value)} placeholder="M-2024-0xxx" style={inp} />
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
          <div style={field}><label style={lbl}>Assignee</label>
            <select value={assignee} onChange={e => setAssignee(e.target.value)} style={inp}>
              {ASSIGNEE_OPTS.map(a => <option key={a}>{a}</option>)}
            </select>
          </div>
          <div style={field}><label style={lbl}>Priority</label>
            <select value={priority} onChange={e => setPriority(e.target.value)} style={inp}>
              <option value="high">High</option><option value="medium">Medium</option><option value="low">Low</option>
            </select>
          </div>
          <div style={field}><label style={lbl}>Category</label>
            <select value={category} onChange={e => setCategory(e.target.value)} style={inp}>
              {CATS.map(c => <option key={c}>{c}</option>)}
            </select>
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
          <div style={field}><label style={lbl}>Est. hours</label>
            <input type="number" min={0.5} step={0.5} value={estimatedHours} onChange={e => setEst(e.target.value)} style={inp} />
          </div>
          <div style={field}><label style={lbl}>Due date</label>
            <input type="date" value={dueDate} onChange={e => setDue(e.target.value)} style={inp} />
          </div>
          <div style={field}><label style={lbl}>Recurrence</label>
            <select value={recurring} onChange={e => setRecurring(e.target.value)} style={inp}>
              <option value="">One-time</option><option value="daily">Daily</option>
              <option value="weekly">Weekly</option><option value="monthly">Monthly</option>
            </select>
          </div>
        </div>
        <div style={field}><label style={lbl}>Description</label>
          <textarea value={description} onChange={e => setDesc(e.target.value)} rows={3} style={{ ...inp, resize: 'vertical' }} />
        </div>
      </TkModal>
    );
  }

  // ── Modal: Log Time ─────────────────────────────────────────────────────
  function TkLogTimeModal({ open, onClose, taskId }) {
    const tk = window.__tk;
    const [hours, setHours] = useState(0.5);
    const [note, setNote] = useState('');
    useEffect(() => { if (open) { setHours(0.5); setNote(''); } }, [open]);
    const submit = () => { if (hours > 0) { window.TaskStore.logTime(taskId, +hours, note.trim()); onClose(); } };
    return (
      <TkModal open={open} onClose={onClose} title=" Log time entry"
        footer={
          <>
            <button onClick={onClose} style={tk.btnSecondary}>Cancel</button>
            <button onClick={submit} style={tk.btnPrimary}>Log {hours}h</button>
          </>
        }>
        <div style={field}><label style={lbl}>Hours</label>
          <input type="number" min={0.1} step={0.1} value={hours} onChange={e => setHours(e.target.value)} style={inp} autoFocus />
        </div>
        <div style={field}><label style={lbl}>Note</label>
          <textarea value={note} onChange={e => setNote(e.target.value)} rows={2} style={{ ...inp, resize: 'vertical' }} />
        </div>
      </TkModal>
    );
  }

  // ── Modal: Bulk action ──────────────────────────────────────────────────
  function TkBulkModal({ open, onClose, ids }) {
    const tk = window.__tk;
    const [action, setAction] = useState('status');
    const [statusVal, setStatusVal] = useState('In Progress');
    const [assigneeVal, setAssigneeVal] = useState('M. Kirkland');
    const [priorityVal, setPriorityVal] = useState('medium');
    if (!ids) ids = [];
    const apply = () => {
      if (action === 'status')   window.TaskStore.bulkSetStatus(ids, statusVal);
      if (action === 'assignee') window.TaskStore.bulkAssign(ids, assigneeVal);
      if (action === 'priority') window.TaskStore.bulkPriority(ids, priorityVal);
      if (action === 'delete')   window.TaskStore.bulkDelete(ids);
      onClose();
    };
    return (
      <TkModal open={open} onClose={onClose} title={` Bulk action · ${ids.length} tasks`}
        footer={
          <>
            <button onClick={onClose} style={tk.btnSecondary}>Cancel</button>
            <button onClick={apply} style={{ ...tk.btnPrimary, background: action === 'delete' ? tk.crimson : tk.cobalt }}>
              {action === 'delete' ? 'Delete' : 'Apply'}
            </button>
          </>
        }>
        <div style={field}><label style={lbl}>Action</label>
          <select value={action} onChange={e => setAction(e.target.value)} style={inp}>
            <option value="status">Change status</option>
            <option value="assignee">Reassign</option>
            <option value="priority">Change priority</option>
            <option value="delete">Delete</option>
          </select>
        </div>
        {action === 'status' && (
          <div style={field}><label style={lbl}>New status</label>
            <select value={statusVal} onChange={e => setStatusVal(e.target.value)} style={inp}>
              {['To Do','In Progress','In Review','Done'].map(s => <option key={s}>{s}</option>)}
            </select>
          </div>
        )}
        {action === 'assignee' && (
          <div style={field}><label style={lbl}>New assignee</label>
            <select value={assigneeVal} onChange={e => setAssigneeVal(e.target.value)} style={inp}>
              {ASSIGNEE_OPTS.map(a => <option key={a}>{a}</option>)}
            </select>
          </div>
        )}
        {action === 'priority' && (
          <div style={field}><label style={lbl}>New priority</label>
            <select value={priorityVal} onChange={e => setPriorityVal(e.target.value)} style={inp}>
              <option value="high">High</option><option value="medium">Medium</option><option value="low">Low</option>
            </select>
          </div>
        )}
      </TkModal>
    );
  }

  // ── Widget: Running Timer Chip ──────────────────────────────────────────
  function TkTimerChip() {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore(['timer.started','timer.stopped']) : {};
    const [tick, setTick] = useState(0);
    useEffect(() => {
      if (!data.activeTimer) return;
      const h = setInterval(() => setTick(x => x + 1), 1000);
      return () => clearInterval(h);
    }, [data.activeTimer]);
    if (!data.activeTimer) return null;
    const t = data.tasks.find(x => x.id === data.activeTimer.taskId);
    const elapsed = (Date.now() - data.activeTimer.startedAt) / 1000;
    const mm = String(Math.floor(elapsed / 60)).padStart(2, '0');
    const ss = String(Math.floor(elapsed % 60)).padStart(2, '0');
    return (
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: '8px', padding: '4px 10px', borderRadius: '16px', background: tk.emeraldBg, border: `1px solid ${tk.emerald}44` }}>
        <span style={{ width: '7px', height: '7px', borderRadius: '50%', background: tk.emerald, animation: 'pulse 1.6s infinite' }} />
        <span style={{ fontSize: '11px', color: tk.emerald, fontWeight: 700, fontFamily: T.font.mono }}>{mm}:{ss}</span>
        <span style={{ fontSize: '11px', color: T.color.text.secondary, maxWidth: '160px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t ? t.title : '—'}</span>
        <button onClick={() => window.TaskStore.stopTimer()}
          style={{ border: 'none', background: tk.crimson, color: '#fff', fontSize: '10px', fontWeight: 700, padding: '2px 8px', borderRadius: '10px', cursor: 'pointer' }}>Stop</button>
      </div>
    );
  }

  // ── Panel: My Day ───────────────────────────────────────────────────────
  function TkMyDayHub({ me = 'M. Kirkland', onSelectTask }) {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore(['created','updated','completed','time.logged']) : { tasks: [] };
    const now = new Date();
    const iso = now.toISOString().slice(0, 10);
    const mine = data.tasks.filter(t => t.assignee === me);
    const overdue = mine.filter(t => t.status !== 'Done' && new Date(t.dueDate) < now);
    const today = mine.filter(t => t.dueDate === iso && t.status !== 'Done');
    const inProg = mine.filter(t => t.status === 'In Progress');
    const review = mine.filter(t => t.status === 'In Review');
    const mentions = (data.mentions || []).filter(m => m.target && me.includes(m.target.split(' ')[0]) || m.target === me);

    const Section = ({ title, items, color, empty }) => (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={{ ...tk.cardH, color }}>{title}<span style={{ fontSize: '11px', color: T.color.text.tertiary, fontFamily: T.font.mono }}>{items.length}</span></div>
        <div style={{ maxHeight: '260px', overflowY: 'auto' }}>
          {items.length === 0 && <div style={{ padding: '20px', textAlign: 'center', color: T.color.text.tertiary, fontSize: '11px' }}>{empty}</div>}
          {items.map(t => (
            <div key={t.id} onClick={() => onSelectTask && onSelectTask(t)}
              style={{ padding: '8px 14px', borderBottom: `1px solid ${T.color.border.light}`, cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: '12px', fontWeight: 600, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.title}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '2px' }}>{t.matter} · {t.category}</div>
              </div>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: new Date(t.dueDate) < now ? tk.crimson : T.color.text.tertiary, whiteSpace: 'nowrap', marginLeft: '8px' }}>
                {new Date(t.dueDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
              </span>
            </div>
          ))}
        </div>
      </div>
    );

    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
          <div style={tk.stat}><span style={tk.statLabel}>Overdue</span><span style={{ ...tk.statValue, color: tk.crimson }}>{overdue.length}</span><span style={{ ...tk.statDelta, color: T.color.text.tertiary }}>need immediate attention</span></div>
          <div style={tk.stat}><span style={tk.statLabel}>Due today</span><span style={{ ...tk.statValue, color: tk.amber }}>{today.length}</span><span style={{ ...tk.statDelta, color: T.color.text.tertiary }}>on today's agenda</span></div>
          <div style={tk.stat}><span style={tk.statLabel}>In progress</span><span style={{ ...tk.statValue, color: tk.cobalt }}>{inProg.length}</span><span style={{ ...tk.statDelta, color: T.color.text.tertiary }}>active work</span></div>
          <div style={tk.stat}><span style={tk.statLabel}>Mentions</span><span style={{ ...tk.statValue, color: tk.violet }}>{mentions.filter(m => !m.read).length}</span><span style={{ ...tk.statDelta, color: T.color.text.tertiary }}>unread @mentions</span></div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
          <Section title="! Overdue" items={overdue} color={tk.crimson} empty="Nothing overdue — good job." />
          <Section title="◉ Due today" items={today} color={tk.amber} empty="Nothing due today." />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
          <Section title="⟳ In progress" items={inProg} color={tk.cobalt} empty="No work in progress." />
          <Section title="ok Awaiting review" items={review} color={tk.violet} empty="No reviews pending." />
        </div>
      </div>
    );
  }

  // ── Panel: Dependency Graph ─────────────────────────────────────────────
  function TkDependencyGraph({ onSelectTask }) {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore(['created','updated','deleted']) : { tasks: [] };
    // Layout: simple leveled DAG based on blockedBy depth
    const depth = {};
    const visit = (id, seen = new Set()) => {
      if (seen.has(id)) return 0;
      seen.add(id);
      const t = data.tasks.find(x => x.id === id);
      if (!t || !t.blockedBy.length) return 0;
      const d = 1 + Math.max(0, ...t.blockedBy.map(b => visit(b, seen)));
      return d;
    };
    data.tasks.forEach(t => { depth[t.id] = visit(t.id); });

    const chains = data.tasks.filter(t => t.blockedBy.length > 0 || t.blocks.length > 0);
    if (!chains.length) return (
      <div style={{ ...tk.card, marginBottom: 0, padding: '40px', textAlign: 'center', color: T.color.text.tertiary, fontSize: '12px' }}>
        No dependencies — all tasks independent.
      </div>
    );

    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span>◇ Dependency Graph</span><span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{chains.length} tasks with dependencies</span></div>
        <div style={{ padding: '16px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
          {chains.map(t => {
            const blockers = t.blockedBy.map(bid => data.tasks.find(x => x.id === bid)).filter(Boolean);
            const blocks   = t.blocks.map(bid => data.tasks.find(x => x.id === bid)).filter(Boolean);
            const statusC = tk.statusColor(t.status);
            return (
              <div key={t.id} style={{ border: `1px solid ${T.color.border.light}`, borderRadius: '6px', padding: '10px 12px', background: T.color.bg.secondary }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
                  <div onClick={() => onSelectTask && onSelectTask(t)} style={{ cursor: 'pointer', flex: 1 }}>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: T.color.text.primary }}>{t.title}</div>
                    <div style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary, marginTop: '1px' }}>{t.id} · depth {depth[t.id]}</div>
                  </div>
                  <span style={{ ...tk.tag, background: statusC.bg, color: statusC.color }}>{t.status}</span>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 20px 1fr', gap: '8px', alignItems: 'center', fontSize: '11px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>Blocked by ({blockers.length})</div>
                    {blockers.length === 0 && <span style={{ color: T.color.text.tertiary }}>—</span>}
                    {blockers.map(b => (
                      <div key={b.id} onClick={() => onSelectTask && onSelectTask(b)} style={{ cursor: 'pointer', padding: '3px 6px', background: tk.crimsonBg, color: tk.crimson, borderRadius: '4px', fontSize: '10px', marginBottom: '2px', fontWeight: 600 }}>
                        ← {b.id} {b.title.slice(0, 38)}{b.title.length > 38 ? '…' : ''}
                      </div>
                    ))}
                  </div>
                  <div style={{ textAlign: 'center', color: tk.cobalt, fontWeight: 700 }}>→</div>
                  <div>
                    <div style={{ fontSize: '9px', color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>Blocks ({blocks.length})</div>
                    {blocks.length === 0 && <span style={{ color: T.color.text.tertiary }}>—</span>}
                    {blocks.map(b => (
                      <div key={b.id} onClick={() => onSelectTask && onSelectTask(b)} style={{ cursor: 'pointer', padding: '3px 6px', background: tk.cobaltBg, color: tk.cobalt, borderRadius: '4px', fontSize: '10px', marginBottom: '2px', fontWeight: 600 }}>
                        → {b.id} {b.title.slice(0, 38)}{b.title.length > 38 ? '…' : ''}
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ── Panel: Activity / Audit Log ─────────────────────────────────────────
  function TkActivityTimeline({ taskId = null, limit = 25 }) {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore(['created','updated','completed','comment.added','time.logged']) : { auditLog: [] };
    const rows = (data.auditLog || []).filter(r => !taskId || r.taskId === taskId).slice(0, limit);
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span> Activity Log</span><span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{rows.length} entries</span></div>
        <div style={{ padding: '6px 0', maxHeight: '340px', overflowY: 'auto' }}>
          {rows.length === 0 && <div style={{ padding: '20px', textAlign: 'center', color: T.color.text.tertiary, fontSize: '12px' }}>No activity yet.</div>}
          {rows.map(r => (
            <div key={r.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'grid', gridTemplateColumns: '110px 1fr', gap: '12px' }}>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary, whiteSpace: 'nowrap' }}>{r.ts}</span>
              <div>
                <div style={{ fontSize: '12px', fontWeight: 700, color: tk.cobalt }}>{r.action}</div>
                <div style={{ fontSize: '11px', color: T.color.text.secondary, marginTop: '2px' }}>{r.detail}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '2px' }}>{r.actor}{r.taskId ? ` · ${r.taskId}` : ''}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── Panel: Workload Balance ─────────────────────────────────────────────
  function TkWorkloadPanel() {
    const tk = window.__tk;
    window.useTaskStore && window.useTaskStore(['created','updated','completed','time.logged']);
    const rows = window.TaskStore ? window.TaskStore.workloadBalance() : [];
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span> Workload Balance</span><span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>remaining hrs / weekly capacity</span></div>
        <div style={{ padding: '10px 16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
          {rows.map(r => {
            const color = r.overbooked ? tk.crimson : r.utilization > 80 ? tk.amber : tk.emerald;
            const pct = Math.min(150, r.utilization);
            return (
              <div key={r.assignee}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '3px' }}>
                  <span style={{ fontSize: '12px', fontWeight: 700 }}>{r.assignee}</span>
                  <span style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    {r.overbooked && <span style={{ ...tk.tag, background: tk.crimsonBg, color: tk.crimson }}>Overbooked</span>}
                    <span style={{ fontSize: '11px', fontFamily: T.font.mono, color }}>{r.remaining}h / {r.capacity}h · {r.utilization}%</span>
                    <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{r.count} tasks</span>
                  </span>
                </div>
                <div style={{ height: '6px', background: T.color.bg.secondary, borderRadius: '3px', overflow: 'hidden', position: 'relative' }}>
                  <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: color }} />
                  {pct > 100 && <div style={{ position: 'absolute', left: '100%', top: 0, width: `${pct - 100}%`, height: '100%', background: tk.crimson, opacity: 0.5 }} />}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ── Panel: Risk Flags ───────────────────────────────────────────────────
  function TkRiskFlagsPanel({ onSelectTask }) {
    const tk = window.__tk;
    window.useTaskStore && window.useTaskStore(['created','updated','completed']);
    const flags = window.TaskStore ? window.TaskStore.riskFlags() : [];
    return (
      <div style={{ ...tk.card, marginBottom: 0, borderTop: `2px solid ${tk.crimson}` }}>
        <div style={{ ...tk.cardH, color: tk.crimson }}>
          <span>flag At-Risk Tasks</span>
          <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{flags.length} flagged</span>
        </div>
        {flags.length === 0 ? (
          <div style={{ padding: '30px', textAlign: 'center', color: T.color.text.tertiary, fontSize: '12px' }}>No at-risk tasks. Keep it up.</div>
        ) : (
          <div style={{ maxHeight: '340px', overflowY: 'auto' }}>
            {flags.map(f => (
              <div key={f.taskId} onClick={() => onSelectTask && onSelectTask(f.task)}
                style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, cursor: 'pointer', display: 'grid', gridTemplateColumns: '40px 1fr auto', gap: '10px', alignItems: 'center' }}>
                <span style={{ ...tk.tag, background: tk.crimsonBg, color: tk.crimson, justifyContent: 'center', fontFamily: T.font.mono }}>{f.score}</span>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 700 }}>{f.task.title}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '2px' }}>
                    {f.reasons.map((r, i) => <span key={i} style={{ marginRight: '8px' }}>• {r}</span>)}
                  </div>
                </div>
                <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{f.task.assignee}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  }

  // ── Panel: Burndown Chart ───────────────────────────────────────────────
  function TkBurndown({ matterId = null }) {
    const tk = window.__tk;
    window.useTaskStore && window.useTaskStore(['created','updated','completed']);
    const series = window.TaskStore ? window.TaskStore.burndown(matterId, 14) : [];
    const W = 480, H = 120, pad = 20;
    const maxR = Math.max(1, ...series.map(s => s.remaining));
    const pts = series.map((s, i) => {
      const x = pad + (i / (series.length - 1)) * (W - pad * 2);
      const y = pad + (1 - s.remaining / maxR) * (H - pad * 2);
      return `${x},${y}`;
    }).join(' ');
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span> Burndown (14 days)</span><span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>remaining · peak {maxR}</span></div>
        <div style={{ padding: '14px' }}>
          <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block' }}>
            <polyline points={pts} fill="none" stroke={tk.cobalt} strokeWidth="2" />
            {series.map((s, i) => {
              const x = pad + (i / (series.length - 1)) * (W - pad * 2);
              const y = pad + (1 - s.remaining / maxR) * (H - pad * 2);
              return <circle key={i} cx={x} cy={y} r="2.5" fill={tk.cobalt} />;
            })}
            <line x1={pad} y1={H - pad} x2={W - pad} y2={H - pad} stroke={T.color.border.light} />
          </svg>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '9px', color: T.color.text.tertiary, fontFamily: T.font.mono, marginTop: '4px' }}>
            <span>{series[0]?.date.slice(5)}</span>
            <span>{series[series.length - 1]?.date.slice(5)}</span>
          </div>
        </div>
      </div>
    );
  }

  // ── Panel: Category SLA ─────────────────────────────────────────────────
  function TkCategorySlaPanel() {
    const tk = window.__tk;
    window.useTaskStore && window.useTaskStore(['created','updated','completed','time.logged']);
    const sla = window.TaskStore ? window.TaskStore.data.categorySla : {};
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span>◈ Category SLA · historical actuals</span></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={tk.th}>Category</th>
            <th style={tk.th}>Tasks</th>
            <th style={tk.th}>Avg est.</th>
            <th style={tk.th}>Avg logged</th>
            <th style={tk.th}>Variance</th>
          </tr></thead>
          <tbody>
            {Object.entries(sla).map(([c, v]) => {
              const varColor = v.variance > 20 ? tk.crimson : v.variance > 0 ? tk.amber : tk.emerald;
              return (
                <tr key={c}>
                  <td style={{ ...tk.td, fontWeight: 600 }}>{c}</td>
                  <td style={{ ...tk.td, fontFamily: T.font.mono }}>{v.count}</td>
                  <td style={{ ...tk.td, fontFamily: T.font.mono }}>{v.avgEst}h</td>
                  <td style={{ ...tk.td, fontFamily: T.font.mono }}>{v.avgLogged}h</td>
                  <td style={{ ...tk.td, fontFamily: T.font.mono, color: varColor, fontWeight: 700 }}>{v.variance > 0 ? '+' : ''}{v.variance}%</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }

  // ── Panel: Utilization Report ───────────────────────────────────────────
  function TkUtilizationPanel() {
    const tk = window.__tk;
    window.useTaskStore && window.useTaskStore(['created','updated','time.logged','completed']);
    const rows = window.TaskStore ? window.TaskStore.utilizationReport() : [];
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span>⟐ Utilization & Billable Report</span></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={tk.th}>Assignee</th>
            <th style={tk.th}>Logged</th>
            <th style={tk.th}>Billable</th>
            <th style={tk.th}>Admin</th>
            <th style={tk.th}>Billable %</th>
            <th style={tk.th}>Active</th>
            <th style={tk.th}>Completed</th>
          </tr></thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.assignee}>
                <td style={{ ...tk.td, fontWeight: 600 }}>{r.assignee}</td>
                <td style={{ ...tk.td, fontFamily: T.font.mono }}>{r.logged}h</td>
                <td style={{ ...tk.td, fontFamily: T.font.mono, color: tk.emerald }}>{r.billable}h</td>
                <td style={{ ...tk.td, fontFamily: T.font.mono, color: T.color.text.tertiary }}>{r.admin}h</td>
                <td style={{ ...tk.td, fontFamily: T.font.mono, fontWeight: 700, color: r.billablePct > 70 ? tk.emerald : r.billablePct > 50 ? tk.amber : tk.crimson }}>{r.billablePct}%</td>
                <td style={{ ...tk.td, fontFamily: T.font.mono }}>{r.active}</td>
                <td style={{ ...tk.td, fontFamily: T.font.mono }}>{r.completed}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }

  // ── Panel: Templates Library ────────────────────────────────────────────
  function TkTemplatesPanel({ onUse }) {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore([]) : { templates: [] };
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span> Task Templates</span><span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{(data.templates || []).length} available</span></div>
        <div style={{ padding: '14px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px' }}>
          {(data.templates || []).map(tpl => (
            <div key={tpl.id} style={{ border: `1px solid ${T.color.border.light}`, borderRadius: '6px', padding: '12px', background: T.color.bg.secondary }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                <span style={{ fontSize: '13px', fontWeight: 700, color: tk.cobalt }}>{tpl.name}</span>
                <span style={{ ...tk.tag, background: tk.cobaltBg, color: tk.cobalt }}>{tpl.category}</span>
              </div>
              <div style={{ fontSize: '11px', color: T.color.text.secondary, marginBottom: '8px' }}>{tpl.description}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '8px', fontFamily: T.font.mono }}>
                Est. {tpl.estimatedHours}h · {tpl.subtasks.length} subtasks
              </div>
              <ul style={{ margin: 0, padding: '0 0 10px 18px', fontSize: '11px', color: T.color.text.secondary }}>
                {tpl.subtasks.map((s, i) => <li key={i}>{s}</li>)}
              </ul>
              <button onClick={() => onUse && onUse(tpl.id)} style={{ ...tk.btnPrimary, width: '100%' }}>Use template →</button>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── Panel: Saved Views ──────────────────────────────────────────────────
  function TkSavedViewsPanel({ onApply }) {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore(['view.saved','view.deleted']) : { savedViews: [] };
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span>* Saved Views</span><span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{(data.savedViews || []).length}</span></div>
        <div style={{ padding: '10px 16px', display: 'flex', flexDirection: 'column', gap: '6px' }}>
          {(data.savedViews || []).map(v => {
            const parts = Object.entries(v.filter).map(([k, val]) => `${k}=${val}`).join(' · ');
            return (
              <div key={v.id} style={{ padding: '8px 12px', borderRadius: '6px', border: `1px solid ${T.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 700 }}>{v.name}{v.system && <span style={{ fontSize: '9px', color: T.color.text.tertiary, marginLeft: '4px' }}>(system)</span>}</div>
                  <div style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary, marginTop: '2px' }}>{parts}</div>
                </div>
                <div style={{ display: 'flex', gap: '4px' }}>
                  <button style={tk.btnGhost} onClick={() => onApply && onApply(v.filter)}>Apply</button>
                  {!v.system && <button style={{ ...tk.btnGhost, color: tk.crimson }} onClick={() => window.TaskStore.deleteView(v.id)}>Delete</button>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  // ── Panel: Mentions Inbox ───────────────────────────────────────────────
  function TkMentionsInbox({ me = 'M. Kirkland', onSelectTask }) {
    const tk = window.__tk;
    const data = window.useTaskStore ? window.useTaskStore(['comment.added','mention.read']) : { mentions: [] };
    const rows = (data.mentions || []).filter(m => m.target && m.target.toLowerCase().includes(me.toLowerCase().slice(0, 2))).slice(0, 20);
    return (
      <div style={{ ...tk.card, marginBottom: 0 }}>
        <div style={tk.cardH}><span>@ Mentions</span><span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{rows.filter(r => !r.read).length} unread</span></div>
        <div style={{ maxHeight: '260px', overflowY: 'auto' }}>
          {rows.length === 0 && <div style={{ padding: '20px', textAlign: 'center', color: T.color.text.tertiary, fontSize: '11px' }}>No mentions.</div>}
          {rows.map(m => (
            <div key={m.id} onClick={() => { window.TaskStore.markMentionRead(m.id); const t = data.tasks.find(x => x.id === m.taskId); onSelectTask && t && onSelectTask(t); }}
              style={{ padding: '10px 14px', borderBottom: `1px solid ${T.color.border.light}`, cursor: 'pointer', background: m.read ? 'transparent' : tk.cobaltBg }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '3px' }}>
                <span style={{ fontSize: '11px', fontWeight: 700 }}>{m.actor} → {m.target}</span>
                <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{m.ts}</span>
              </div>
              <div style={{ fontSize: '11px', color: T.color.text.secondary, marginBottom: '3px' }}>{m.body}</div>
              <div style={{ fontSize: '10px', color: tk.cobalt, fontFamily: T.font.mono }}>on {m.taskTitle}</div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── Analytics Hub (top-level tab) ───────────────────────────────────────
  function TkAnalyticsHub({ onSelectTask }) {
    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
          <TkWorkloadPanel />
          <TkRiskFlagsPanel onSelectTask={onSelectTask} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
          <TkBurndown />
          <TkCategorySlaPanel />
        </div>
        <TkUtilizationPanel />
      </div>
    );
  }

  // ── Activity Hub (top-level tab) ────────────────────────────────────────
  function TkActivityHub({ onSelectTask }) {
    return (
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
        <TkActivityTimeline limit={30} />
        <TkMentionsInbox onSelectTask={onSelectTask} />
      </div>
    );
  }

  // ── inject pulse keyframe
  if (!document.getElementById('tk-animations')) {
    const style = document.createElement('style');
    style.id = 'tk-animations';
    style.textContent = `@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.3} }`;
    document.head.appendChild(style);
  }

  // ── Exports ─────────────────────────────────────────────────────────────
  window.TkModal            = TkModal;
  window.TkNewTaskModal     = TkNewTaskModal;
  window.TkLogTimeModal     = TkLogTimeModal;
  window.TkBulkModal        = TkBulkModal;
  window.TkTimerChip        = TkTimerChip;
  window.TkMyDayHub         = TkMyDayHub;
  window.TkDependencyGraph  = TkDependencyGraph;
  window.TkActivityTimeline = TkActivityTimeline;
  window.TkWorkloadPanel    = TkWorkloadPanel;
  window.TkRiskFlagsPanel   = TkRiskFlagsPanel;
  window.TkBurndown         = TkBurndown;
  window.TkCategorySlaPanel = TkCategorySlaPanel;
  window.TkUtilizationPanel = TkUtilizationPanel;
  window.TkTemplatesPanel   = TkTemplatesPanel;
  window.TkSavedViewsPanel  = TkSavedViewsPanel;
  window.TkMentionsInbox    = TkMentionsInbox;
  window.TkAnalyticsHub     = TkAnalyticsHub;
  window.TkActivityHub      = TkActivityHub;
})();
