'use client'

import { useEffect, useMemo, useState, type DragEvent } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { AlertTriangle, CalendarClock, CheckCircle2, CircleDashed, Clock, ListChecks, MessageSquare, PlayCircle, RotateCcw, Search, Undo2 } from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import {
  DEV_TASK_STATUSES, STATUS_LABELS, URGENCY_LABELS, canMove, sortColumn, taskRef,
  type BoardRole, type DevTask, type DevTaskEvent, type DevTaskStatus, type DevTaskUrgency,
} from '@/lib/domain/dev-tasks'

/**
 * Developer task board (Nash, 2026-10-21). Three columns: Pending, Ongoing,
 * Completed. The developer drags a card (or uses the buttons in the task)
 * from Pending to Ongoing when he starts and to Completed when he is done;
 * the CTO sees it. The admin may also drag inside a column to reorder.
 * `apiBase` null = preview with sample data: changes stay in the browser.
 */
type Columns = Record<DevTaskStatus, DevTask[]>

const BTN = 'inline-flex items-center gap-1.5 rounded-lg bg-[#0f1b2d] px-3 py-2 text-xs font-bold text-white transition hover:bg-[#1c2d47] disabled:opacity-50'
const BTN_SOFT = 'inline-flex items-center gap-1.5 rounded-lg border bg-white px-3 py-2 text-xs font-bold text-neutral-800 transition hover:bg-neutral-50 disabled:opacity-50'

const URGENCY_STYLE: Record<DevTaskUrgency, { pill: string; bar: string }> = {
  urgent: { pill: 'bg-red-50 text-red-700 ring-red-200', bar: 'before:bg-red-500' },
  high: { pill: 'bg-orange-50 text-orange-700 ring-orange-200', bar: 'before:bg-orange-400' },
  normal: { pill: 'bg-sky-50 text-sky-700 ring-sky-200', bar: 'before:bg-sky-300' },
  low: { pill: 'bg-neutral-100 text-neutral-600 ring-neutral-200', bar: 'before:bg-neutral-300' },
}

const COLUMN_STYLE: Record<DevTaskStatus, { dot: string; tint: string; hint: string; icon: typeof CircleDashed }> = {
  pending: { dot: 'bg-amber-400', tint: 'bg-amber-50/40', hint: 'New tasks, most urgent first. Drag one to Ongoing when you start it.', icon: CircleDashed },
  ongoing: { dot: 'bg-sky-500', tint: 'bg-sky-50/40', hint: 'Being worked on. Drag to Completed when it is done.', icon: PlayCircle },
  completed: { dot: 'bg-emerald-500', tint: 'bg-emerald-50/40', hint: 'Done, newest first. The CTO is notified from here.', icon: CheckCircle2 },
}

function relative(iso: string | null, now: number | null): string {
  if (!iso) return ''
  const t = Date.parse(iso)
  if (now === null) return new Date(t).toISOString().slice(0, 10)
  const mins = Math.max(0, Math.round((now - t) / 60_000))
  if (mins < 1) return 'just now'
  if (mins < 60) return `${mins}m ago`
  const hours = Math.round(mins / 60)
  if (hours < 24) return `${hours}h ago`
  const days = Math.round(hours / 24)
  return days < 30 ? `${days}d ago` : new Date(t).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}

function dateTime(iso: string): string {
  return new Date(iso).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })
}

function isOverdue(task: DevTask, now: number | null): boolean {
  return !!task.due_date && task.status !== 'completed' && now !== null && Date.parse(`${task.due_date}T23:59:59`) < now
}

