// Artboard 3: Kanban Board with drag & drop.

const { AGENTS: AA3, MINISTRIES: MM3 } = window.DHAM;

const INIT_TASKS = [
  { id: 't1',  col: 'backlog',   title: 'Refactor task queue for priority inversion', assignee: 'yantaka',     ministry: 'tech',     prio: 'high',   estimate: '4h', tag: 'refactor' },
  { id: 't2',  col: 'backlog',   title: 'Image generation batch · marketing',           assignee: 'cittakara',   ministry: 'culture',  prio: 'low',    estimate: '2h', tag: 'content' },
  { id: 't3',  col: 'backlog',   title: 'Draft Q2 sales outlook report',                assignee: 'vanijja',     ministry: 'commerce', prio: 'med',    estimate: '1d', tag: 'report' },
  { id: 't4',  col: 'backlog',   title: 'Rotate API keys across all 6 cities',         assignee: 'kuncika',     ministry: 'defense',  prio: 'high',   estimate: '30m', tag: 'security' },
  { id: 't5',  col: 'progress',  title: 'Hot-fix redis pool connection limit',         assignee: 'arakkhaka',   ministry: 'interior', prio: 'crit',   estimate: '1h', tag: 'bug', progress: 62 },
  { id: 't6',  col: 'progress',  title: 'Mesh v2 architecture spec',                   assignee: 'vijjadhara',  ministry: 'tech',     prio: 'high',   estimate: '2d', tag: 'design', progress: 40 },
  { id: 't7',  col: 'progress',  title: 'Scrape 48 AI news sources',                   assignee: 'rahu',        ministry: 'intel',    prio: 'low',    estimate: '2h', tag: 'ingest', progress: 78 },
  { id: 't8',  col: 'progress',  title: 'Provisioning dev-env · proxmox',              assignee: 'nidhi',       ministry: 'tech',     prio: 'med',    estimate: '45m', tag: 'ops', progress: 88 },
  { id: 't9',  col: 'review',    title: 'Kanban drag-drop polish',                     assignee: 'angkura',     ministry: 'tech',     prio: 'med',    estimate: '3h', tag: 'ui' },
  { id: 't10', col: 'review',    title: 'Weekly digest · tone review',                 assignee: 'sasanaka',    ministry: 'comms',    prio: 'low',    estimate: '20m', tag: 'content' },
  { id: 't11', col: 'review',    title: 'DPA draft · legal compliance',                assignee: 'neetisara',   ministry: 'justice',  prio: 'high',   estimate: '—', tag: 'legal' },
  { id: 't12', col: 'done',      title: 'Close daily ledger',                          assignee: 'kosajja',     ministry: 'finance',  prio: 'med',    estimate: '—', tag: 'finance' },
  { id: 't13', col: 'done',      title: 'Listing sync · Remax · 420 items',            assignee: 'dev-remax',   ministry: 'company',  prio: 'med',    estimate: '—', tag: 'sync' },
  { id: 't14', col: 'done',      title: 'Optimize DB indexes · products',              assignee: 'dhammadhara', ministry: 'data',     prio: 'low',    estimate: '—', tag: 'perf' },
];

const PRIO = {
  crit: { c: 'var(--danger)',  l: 'CRIT' },
  high: { c: 'var(--amber)',   l: 'HIGH' },
  med:  { c: 'var(--info)',    l: 'MED' },
  low:  { c: 'var(--text-dim)',l: 'LOW' },
};

const COLS = [
  { id: 'backlog',  name: 'Backlog',     desc: 'awaiting pickup' },
  { id: 'progress', name: 'In Progress', desc: 'actively working' },
  { id: 'review',   name: 'Review',      desc: 'awaiting audit' },
  { id: 'done',     name: 'Done',        desc: 'shipped today' },
];