export function DevTaskBoard({ initial, commentCounts, role, apiBase, sampleEvents }: {
  initial: Columns
  commentCounts: Record<string, number>
  role: BoardRole
  apiBase: string | null
  sampleEvents?: Record<string, DevTaskEvent[]>
}) {
  const router = useRouter()
  const [columns, setColumns] = useState<Columns>(initial)
  const [project, setProject] = useState<string>('all')
  const [query, setQuery] = useState('')
  const [openId, setOpenId] = useState<string | null>(null)
  const [dragId, setDragId] = useState<string | null>(null)
  const [overColumn, setOverColumn] = useState<DevTaskStatus | null>(null)
  const [now, setNow] = useState<number | null>(null)

  // A server refresh brings new columns: adopt them (React's "adjust state on prop change" pattern).
  const [seen, setSeen] = useState(initial)
  if (seen !== initial) { setSeen(initial); setColumns(initial) }
  useEffect(() => {
    const first = setTimeout(() => setNow(Date.now()), 0)
    const tick = setInterval(() => setNow(Date.now()), 60_000)
    // The board refreshes itself so new tasks and moves show up without a reload.
    const refresh = apiBase ? setInterval(() => router.refresh(), 60_000) : null
    return () => { clearTimeout(first); clearInterval(tick); if (refresh) clearInterval(refresh) }
  }, [apiBase, router])

  const all = useMemo(() => DEV_TASK_STATUSES.flatMap((s) => columns[s]), [columns])
  const projects = useMemo(() => [...new Set(all.map((t) => t.project))].sort(), [all])
  const visible = (status: DevTaskStatus) => columns[status].filter((t) =>
    (project === 'all' || t.project === project) &&
    (!query.trim() || `${taskRef(t)} ${t.title} ${t.summary ?? ''}`.toLowerCase().includes(query.trim().toLowerCase())))
  const openTask = all.find((t) => t.id === openId) ?? null

  async function send(task: DevTask, body: Record<string, unknown>, optimistic: Columns, okMessage: string): Promise<boolean> {
    const previous = columns
    setColumns(optimistic)
    if (!apiBase) { toast.success(`${okMessage} (preview — not saved)`); return true }
    try {
      const res = await fetch(`${apiBase}/${task.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
      const json = await res.json().catch(() => ({}))
      if (!res.ok) throw new Error(json.error || 'The change was not saved.')
      toast.success(okMessage)
      router.refresh()
      return true
    } catch (e) {
      setColumns(previous)
      toast.error(e instanceof Error ? e.message : 'The change was not saved.')
      return false
    }
  }

  function moveTask(task: DevTask, to: DevTaskStatus, extra: { completion_note?: string | null; beforeId?: string } = {}) {
    if (!canMove(role, task.status, to)) { toast.error(`A task can't go from ${STATUS_LABELS[task.status]} to ${STATUS_LABELS[to]}.`); return Promise.resolve(false) }
    const nowIso = new Date().toISOString()
    const moved: DevTask = {
      ...task, status: to,
      started_at: to === 'pending' ? null : task.started_at ?? nowIso,
      completed_at: to === 'completed' ? nowIso : null,
      completion_note: to === 'completed' ? extra.completion_note ?? task.completion_note : null,
    }
    const next: Columns = { ...columns, [task.status]: columns[task.status].filter((t) => t.id !== task.id) }
    const dest = next[to].filter((t) => t.id !== task.id)
    const at = extra.beforeId ? dest.findIndex((t) => t.id === extra.beforeId) : -1
    if (at >= 0) dest.splice(at, 0, moved)
    else if (to === 'completed') dest.unshift(moved)
    else dest.push(moved)
    next[to] = to === 'completed' ? sortColumn(dest) : dest
    const body: Record<string, unknown> = { status: to }
    if (to === 'completed' && extra.completion_note) body.completion_note = extra.completion_note
    if (extra.beforeId && role === 'manager') body.place = { before: extra.beforeId }
    const message = to === 'ongoing' ? `${taskRef(task)} started` : to === 'completed' ? `${taskRef(task)} completed` : `${taskRef(task)} moved back to Pending`
    return send(task, body, next, task.status === to ? `${taskRef(task)} moved` : message)
  }

  function reorder(task: DevTask, beforeId: string | null) {
    const list = columns[task.status].filter((t) => t.id !== task.id)
    const at = beforeId ? list.findIndex((t) => t.id === beforeId) : -1
    if (at >= 0) list.splice(at, 0, task)
    else list.push(task)
    const place = beforeId ? { before: beforeId } : { edge: 'bottom' }
    void send(task, { place }, { ...columns, [task.status]: list }, `${taskRef(task)} moved`)
  }

  function onDrop(e: DragEvent, to: DevTaskStatus, beforeId: string | null) {
    e.preventDefault()
    e.stopPropagation()
    setOverColumn(null)
    const task = all.find((t) => t.id === (dragId ?? e.dataTransfer.getData('text/plain')))
    setDragId(null)
    if (!task || task.id === beforeId) return
    if (task.status === to) {
      if (role === 'manager' && to !== 'completed') reorder(task, beforeId)
      return
    }
    if (to === 'completed') { setOpenId(task.id); toast.message('Add a short completion note, then confirm.'); return }
    void moveTask(task, to, { beforeId: beforeId ?? undefined })
  }

  const total = all.length
  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex flex-wrap items-center gap-1.5">
          {['all', ...projects].map((p) => (
            <button key={p} type="button" onClick={() => setProject(p)}
              className={`rounded-full px-3 py-1 text-xs font-semibold ring-1 ring-inset transition ${project === p ? 'bg-[#0f1b2d] text-white ring-[#0f1b2d]' : 'bg-white text-neutral-600 ring-neutral-200 hover:bg-neutral-50'}`}>
              {p === 'all' ? `All projects · ${total}` : p}
            </button>
          ))}
        </div>
        <label className="relative ml-auto w-full sm:w-64">
          <Search className="pointer-events-none absolute left-2.5 top-2.5 size-4 text-neutral-400" aria-hidden />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search tasks or T-number"
            className="w-full rounded-lg border bg-white py-2 pl-8 pr-3 text-sm outline-none focus:ring-2 focus:ring-[#0f1b2d]/15" />
        </label>
      </div>

      <div className="grid gap-4 lg:grid-cols-3">
        {DEV_TASK_STATUSES.map((status) => {
          const style = COLUMN_STYLE[status]
          const list = visible(status)
          const dropAllowed = dragId ? (() => { const t = all.find((x) => x.id === dragId); return !!t && (t.status === status ? role === 'manager' && status !== 'completed' : canMove(role, t.status, status)) })() : false
          return (
            <section key={status}
              onDragOver={(e) => { if (dropAllowed) { e.preventDefault(); setOverColumn(status) } }}
              onDragLeave={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node)) setOverColumn(null) }}
              onDrop={(e) => onDrop(e, status, null)}
              className={`flex min-h-[420px] flex-col rounded-2xl border p-3 transition ${style.tint} ${overColumn === status ? 'border-[#0f1b2d]/40 ring-2 ring-[#0f1b2d]/10' : ''} ${dragId && !dropAllowed ? 'opacity-60' : ''}`}>
              <header className="mb-3 px-1">
                <div className="flex items-center gap-2">
                  <span className={`size-2.5 rounded-full ${style.dot}`} aria-hidden />
                  <h2 className="text-sm font-bold">{STATUS_LABELS[status]}</h2>
                  <span className="rounded-full bg-white px-2 py-0.5 text-[11px] font-bold text-neutral-600 ring-1 ring-inset ring-neutral-200">{list.length}</span>
                </div>
                <p className="mt-1 text-[11px] leading-snug text-neutral-500">{style.hint}</p>
              </header>
              <ol className="flex flex-1 flex-col gap-2.5">
                {list.map((task) => (
                  <li key={task.id}>
                    <TaskCard task={task} now={now} comments={commentCounts[task.id] ?? 0} dragging={dragId === task.id}
                      onOpen={() => setOpenId(task.id)}
                      onDragStart={(e) => { e.dataTransfer.setData('text/plain', task.id); e.dataTransfer.effectAllowed = 'move'; setDragId(task.id) }}
                      onDragEnd={() => { setDragId(null); setOverColumn(null) }}
                      onDropBefore={(e) => onDrop(e, status, task.id)} />
                  </li>
                ))}
                {!list.length && (
                  <li className="flex flex-1 items-center justify-center rounded-xl border border-dashed border-neutral-300 p-6 text-center text-xs text-neutral-400">
                    {status === 'pending' ? 'No tasks waiting.' : status === 'ongoing' ? 'Nothing in progress.' : 'Nothing completed yet.'}
                  </li>
                )}
              </ol>
            </section>
          )
        })}
      </div>

      <TaskDialog key={openTask?.id ?? 'closed'} task={openTask} role={role} now={now} apiBase={apiBase} sampleEvents={sampleEvents}
        onClose={() => setOpenId(null)} onMove={moveTask} />
    </div>
  )
}

function TaskCard({ task, now, comments, dragging, onOpen, onDragStart, onDragEnd, onDropBefore }: {
  task: DevTask; now: number | null; comments: number; dragging: boolean
  onOpen: () => void; onDragStart: (e: DragEvent) => void; onDragEnd: () => void; onDropBefore: (e: DragEvent) => void
}) {
  const u = URGENCY_STYLE[task.urgency]
  const overdue = isOverdue(task, now)
  const when = task.status === 'completed' ? `Done ${relative(task.completed_at, now)}` : task.status === 'ongoing' ? `Started ${relative(task.started_at, now)}` : `Added ${relative(task.created_at, now)}`
  return (
    <button type="button" draggable onClick={onOpen} onDragStart={onDragStart} onDragEnd={onDragEnd}
      onDragOver={(e) => e.preventDefault()} onDrop={onDropBefore}
      className={`group relative w-full overflow-hidden rounded-xl border bg-white p-3 pl-4 text-left shadow-[0_1px_2px_rgba(15,27,45,0.04)] transition before:absolute before:inset-y-0 before:left-0 before:w-1 hover:-translate-y-px hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-[#0f1b2d]/30 ${u.bar} ${dragging ? 'opacity-40' : ''} ${task.status === 'completed' ? 'bg-white/80' : ''}`}>
      <div className="flex items-center gap-2">
        <span className="font-mono text-[11px] font-bold text-neutral-400">{taskRef(task)}</span>
        <span className={`rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ring-1 ring-inset ${u.pill}`}>{URGENCY_LABELS[task.urgency]}</span>
        <span className="ml-auto truncate text-[11px] font-medium text-neutral-500">{task.project}</span>
      </div>
      <h3 className={`mt-1.5 text-sm font-semibold leading-snug ${task.status === 'completed' ? 'text-neutral-600' : 'text-neutral-900'}`}>{task.title}</h3>
      {task.summary && <p className="mt-1 line-clamp-2 text-xs leading-relaxed text-neutral-500">{task.summary}</p>}
      <div className="mt-2.5 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-neutral-500">
        {task.steps.length > 0 && <span className="inline-flex items-center gap-1"><ListChecks className="size-3.5" aria-hidden />{task.steps.length} steps</span>}
        {comments > 0 && <span className="inline-flex items-center gap-1"><MessageSquare className="size-3.5" aria-hidden />{comments}</span>}
        {task.due_date && (
          <span className={`inline-flex items-center gap-1 ${overdue ? 'font-bold text-red-600' : ''}`}>
            {overdue ? <AlertTriangle className="size-3.5" aria-hidden /> : <CalendarClock className="size-3.5" aria-hidden />}
            Due {new Date(`${task.due_date}T12:00:00`).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
          </span>
        )}
        <span className="ml-auto inline-flex items-center gap-1"><Clock className="size-3.5" aria-hidden />{when}</span>
      </div>
    </button>
  )
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <section>
      <h4 className="mb-1.5 text-[11px] font-bold uppercase tracking-wider text-neutral-500">{title}</h4>
      <div className="text-sm leading-relaxed text-neutral-800">{children}</div>
    </section>
  )
}