function TaskCard({ task, isDragging, onPointerDown }) {
  const agent = AA3.find((a) => a.id === task.assignee);
  const m = MM3[task.ministry];
  const p = PRIO[task.prio];
  return (
    <div onPointerDown={onPointerDown}
      style={{
        background: 'var(--surface-hi)',
        border: `1px solid ${isDragging ? 'var(--gold)' : 'var(--line)'}`,
        borderLeft: `3px solid ${m.color}`,
        borderRadius: 3, padding: 10, marginBottom: 8,
        cursor: 'grab', userSelect: 'none',
        boxShadow: isDragging ? '0 12px 32px rgba(0,0,0,0.5), 0 0 0 1px var(--gold)' : 'none',
        transform: isDragging ? 'rotate(-1deg)' : 'none',
        transition: isDragging ? 'none' : 'all .15s',
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
        <span style={{ fontSize: 9, fontFamily: 'var(--mono)', color: p.c, fontWeight: 700, letterSpacing: 1 }}>{p.l}</span>
        <span style={{ fontSize: 9, fontFamily: 'var(--mono)', color: 'var(--text-faint)' }}>· {task.tag}</span>
        <div style={{ flex: 1 }} />
        <MinistryTag id={task.ministry} />
      </div>
      <div style={{ fontSize: 12, lineHeight: 1.3, marginBottom: 10, color: 'var(--text)' }}>{task.title}</div>
      {task.progress != null && (
        <div style={{ marginBottom: 8 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9, fontFamily: 'var(--mono)', color: 'var(--text-dim)', marginBottom: 3 }}>
            <span>PROGRESS</span><span>{task.progress}%</span>
          </div>
          <div style={{ height: 2, background: 'var(--surface-lo)', borderRadius: 1, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${task.progress}%`, background: 'var(--gold)' }} />
          </div>
        </div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--mono)' }}>
        {agent && <Avatar agent={agent} size={20} showStatus={false} />}
        <span>{agent?.pali || task.assignee}</span>
        <div style={{ flex: 1 }} />
        <span>⟐ {task.estimate}</span>
      </div>
    </div>
  );
}

function Artboard_Kanban() {
  const [tasks, setTasks] = React.useState(() => {
    try { const s = localStorage.getItem('dham_kanban'); return s ? JSON.parse(s) : INIT_TASKS; } catch { return INIT_TASKS; }
  });
  React.useEffect(() => { try { localStorage.setItem('dham_kanban', JSON.stringify(tasks)); } catch {} }, [tasks]);
  const [drag, setDrag] = React.useState(null); // { id, x, y, ox, oy, fromCol }
  const [hoverCol, setHoverCol] = React.useState(null);

  React.useEffect(() => {
    if (!drag) return;
    const move = (e) => setDrag((d) => d ? { ...d, x: e.clientX, y: e.clientY } : null);
    const up = (e) => {
      const el = document.elementFromPoint(e.clientX, e.clientY);
      const col = el?.closest?.('[data-kanban-col]');
      if (col) {
        const colId = col.dataset.kanbanCol;
        setTasks((ts) => ts.map((t) => t.id === drag.id ? { ...t, col: colId } : t));
      }
      setDrag(null);
      setHoverCol(null);
    };
    const hover = (e) => {
      const el = document.elementFromPoint(e.clientX, e.clientY);
      const col = el?.closest?.('[data-kanban-col]');
      setHoverCol(col?.dataset.kanbanCol || null);
    };
    window.addEventListener('pointermove', move);
    window.addEventListener('pointermove', hover);
    window.addEventListener('pointerup', up);
    return () => {
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointermove', hover);
      window.removeEventListener('pointerup', up);
    };
  }, [drag]);

  const startDrag = (e, task) => {
    const r = e.currentTarget.getBoundingClientRect();
    setDrag({ id: task.id, x: e.clientX, y: e.clientY, ox: e.clientX - r.left, oy: e.clientY - r.top, w: r.width, fromCol: task.col });
  };

  const dragTask = drag && tasks.find((t) => t.id === drag.id);

  return (
    <AppChrome activePage="kanban" title="Tasks · Kanban" subtitle="DRAG TO MOVE · 14 ACTIVE">
      <div style={{ display: 'flex', gap: 12, flex: 1, overflow: 'hidden' }}>
        {COLS.map((c) => {
          const colTasks = tasks.filter((t) => t.col === c.id);
          const isHover = hoverCol === c.id && drag && drag.fromCol !== c.id;
          return (
            <div key={c.id} data-kanban-col={c.id}
              style={{
                flex: 1, background: isHover ? 'var(--surface)' : 'var(--surface-lo)',
                border: `1px solid ${isHover ? 'var(--gold)' : 'var(--line)'}`,
                borderRadius: 3, display: 'flex', flexDirection: 'column', overflow: 'hidden',
                transition: 'background .15s, border-color .15s',
              }}>
              <div style={{ padding: '12px 14px', borderBottom: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: 0.3 }}>{c.name}</div>
                  <div style={{ fontSize: 10, fontFamily: 'var(--mono)', padding: '1px 6px', background: 'var(--base)', borderRadius: 2, color: 'var(--text-dim)' }}>{colTasks.length}</div>
                </div>
                <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--mono)', letterSpacing: 0.5, marginTop: 2, textTransform: 'uppercase' }}>{c.desc}</div>
              </div>
              <div style={{ padding: 10, overflow: 'auto', flex: 1 }}>
                {colTasks.map((t) => (
                  <TaskCard key={t.id} task={t}
                    isDragging={drag?.id === t.id}
                    onPointerDown={(e) => startDrag(e, t)} />
                ))}
                {colTasks.length === 0 && <div style={{ textAlign: 'center', padding: 30, color: 'var(--text-faint)', fontSize: 10, fontFamily: 'var(--mono)', letterSpacing: 1 }}>—  EMPTY  —</div>}
              </div>
            </div>
          );
        })}
      </div>
      {/* dragging overlay */}
      {drag && dragTask && ReactDOM.createPortal(
        <div style={{
          position: 'fixed', top: drag.y - drag.oy, left: drag.x - drag.ox,
          width: drag.w, pointerEvents: 'none', zIndex: 9999, opacity: 0.95,
        }}>
          <TaskCard task={dragTask} isDragging />
        </div>,
        document.body
      )}
    </AppChrome>
  );
}

window.Artboard_Kanban = Artboard_Kanban;