const EVENT_TEXT: Record<string, (e: DevTaskEvent) => string> = {
  created: () => 'created the task',
  updated: (e) => `edited ${((e.detail.fields as string[] | undefined) ?? []).join(', ').replace(/_/g, ' ') || 'the task'}`,
  moved: (e) => `moved it to ${STATUS_LABELS[e.to_status as DevTaskStatus] ?? e.to_status}`,
  reordered: () => 'changed its place in the column',
  archived: () => 'removed it from the board',
  restored: () => 'restored it',
}

function TaskDialog({ task, role, now, apiBase, sampleEvents, onClose, onMove }: {
  task: DevTask | null; role: BoardRole; now: number | null; apiBase: string | null
  sampleEvents?: Record<string, DevTaskEvent[]>
  onClose: () => void
  onMove: (task: DevTask, to: DevTaskStatus, extra?: { completion_note?: string | null }) => Promise<boolean>
}) {
  // Keyed by task id, so every opened task starts with fresh state.
  const [events, setEvents] = useState<DevTaskEvent[]>(() => (!apiBase && task ? sampleEvents?.[task.id] ?? [] : []))
  const [comment, setComment] = useState('')
  const [note, setNote] = useState('')
  const [completing, setCompleting] = useState(false)
  const [busy, setBusy] = useState(false)
  const taskId = task?.id ?? null

  useEffect(() => {
    if (!taskId || !apiBase) return
    let live = true
    fetch(`${apiBase}/${taskId}`).then((r) => r.json()).then((j) => { if (live) setEvents(j.events ?? []) }).catch(() => undefined)
    return () => { live = false }
  }, [taskId, apiBase])

  if (!task) return null
  const u = URGENCY_STYLE[task.urgency]

  async function move(to: DevTaskStatus) {
    if (!task) return
    setBusy(true)
    const ok = await onMove(task, to, to === 'completed' ? { completion_note: note.trim() || null } : {})
    setBusy(false)
    if (ok) { setCompleting(false); if (to === 'completed') onClose() }
  }

  async function postComment() {
    if (!task || !comment.trim()) return
    setBusy(true)
    const text = comment.trim()
    if (!apiBase) {
      setEvents((list) => [...list, { id: `local-${list.length}`, task_id: task.id, action: 'comment', from_status: task.status, to_status: task.status, actor_kind: role === 'manager' ? 'admin' : 'developer', actor_label: 'You (preview)', detail: { text }, created_at: new Date().toISOString() }])
      setComment(''); setBusy(false); return
    }
    const res = await fetch(`${apiBase}/${task.id}/comments`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) })
    const json = await res.json().catch(() => ({}))
    setBusy(false)
    if (!res.ok) { toast.error(json.error || 'The comment was not saved.'); return }
    setEvents((list) => [...list, json.comment])
    setComment('')
    toast.success('Comment posted')
  }

  return (
    <Dialog open onOpenChange={(open) => { if (!open) onClose() }}>
      <DialogContent className="max-h-[90vh] gap-0 overflow-y-auto p-0 sm:max-w-2xl">
        <DialogHeader className="border-b px-6 pb-4 pt-5 text-left">
          <div className="flex flex-wrap items-center gap-2 text-xs">
            <span className="font-mono font-bold text-neutral-400">{taskRef(task)}</span>
            <span className={`rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ring-1 ring-inset ${u.pill}`}>{URGENCY_LABELS[task.urgency]}</span>
            <span className="rounded-full bg-neutral-100 px-2 py-0.5 font-semibold text-neutral-600">{task.project}</span>
            <span className="inline-flex items-center gap-1 font-semibold text-neutral-600"><span className={`size-2 rounded-full ${COLUMN_STYLE[task.status].dot}`} />{STATUS_LABELS[task.status]}</span>
          </div>
          <DialogTitle className="mt-2 text-lg leading-snug">{task.title}</DialogTitle>
          <DialogDescription className="text-sm text-neutral-600">{task.summary || 'Read the brief below, then move the task when you start and when you finish.'}</DialogDescription>
        </DialogHeader>

        <div className="space-y-5 px-6 py-5">
          {task.why && <Section title="Why"><p className="whitespace-pre-wrap">{task.why}</p></Section>}
          {task.steps.length > 0 && (
            <Section title="Steps, in order">
              <ol className="space-y-2">
                {task.steps.map((step, i) => (
                  <li key={i} className="flex gap-3">
                    <span className="mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full bg-[#0f1b2d] text-[10px] font-bold text-white">{i + 1}</span>
                    <span className="whitespace-pre-wrap">{step}</span>
                  </li>
                ))}
              </ol>
            </Section>
          )}
          {task.done_when && <Section title="Done when"><p className="whitespace-pre-wrap">{task.done_when}</p></Section>}
          {task.report_back && <Section title="Report back"><p className="whitespace-pre-wrap">{task.report_back}</p></Section>}
          {task.do_not_touch && (
            <Section title="Do not touch">
              <p className="whitespace-pre-wrap rounded-lg bg-red-50 px-3 py-2 text-red-900">{task.do_not_touch}</p>
            </Section>
          )}
          {task.details && <Section title="Details"><p className="whitespace-pre-wrap">{task.details}</p></Section>}
          {task.completion_note && (
            <Section title="Completion note">
              <p className="whitespace-pre-wrap rounded-lg bg-emerald-50 px-3 py-2 text-emerald-900">{task.completion_note}</p>
            </Section>
          )}

          <dl className="grid grid-cols-2 gap-2 rounded-xl bg-neutral-50 p-3 text-xs sm:grid-cols-4">
            {[
              ['Added', task.created_at], ['Started', task.started_at], ['Completed', task.completed_at],
            ].map(([k, v]) => (
              <div key={k}><dt className="font-bold uppercase tracking-wide text-neutral-400">{k}</dt><dd className="mt-0.5 font-semibold text-neutral-700">{v ? (now === null ? v.slice(0, 10) : dateTime(v)) : '—'}</dd></div>
            ))}
            <div><dt className="font-bold uppercase tracking-wide text-neutral-400">Due</dt><dd className={`mt-0.5 font-semibold ${isOverdue(task, now) ? 'text-red-600' : 'text-neutral-700'}`}>{task.due_date ?? '—'}</dd></div>
          </dl>

          <div className="flex flex-wrap items-center gap-2 border-t pt-4">
            {task.status === 'pending' && <button type="button" disabled={busy} onClick={() => move('ongoing')} className={BTN}><PlayCircle className="size-4" />Start task</button>}
            {task.status === 'ongoing' && !completing && (
              <>
                <button type="button" disabled={busy} onClick={() => setCompleting(true)} className={BTN}><CheckCircle2 className="size-4" />Mark completed</button>
                <button type="button" disabled={busy} onClick={() => move('pending')} className={BTN_SOFT}><Undo2 className="size-4" />Back to Pending</button>
              </>
            )}
            {task.status === 'completed' && <button type="button" disabled={busy} onClick={() => move('ongoing')} className={BTN_SOFT}><RotateCcw className="size-4" />Reopen</button>}
            {role === 'manager' && task.status === 'completed' && <button type="button" disabled={busy} onClick={() => move('pending')} className={BTN_SOFT}><Undo2 className="size-4" />Back to Pending</button>}
          </div>
          {completing && (
            <div className="space-y-2 rounded-xl border border-emerald-200 bg-emerald-50/60 p-3">
              <label className="block text-xs font-bold text-emerald-900" htmlFor="completion-note">Completion note: what you did, the commit or branch, and anything to check</label>
              <textarea id="completion-note" value={note} onChange={(e) => setNote(e.target.value)} rows={4} maxLength={4000}
                placeholder={task.report_back ?? 'Commit abc1234 on main. Tests pass. Deployed at 9:40 AM CT.'}
                className="w-full rounded-lg border bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-emerald-600/20" />
              <div className="flex gap-2">
                <button type="button" disabled={busy} onClick={() => move('completed')} className={BTN}><CheckCircle2 className="size-4" />Confirm completed</button>
                <button type="button" disabled={busy} onClick={() => setCompleting(false)} className={BTN_SOFT}>Cancel</button>
              </div>
            </div>
          )}

          <Section title="Questions and history">
            <ol className="space-y-2.5">
              {events.map((e) => e.action === 'comment' ? (
                <li key={e.id} className={`rounded-xl px-3 py-2 ${e.actor_kind === 'developer' ? 'bg-sky-50' : 'bg-neutral-100'}`}>
                  <div className="text-[11px] font-bold text-neutral-500">{e.actor_label} · {relative(e.created_at, now)}</div>
                  <p className="mt-0.5 whitespace-pre-wrap text-sm text-neutral-800">{String(e.detail.text ?? '')}</p>
                </li>
              ) : (
                <li key={e.id} className="flex items-center gap-2 text-xs text-neutral-500">
                  <span className="size-1.5 rounded-full bg-neutral-300" aria-hidden />
                  <span><b className="font-semibold text-neutral-700">{e.actor_label}</b> {(EVENT_TEXT[e.action] ?? (() => e.action))(e)}{e.action === 'moved' && e.detail.note ? ' with a note' : ''} · {relative(e.created_at, now)}</span>
                </li>
              ))}
              {!events.length && <li className="text-xs text-neutral-400">No questions yet.</li>}
            </ol>
            <div className="mt-3 flex flex-col gap-2 sm:flex-row">
              <textarea value={comment} onChange={(e) => setComment(e.target.value)} rows={2} maxLength={4000}
                placeholder={role === 'developer' ? 'Ask a question or post an update on this task' : 'Answer or add a note for the developer'}
                className="min-h-[44px] flex-1 rounded-lg border bg-white px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-[#0f1b2d]/15" />
              <button type="button" disabled={busy || !comment.trim()} onClick={postComment} className={`${BTN} justify-center`}><MessageSquare className="size-4" />Post</button>
            </div>
          </Section>
        </div>
      </DialogContent>
    </Dialog>
  )
}
