// Tarefas — Kanban com drag & drop, cronômetro, modal de criação

const COLS = [
  { key: 'novo',      label: 'Novo' },
  { key: 'analise',   label: 'Em análise' },
  { key: 'cliente',   label: 'Aguardando cliente' },
  { key: 'redacao',   label: 'Em redação' },
  { key: 'revisao',   label: 'Em revisão' },
  { key: 'externos',  label: 'Aguardando externos' },
  { key: 'concluido', label: 'Concluído' },
];

const COL_TO_DB = {
  novo: 'novo', analise: 'analise', cliente: 'cliente',
  redacao: 'redacao', revisao: 'revisao', externos: 'externos', concluido: 'concluido',
};
const DB_TO_COL = Object.fromEntries(Object.entries(COL_TO_DB).map(([k, v]) => [v, k]));

const fmtTime = (s) => {
  if (!s || s < 60) return s ? `${s}s` : '0min';
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  return h === 0 ? `${m}min` : `${h}h${String(m).padStart(2, '0')}`;
};

// Adapta tarefa da API → formato interno da UI
const adaptTask = (t, clientMap, userMap) => {
  const cl = clientMap[t.client_id] || {};
  const ow = userMap[t.owner_user_id] || {};
  return {
    ...t,
    col: DB_TO_COL[t.kanban_column] || 'novo',
    clientName: cl.short_name || cl.name || '—',
    clientColor: cl.color || '#ccc',
    ownerInitials: ow.initials || '?',
    ownerColor: ow.color || '#888',
    ownerName: ow.name || '—',
    due: t.due_date ? new Date(t.due_date).toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' }) : '—',
    priority: t.priority || 'Média',
  };
};

// ============================================================
// Cronômetro local (não persiste entre sessões — o real fica no banco)
// ============================================================
const useTaskTimers = () => {
  const [timers, setTimers] = React.useState({});
  const [, setTick] = React.useState(0);

  React.useEffect(() => {
    const anyRunning = Object.values(timers).some(t => t.running);
    if (!anyRunning) return;
    const i = setInterval(() => setTick(t => t + 1), 1000);
    return () => clearInterval(i);
  }, [timers]);

  const elapsed = (id) => {
    const t = timers[id];
    if (!t) return 0;
    return t.running ? t.elapsed + Math.floor((Date.now() - t.startedAt) / 1000) : t.elapsed;
  };
  const isRunning = (id) => !!timers[id]?.running;

  const toggle = (id) => {
    setTimers(prev => {
      const cur = prev[id] || { elapsed: 0, running: false };
      const next = { ...prev };
      // Parar qualquer outro que esteja rodando
      Object.keys(next).forEach(k => {
        if (next[k].running && k !== id) {
          next[k] = { elapsed: next[k].elapsed + Math.floor((Date.now() - next[k].startedAt) / 1000), running: false };
        }
      });
      if (cur.running) {
        next[id] = { elapsed: cur.elapsed + Math.floor((Date.now() - cur.startedAt) / 1000), running: false };
        window.PACApi?.tasks?.stopTimer(id).catch(() => {});
      } else {
        next[id] = { elapsed: cur.elapsed, running: true, startedAt: Date.now() };
        window.PACApi?.tasks?.startTimer(id).catch(() => {});
      }
      return next;
    });
  };

  return { elapsed, isRunning, toggle };
};

// ============================================================
// TaskTimer button
// ============================================================
const TaskTimer = ({ id, elapsed, running, onToggle }) => {
  const has = elapsed > 0;
  const cls = running ? 'timer running' : has ? 'timer' : 'timer idle';
  return (
    <button className={cls} onClick={(e) => { e.preventDefault(); e.stopPropagation(); onToggle(id); }}
      onMouseDown={(e) => e.stopPropagation()} draggable={false}
      title={running ? 'Pausar' : has ? 'Retomar' : 'Iniciar cronômetro'}>
      <span className="play-ic">
        {running ? <span className="live-dot" /> : <Icon name="play" size={9} />}
      </span>
      <span>{has || running ? fmtTime(elapsed) : 'Iniciar'}</span>
    </button>
  );
};

// ============================================================
// TaskCard
// ============================================================
// Ícone de mira — indica que o usuário logado é responsável ou revisor
const TargetIcon = () => (
  <svg width="13" height="13" viewBox="0 0 13 13" fill="none" xmlns="http://www.w3.org/2000/svg"
    style={{ position: 'absolute', top: 7, right: 7, color: 'var(--pac-navy)', opacity: 0.75 }}>
    <circle cx="6.5" cy="6.5" r="5.25" stroke="currentColor" strokeWidth="1.3"/>
    <circle cx="6.5" cy="6.5" r="2" fill="currentColor"/>
    <line x1="6.5" y1="1" x2="6.5" y2="3.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
    <line x1="6.5" y1="9.5" x2="6.5" y2="12" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
    <line x1="1" y1="6.5" x2="3.5" y2="6.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
    <line x1="9.5" y1="6.5" x2="12" y2="6.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
  </svg>
);

const TaskCard = ({ task, onDragStart, onDragEnd, dragging, layout, timer, currentUser, onCardClick }) => {
  const dueColor = (task.due === 'Hoje' || task.due === 'Amanhã') ? '#C2253E' : 'var(--fg-muted)';
  const tElapsed = timer.elapsed(task.id);
  const tRunning = timer.isRunning(task.id);
  const isMine = currentUser && (task.owner_user_id === currentUser.id || task.reviewer_user_id === currentUser.id);

  // Use mousedown/mouseup to detect clicks — draggable elements can swallow onClick in some browsers
  const _mousePos = React.useRef(null);
  const _dragged = React.useRef(false);

  const handleMouseDown = (e) => {
    if (e.button !== 0) return;
    _mousePos.current = { x: e.clientX, y: e.clientY };
    _dragged.current = false;
  };
  const handleDragStartInner = (e) => {
    _dragged.current = true;
    onDragStart(e, task);
  };
  const handleMouseUp = (e) => {
    if (e.button !== 0 || !_mousePos.current || _dragged.current) return;
    const dist = Math.hypot(e.clientX - _mousePos.current.x, e.clientY - _mousePos.current.y);
    _mousePos.current = null;
    if (dist < 8) onCardClick(task);
  };

  if (layout === 'rows') {
    return (
      <div className={`kb-card ${dragging ? 'dragging' : ''}`} draggable style={{ position: 'relative', cursor: 'pointer' }}
        onMouseDown={handleMouseDown} onMouseUp={handleMouseUp}
        onDragStart={handleDragStartInner} onDragEnd={onDragEnd}>
        {isMine && <TargetIcon />}
        <span className={`priority-bar ${task.priority}`} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingLeft: 8, flex: 1, minWidth: 0 }}>
          <span className={`dot ${task.priority}`} />
          <div className="ttl" style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{task.title}</div>
        </div>
        <div className="client-mark sm" style={{ background: task.clientColor }}>{(task.clientName || '?').slice(0,3)}</div>
        <div style={{ fontSize: 11, color: dueColor, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 4 }}>
          <Icon name="clock" size={12} /> {task.due}
        </div>
        <TaskTimer id={task.id} elapsed={tElapsed} running={tRunning} onToggle={timer.toggle} />
        <div className="av xs" style={{ background: task.ownerColor }} title={task.ownerName}>{task.ownerInitials}</div>
      </div>
    );
  }

  return (
    <div className={`kb-card ${dragging ? 'dragging' : ''}`} draggable style={{ position: 'relative', cursor: 'pointer' }}
      onMouseDown={handleMouseDown} onMouseUp={handleMouseUp}
      onDragStart={handleDragStartInner} onDragEnd={onDragEnd}>
      {isMine && <TargetIcon />}
      <span className={`priority-bar ${task.priority}`} />
      <div className="ttl" style={{ paddingRight: isMine ? 20 : 0 }}>{task.title}</div>
      {task.description && (
        <div style={{ fontSize: 11, color: 'var(--fg-muted)', lineHeight: 1.4, marginTop: 2 }}>
          {task.description.slice(0, 80)}{task.description.length > 80 ? '…' : ''}
        </div>
      )}
      <div className="meta-row" style={{ gap: 10 }}>
        <div className="client-mark sm" style={{ background: task.clientColor }}>
          {(task.clientName || '?').slice(0, 3).toUpperCase()}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <span style={{ fontSize: 11, color: 'var(--pac-navy)', fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'block' }}>
            {task.clientName}
          </span>
        </div>
        <TaskTimer id={task.id} elapsed={tElapsed} running={tRunning} onToggle={timer.toggle} />
      </div>
      <div className="meta-row bottom">
        <span style={{ fontSize: 11, color: dueColor, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          <Icon name="clock" size={11} /> {task.due}
        </span>
        <div className="av xs" style={{ background: task.ownerColor }} title={task.ownerName}>{task.ownerInitials}</div>
      </div>
    </div>
  );
};

// ============================================================
// TaskDetailDrawer
// ============================================================
const TaskDetailDrawer = ({ task, clients, cases, users, clientMap, userMap, onClose, onSaved, onDeleted }) => {
  const [form, setForm] = React.useState({
    title: task.title || '',
    description: task.description || '',
    priority: task.priority || 'Média',
    kanban_column: task.kanban_column || 'novo',
    client_id: task.client_id || '',
    case_id: task.case_id || '',
    owner_user_id: task.owner_user_id || '',
    reviewer_user_id: task.reviewer_user_id || '',
    due_date: task.due_date || '',
  });
  const [subtasks, setSubtasks] = React.useState([]);
  // Estado do formulário de nova subtarefa
  const [newSub, setNewSub] = React.useState({ title: '', due_date: '', owner_user_id: '' });
  const [addingSubtask, setAddingSubtask] = React.useState(false);
  const [saving, setSaving] = React.useState(false);
  const [dirty, setDirty] = React.useState(false);
  const [error, setError] = React.useState('');

  React.useEffect(() => {
    window.PACApi.tasks.get(task.id).then(t => {
      if (t?.subtasks) setSubtasks(t.subtasks);
    }).catch(() => {});
  }, [task.id]);

  const set = (k, v) => { setForm(f => ({ ...f, [k]: v })); setDirty(true); };

  const filteredCases = cases.filter(c => !form.client_id || c.client_id === form.client_id);

  const fmtDate = (d) => d ? new Date(d + 'T12:00:00').toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' }) : '';

  const onSave = async () => {
    if (!form.title.trim()) { setError('Título é obrigatório.'); return; }
    setSaving(true); setError('');
    try {
      const payload = {
        title: form.title.trim(),
        description: form.description || null,
        priority: form.priority,
        kanban_column: form.kanban_column,
        client_id: form.client_id || null,
        case_id: form.case_id || null,
        owner_user_id: form.owner_user_id || null,
        reviewer_user_id: form.reviewer_user_id || null,
        due_date: form.due_date || null,
      };
      const updated = await window.PACApi.tasks.update(task.id, payload);
      onSaved(updated);
      setDirty(false);
    } catch (e) {
      setError(e.message || 'Erro ao salvar.');
    } finally {
      setSaving(false);
    }
  };

  const onDelete = async () => {
    if (!confirm('Excluir esta tarefa permanentemente?')) return;
    try {
      await window.PACApi.tasks.delete(task.id);
      onDeleted(task.id);
    } catch (e) {
      setError(e.message || 'Erro ao excluir.');
    }
  };

  const confirmAddSubtask = async () => {
    if (!newSub.title.trim()) return;
    try {
      const sub = await window.PACApi.tasks.addSubtask(task.id, {
        title: newSub.title.trim(),
        due_date: newSub.due_date || null,
        owner_user_id: newSub.owner_user_id || null,
      });
      setSubtasks(prev => [...prev, sub]);
      setNewSub({ title: '', due_date: '', owner_user_id: '' });
      setAddingSubtask(false);
    } catch (e) {
      setError(e.message || 'Erro ao adicionar tarefa.');
    }
  };

  const toggleSubtask = async (subtaskId) => {
    try {
      const updated = await window.PACApi.tasks.toggleSubtask(subtaskId);
      setSubtasks(prev => prev.map(s => s.id === subtaskId ? updated : s));
    } catch {}
  };

  const removeSubtask = async (subtaskId) => {
    try {
      await window.PACApi.tasks.deleteSubtask(subtaskId);
      setSubtasks(prev => prev.filter(s => s.id !== subtaskId));
    } catch {}
  };

  const doneCount = subtasks.filter(s => s.done).length;
  const progress = subtasks.length > 0 ? Math.round((doneCount / subtasks.length) * 100) : 0;

  return ReactDOM.createPortal(
    <>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 298, background: 'rgba(0,0,0,.2)',
      }} />
      <div style={{
        position: 'fixed', top: 0, right: 0, height: '100vh', width: 520,
        background: '#fff', borderLeft: '1px solid #e2e2e8',
        boxShadow: '-8px 0 32px rgba(0,0,0,.15)', zIndex: 299,
        display: 'flex', flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{ padding: '16px 20px 12px', borderBottom: '1px solid #e2e2e8', display: 'flex', alignItems: 'flex-start', gap: 12 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <input
              value={form.title}
              onChange={e => set('title', e.target.value)}
              style={{
                width: '100%', border: 'none', outline: 'none', background: 'transparent',
                fontSize: 15, fontWeight: 700, color: '#1a1a2e', padding: 0, fontFamily: 'inherit',
              }}
              placeholder="Título da tarefa"
            />
            <div style={{ fontSize: 11, color: '#aaa', marginTop: 3 }}>
              {clientMap[form.client_id]?.name && <span>{clientMap[form.client_id].name} · </span>}
              {form.kanban_column && <span>{COLS.find(c => COL_TO_DB[c.key] === form.kanban_column)?.label || form.kanban_column}</span>}
            </div>
          </div>
          <button className="btn ghost sm icon" onClick={onClose}><Icon name="x" size={14} /></button>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px' }}>
          {error && (
            <div style={{ marginBottom: 12, padding: '8px 12px', background: 'rgba(194,37,62,.08)', border: '1px solid rgba(194,37,62,.2)', borderRadius: 6, color: '#C2253E', fontSize: 12 }}>
              {error}
            </div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
            <div className="field-w">
              <label>Coluna</label>
              <select value={form.kanban_column} onChange={e => set('kanban_column', e.target.value)}>
                {COLS.map(c => <option key={c.key} value={COL_TO_DB[c.key]}>{c.label}</option>)}
              </select>
            </div>
            <div className="field-w">
              <label>Prioridade</label>
              <select value={form.priority} onChange={e => set('priority', e.target.value)}>
                <option value="Alta">Alta</option>
                <option value="Média">Média</option>
                <option value="Baixa">Baixa</option>
              </select>
            </div>
            <div className="field-w">
              <label>Cliente</label>
              <select value={form.client_id} onChange={e => { set('client_id', e.target.value); set('case_id', ''); }}>
                <option value="">— Nenhum —</option>
                {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>
            <div className="field-w">
              <label>Caso</label>
              <select value={form.case_id} onChange={e => set('case_id', e.target.value)}>
                <option value="">— Nenhum —</option>
                {filteredCases.map(c => <option key={c.id} value={c.id}>{c.number} · {c.title}</option>)}
              </select>
            </div>
            <div className="field-w">
              <label>Responsável</label>
              <select value={form.owner_user_id} onChange={e => set('owner_user_id', e.target.value)}>
                <option value="">— Nenhum —</option>
                {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
              </select>
            </div>
            <div className="field-w">
              <label>Revisor</label>
              <select value={form.reviewer_user_id} onChange={e => set('reviewer_user_id', e.target.value)}>
                <option value="">— Nenhum —</option>
                {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
              </select>
            </div>
            <div className="field-w" style={{ gridColumn: '1 / -1' }}>
              <label>Prazo da tarefa principal</label>
              <input type="date" value={form.due_date} onChange={e => set('due_date', e.target.value)} />
            </div>
          </div>

          <div className="field-w" style={{ marginBottom: 20 }}>
            <label>Descrição</label>
            <textarea
              value={form.description}
              onChange={e => set('description', e.target.value)}
              placeholder="Adicione detalhes, contexto, links..."
              rows={3}
              style={{ resize: 'vertical', padding: '8px 10px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12, width: '100%', boxSizing: 'border-box', fontFamily: 'inherit', lineHeight: 1.5 }}
            />
          </div>

          {/* ── Tarefas do card ───────────────────────────────── */}
          <div style={{ borderTop: '1px solid #eeeef5', paddingTop: 16 }}>
            {/* Cabeçalho da seção */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
              <span style={{ fontWeight: 700, fontSize: 13, color: '#1a1a2e' }}>
                Tarefas do card
              </span>
              {subtasks.length > 0 && (
                <span style={{ fontSize: 11, color: '#999', background: '#f0f0f8', borderRadius: 99, padding: '1px 7px' }}>
                  {subtasks.length}
                </span>
              )}
              {subtasks.length > 0 && (
                <>
                  <div style={{ flex: 1, height: 4, background: '#eeeef5', borderRadius: 4, overflow: 'hidden', margin: '0 4px' }}>
                    <div style={{ height: '100%', width: `${progress}%`, background: progress === 100 ? '#22c55e' : 'var(--pac-navy)', borderRadius: 4, transition: 'width .25s' }} />
                  </div>
                  <span style={{ fontSize: 11, color: '#888', whiteSpace: 'nowrap' }}>{doneCount}/{subtasks.length} concluídas</span>
                </>
              )}
            </div>

            {/* Lista de subtarefas */}
            {subtasks.map(sub => {
              const owner = userMap[sub.owner_user_id] || null;
              return (
                <div key={sub.id} style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '8px 10px', marginBottom: 4,
                  background: sub.done ? '#f9f9fc' : '#fff',
                  border: '1px solid #eeeef5', borderRadius: 6,
                  opacity: sub.done ? 0.6 : 1,
                }}>
                  {/* Checkbox */}
                  <button onClick={() => toggleSubtask(sub.id)} style={{
                    width: 20, height: 20, borderRadius: 99, flexShrink: 0,
                    border: `1.5px solid ${sub.done ? 'var(--pac-navy)' : '#c8c8d8'}`,
                    background: sub.done ? 'var(--pac-navy)' : '#fff',
                    cursor: 'pointer', display: 'grid', placeItems: 'center', padding: 0,
                  }}>
                    {sub.done && <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                  </button>

                  {/* Título */}
                  <span style={{ fontSize: 12.5, flex: 1, color: '#1a1a2e', textDecoration: sub.done ? 'line-through' : 'none', lineHeight: 1.4 }}>
                    {sub.title}
                  </span>

                  {/* Data */}
                  {sub.due_date && (
                    <span style={{ fontSize: 11, color: '#C2253E', fontWeight: 600, whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 3 }}>
                      <Icon name="clock" size={10} /> {fmtDate(sub.due_date)}
                    </span>
                  )}

                  {/* Avatar responsável */}
                  {owner && (
                    <div className="av xs" style={{ background: owner.color || '#888', width: 22, height: 22, fontSize: 9, flexShrink: 0 }} title={owner.name}>
                      {owner.initials}
                    </div>
                  )}

                  {/* Excluir */}
                  <button onClick={() => removeSubtask(sub.id)} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#ccc', padding: 2, flexShrink: 0, lineHeight: 0 }}>
                    <Icon name="x" size={12} />
                  </button>
                </div>
              );
            })}

            {/* Formulário de nova subtarefa */}
            {addingSubtask ? (
              <div style={{ border: '1px solid var(--pac-navy)', borderRadius: 6, padding: '10px 12px', background: '#f8f8ff', marginTop: 4 }}>
                <input
                  autoFocus
                  value={newSub.title}
                  onChange={e => setNewSub(s => ({ ...s, title: e.target.value }))}
                  onKeyDown={e => { if (e.key === 'Enter') confirmAddSubtask(); if (e.key === 'Escape') setAddingSubtask(false); }}
                  placeholder="Título da tarefa…"
                  style={{ width: '100%', border: 'none', outline: 'none', background: 'transparent', fontSize: 13, color: '#1a1a2e', fontFamily: 'inherit', marginBottom: 8 }}
                />
                <div style={{ display: 'flex', gap: 8 }}>
                  <input
                    type="date"
                    value={newSub.due_date}
                    onChange={e => setNewSub(s => ({ ...s, due_date: e.target.value }))}
                    style={{ flex: 1, padding: '5px 8px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12, outline: 'none', color: '#1a1a2e', background: '#fff' }}
                  />
                  <select
                    value={newSub.owner_user_id}
                    onChange={e => setNewSub(s => ({ ...s, owner_user_id: e.target.value }))}
                    style={{ flex: 1, padding: '5px 8px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12, outline: 'none', color: '#1a1a2e', background: '#fff' }}
                  >
                    <option value="">Responsável…</option>
                    {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                  </select>
                </div>
                <div style={{ display: 'flex', gap: 6, marginTop: 8, justifyContent: 'flex-end' }}>
                  <button className="btn ghost sm" onClick={() => { setAddingSubtask(false); setNewSub({ title: '', due_date: '', owner_user_id: '' }); }}>Cancelar</button>
                  <button className="btn sm" onClick={confirmAddSubtask} disabled={!newSub.title.trim()}>Adicionar</button>
                </div>
              </div>
            ) : (
              <button
                onClick={() => setAddingSubtask(true)}
                style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '7px 10px', marginTop: 4, border: '1px dashed #d0d0e0', borderRadius: 6, background: 'transparent', cursor: 'pointer', color: '#888', fontSize: 12, width: '100%' }}
              >
                <Icon name="plus" size={12} /> Adicionar tarefa
              </button>
            )}
          </div>
        </div>

        {/* Footer */}
        <div style={{ padding: '12px 20px', borderTop: '1px solid #e2e2e8', display: 'flex', gap: 8, background: '#fafafa', flexShrink: 0 }}>
          <button className="btn ghost sm" style={{ color: '#C2253E' }} onClick={onDelete}>
            <Icon name="trash" size={12} /> Excluir
          </button>
          <div style={{ flex: 1 }} />
          <button className="btn ghost sm" onClick={onClose}>Cancelar</button>
          <button className="btn sm" onClick={onSave} disabled={saving || !dirty}>
            {saving ? <><span className="spinner" style={{ width: 12, height: 12, borderWidth: 2, marginRight: 6 }} />Salvando…</> : 'Salvar'}
          </button>
        </div>
      </div>
    </>,
    document.body
  );
};

// ============================================================
// Modal de nova tarefa
// ============================================================
const NewTaskModal = ({ onClose, onCreated, clients, cases, users, prefillTitle = '', defaultColumn = 'novo' }) => {
  const [form, setForm] = React.useState({
    title: prefillTitle, description: '', priority: 'Média',
    client_id: '', case_id: '', owner_user_id: '', reviewer_user_id: '', due_date: '',
    kanban_column: defaultColumn,
  });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const filteredCases = cases.filter(c => !form.client_id || c.client_id === form.client_id);

  const onSave = async () => {
    if (!form.title.trim()) { setError('Título é obrigatório.'); return; }
    setSaving(true); setError('');
    try {
      const payload = {
        title: form.title.trim(),
        description: form.description || undefined,
        priority: form.priority,
        kanban_column: form.kanban_column,
        client_id: form.client_id || undefined,
        case_id: form.case_id || undefined,
        owner_user_id: form.owner_user_id || undefined,
        reviewer_user_id: form.reviewer_user_id || undefined,
        due_date: form.due_date || undefined,
      };
      const created = await window.PACApi.tasks.create(payload);
      onCreated(created);
      onClose();
    } catch (e) {
      setError(e.message || 'Erro ao criar tarefa.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <div style={{ width: 32, height: 32, borderRadius: 4, background: 'var(--pac-navy)', color: '#fff', display: 'grid', placeItems: 'center' }}>
            <Icon name="kanban" size={16} />
          </div>
          <div><h2>Nova tarefa</h2></div>
          <button className="x" onClick={onClose}><Icon name="x" size={16} /></button>
        </div>
        <div className="modal-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {error && (
            <div style={{ gridColumn: '1 / -1', padding: '8px 12px', background: 'rgba(194,37,62,.08)', border: '1px solid rgba(194,37,62,.2)', borderRadius: 6, color: '#C2253E', fontSize: 12 }}>
              {error}
            </div>
          )}

          <div className="field-w" style={{ gridColumn: '1 / -1' }}>
            <label>Título *</label>
            <input autoFocus value={form.title} onChange={e => set('title', e.target.value)}
              placeholder="Ex: Revisar cláusula 8.4 do SPA" />
          </div>

          <div className="field-w">
            <label>Coluna inicial</label>
            <select value={form.kanban_column} onChange={e => set('kanban_column', e.target.value)}>
              {COLS.map(c => <option key={c.key} value={COL_TO_DB[c.key]}>{c.label}</option>)}
            </select>
          </div>
          <div className="field-w">
            <label>Prioridade</label>
            <select value={form.priority} onChange={e => set('priority', e.target.value)}>
              <option value="Alta">Alta</option>
              <option value="Média">Média</option>
              <option value="Baixa">Baixa</option>
            </select>
          </div>

          <div className="field-w">
            <label>Cliente</label>
            <select value={form.client_id} onChange={e => { set('client_id', e.target.value); set('case_id', ''); }}>
              <option value="">— Nenhum —</option>
              {clients.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          <div className="field-w">
            <label>Caso</label>
            <select value={form.case_id} onChange={e => set('case_id', e.target.value)}>
              <option value="">— Nenhum —</option>
              {filteredCases.map(c => <option key={c.id} value={c.id}>{c.number} · {c.title}</option>)}
            </select>
          </div>

          <div className="field-w">
            <label>Responsável pela execução</label>
            <select value={form.owner_user_id} onChange={e => set('owner_user_id', e.target.value)}>
              <option value="">— Nenhum —</option>
              {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
            </select>
          </div>
          <div className="field-w">
            <label>Revisor <span style={{ color: 'var(--fg-muted)', fontWeight: 400 }}>(opcional)</span></label>
            <select value={form.reviewer_user_id} onChange={e => set('reviewer_user_id', e.target.value)}>
              <option value="">— Mesmo que execução —</option>
              {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
            </select>
          </div>

          <div className="field-w">
            <label>Prazo</label>
            <input type="date" value={form.due_date} onChange={e => set('due_date', e.target.value)} />
          </div>
          <div />

          <div className="field-w" style={{ gridColumn: '1 / -1' }}>
            <label>Descrição</label>
            <textarea value={form.description} onChange={e => set('description', e.target.value)}
              placeholder="Detalhes da tarefa..." rows={3}
              style={{ resize: 'vertical', padding: '8px 10px', border: '1px solid var(--border)', borderRadius: 4, fontSize: 12, width: '100%', boxSizing: 'border-box', fontFamily: 'inherit' }} />
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn ghost sm" onClick={onClose}>Cancelar</button>
          <button className="btn sm" onClick={onSave} disabled={saving}>
            {saving ? <><span className="spinner" style={{ width: 12, height: 12, borderWidth: 2, marginRight: 6 }} />Salvando…</> : 'Criar tarefa'}
          </button>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Tasks — view principal
// ============================================================
const Tasks = ({ layout = 'cards', currentUser }) => {
  const [tasks, setTasks] = React.useState([]);
  const [clients, setClients] = React.useState([]);
  const [cases, setCases] = React.useState([]);
  const [users, setUsers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [showNew, setShowNew] = React.useState(false);
  const [dragId, setDragId] = React.useState(null);
  const [dragOver, setDragOver] = React.useState(null);
  const [newInCol, setNewInCol] = React.useState(null); // coluna de atalho no "+"
  const [openTask, setOpenTask] = React.useState(null);
  const timer = useTaskTimers();

  const clientMap = React.useMemo(() => Object.fromEntries(clients.map(c => [c.id, c])), [clients]);
  const userMap   = React.useMemo(() => Object.fromEntries(users.map(u => [u.id, u])), [users]);

  const [loadError, setLoadError] = React.useState('');

  const loadAll = async () => {
    setLoadError('');
    try {
      const [apiTasks, apiClients, apiCases, apiUsers] = await Promise.all([
        window.PACApi.tasks.list().catch(() => null),
        window.PACApi.clients.list().catch(() => []),
        window.PACApi.cases.list().catch(() => []),
        window.PACApi.users.list().catch(() => []),
      ]);

      if (apiTasks === null) {
        setLoadError('Não foi possível carregar as tarefas. Verifique sua conexão.');
        return;
      }

      const cl = apiClients || [];
      const us = apiUsers || [];
      setClients(cl);
      setCases(apiCases || []);
      setUsers(us);

      const cMap = Object.fromEntries(cl.map(c => [c.id, c]));
      const uMap = Object.fromEntries(us.map(u => [u.id, u]));
      setTasks((apiTasks || []).map(t => adaptTask(t, cMap, uMap)));
    } catch (e) {
      setLoadError(e.message || 'Erro ao carregar tarefas.');
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => { loadAll(); }, []);

  const byCol = React.useMemo(() => {
    const m = {};
    COLS.forEach(c => m[c.key] = []);
    tasks.forEach(t => { const col = t.col || 'novo'; (m[col] = m[col] || []).push(t); });
    return m;
  }, [tasks]);

  const onDragStart = (e, task) => {
    setDragId(task.id);
    e.dataTransfer.effectAllowed = 'move';
    try { e.dataTransfer.setData('text/plain', task.id); } catch {}
  };
  const onDragEnd = () => { setDragId(null); setDragOver(null); };
  const onColDragOver = (e, colKey) => {
    e.preventDefault(); e.dataTransfer.dropEffect = 'move';
    if (dragOver !== colKey) setDragOver(colKey);
  };
  const onColDrop = (e, colKey) => {
    e.preventDefault();
    if (dragId) {
      setTasks(prev => prev.map(t => t.id === dragId ? { ...t, col: colKey } : t));
      window.PACApi.tasks.moveColumn(dragId, COL_TO_DB[colKey] || colKey).catch(() => {});
    }
    setDragId(null); setDragOver(null);
  };

  const onTaskCreated = (raw) => {
    const adapted = adaptTask(raw, clientMap, userMap);
    setTasks(prev => [adapted, ...prev]);
  };

  const onCardClick = (task) => setOpenTask(task);

  const onTaskSaved = (raw) => {
    const adapted = adaptTask(raw, clientMap, userMap);
    setTasks(prev => prev.map(t => t.id === raw.id ? adapted : t));
    setOpenTask(adapted);
  };

  const onTaskDeleted = (id) => {
    setTasks(prev => prev.filter(t => t.id !== id));
    setOpenTask(null);
  };

  const handleNewInCol = (colKey) => {
    setNewInCol(colKey);
    setShowNew(true);
  };

  // ── To-do panel ──────────────────────────────────────────
  const [showTodo, setShowTodo] = React.useState(false);
  const [todos, setTodos] = React.useState([]);
  const [todoInput, setTodoInput] = React.useState('');
  const [todosLoaded, setTodosLoaded] = React.useState(false);

  const openTodo = async () => {
    setShowTodo(true);
    if (todosLoaded) return;
    try { setTodos(await window.PACApi.todos.list()); setTodosLoaded(true); } catch {}
  };

  const addTodo = async () => {
    const t = todoInput.trim();
    if (!t) return;
    setTodoInput('');
    try { const todo = await window.PACApi.todos.create(t); setTodos(prev => [...prev, todo]); } catch {}
  };

  const toggleTodo = async (id, done) => {
    try { const updated = await window.PACApi.todos.update(id, { done: !done }); setTodos(prev => prev.map(t => t.id === id ? updated : t)); } catch {}
  };

  const removeTodo = async (id) => {
    try { await window.PACApi.todos.remove(id); setTodos(prev => prev.filter(t => t.id !== id)); } catch {}
  };

  const promoteToTask = (todo) => {
    setNewInCol('novo');
    setShowNew(true);
    // pré-preencher título no modal via ref não é trivial com função pura;
    // usamos um estado temporário
    setPrefillTitle(todo.title);
  };

  const [prefillTitle, setPrefillTitle] = React.useState('');
  // ─────────────────────────────────────────────────────────

  const totalTracked = tasks.reduce((sum, t) => sum + timer.elapsed(t.id), 0);
  const runningCount = tasks.filter(t => timer.isRunning(t.id)).length;

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 300, gap: 12, color: 'var(--fg-muted)', fontSize: 13 }}>
      <div className="spinner" /> Carregando tarefas…
    </div>
  );

  if (loadError) return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: 300, gap: 12 }}>
      <div style={{ color: '#C2253E', fontSize: 13, fontWeight: 600 }}>{loadError}</div>
      <button className="btn sm" onClick={() => { setLoading(true); loadAll(); }}>Tentar novamente</button>
    </div>
  );

  // Painel To-do como componente reutilizável (usado aqui e no Dashboard)
  const TodoPanel = showTodo ? (
    <>
      {/* Scrim clicável para fechar */}
      <div onClick={() => setShowTodo(false)} style={{
        position: 'fixed', inset: 0, zIndex: 199, background: 'rgba(0,0,0,.18)',
      }} />
      <div style={{
        position: 'fixed', top: 0, right: 0, height: '100vh', width: 320,
        background: '#ffffff', borderLeft: '1px solid #e2e2e8',
        boxShadow: '-8px 0 32px rgba(0,0,0,.15)', zIndex: 200,
        display: 'flex', flexDirection: 'column',
      }}>
          <div style={{ padding: '18px 20px 14px', borderBottom: '1px solid #e2e2e8', display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 800, fontSize: 14, color: '#1a1a2e' }}>Meu To-do</div>
              <div style={{ fontSize: 11, color: '#888', marginTop: 2 }}>Visível somente para você</div>
            </div>
            <button className="btn ghost sm icon" onClick={() => setShowTodo(false)}><Icon name="x" size={14} /></button>
          </div>

          {/* Input novo to-do */}
          <div style={{ padding: '12px 16px', borderBottom: '1px solid #e2e2e8', display: 'flex', gap: 8 }}>
            <input
              value={todoInput} onChange={e => setTodoInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addTodo()}
              placeholder="Adicionar item…"
              style={{ flex: 1, padding: '7px 10px', border: '1px solid #d0d0dc', borderRadius: 5, fontSize: 12.5, outline: 'none', background: '#f5f5f8', color: '#1a1a2e' }}
              autoFocus
            />
            <button className="btn sm" onClick={addTodo} disabled={!todoInput.trim()} style={{ flexShrink: 0 }}>
              <Icon name="plus" size={12} />
            </button>
          </div>

          {/* Lista */}
          <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0', background: '#ffffff' }}>
            {todos.length === 0 && (
              <div style={{ padding: '32px 20px', textAlign: 'center', color: '#888', fontSize: 12 }}>
                Nenhum item. Adicione acima.
              </div>
            )}
            {todos.filter(t => !t.done).concat(todos.filter(t => t.done)).map(todo => (
              <div key={todo.id} style={{
                display: 'flex', alignItems: 'flex-start', gap: 10, padding: '8px 16px',
                opacity: todo.done ? 0.45 : 1,
              }}>
                <button onClick={() => toggleTodo(todo.id, todo.done)} style={{
                  width: 18, height: 18, borderRadius: 4,
                  border: `1.5px solid ${todo.done ? '#0D0D6B' : '#c0c0cc'}`,
                  background: todo.done ? '#0D0D6B' : '#ffffff',
                  cursor: 'pointer', flexShrink: 0, marginTop: 1,
                  display: 'grid', placeItems: 'center',
                }}>
                  {todo.done && <svg width="10" height="8" viewBox="0 0 10 8" fill="none"><path d="M1 4l3 3 5-6" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                </button>
                <span style={{ flex: 1, fontSize: 12.5, color: '#1a1a2e', textDecoration: todo.done ? 'line-through' : 'none', lineHeight: 1.4 }}>
                  {todo.title}
                </span>
                <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
                  {!todo.done && (
                    <button onClick={() => promoteToTask(todo)} title="Converter em tarefa Kanban"
                      style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#0D0D6B', padding: 2 }}>
                      <Icon name="kanban" size={13} />
                    </button>
                  )}
                  <button onClick={() => removeTodo(todo.id)}
                    style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#999', padding: 2 }}>
                    <Icon name="x" size={12} />
                  </button>
                </div>
              </div>
            ))}
          </div>

          <div style={{ padding: '12px 16px', borderTop: '1px solid #e2e2e8', fontSize: 11, color: '#888', background: '#ffffff' }}>
            {todos.filter(t => t.done).length} de {todos.length} concluído{todos.length !== 1 ? 's' : ''}
            {' · '}Clique em <Icon name="kanban" size={10} style={{ display: 'inline', verticalAlign: 'middle' }} /> para criar tarefa no Kanban
          </div>
        </div>
      </>
  ) : null;

  return (
    <>
      {TodoPanel}
      <div className={`kb ${layout === 'rows' ? 'rows' : ''}`}>
      <div className="kb-head">
        <h1>Tarefas</h1>
        <span className="count">{tasks.length} ativas</span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginLeft: 18 }}>
          <button className="chip soft" style={{ cursor: 'pointer' }}><Icon name="filter" size={11} /> Todas</button>
          <button className="chip soft" style={{ cursor: 'pointer' }}>Minhas</button>
          <button className="chip soft" style={{ cursor: 'pointer' }}>Urgentes</button>
        </div>
        <div className="kb-filter">
          <span style={{ fontSize: 11, color: 'var(--fg-muted)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <Icon name="clock" size={12} style={{ color: 'var(--pac-navy)' }} />
            <b style={{ color: 'var(--pac-navy)' }}>{fmtTime(totalTracked)}</b> hoje
            {runningCount > 0 && (
              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginLeft: 8, color: 'var(--pac-dark-purple)', fontWeight: 700 }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: 'var(--pac-neon)', boxShadow: '0 0 6px var(--pac-neon)' }} />
                {runningCount} cronômetro{runningCount > 1 ? 's' : ''} ativo{runningCount > 1 ? 's' : ''}
              </span>
            )}
          </span>
          <button className="btn ghost sm" onClick={openTodo} style={{ gap: 5 }}>
            <Icon name="checkSquare" size={12} /> To-do
            {todos.filter(t => !t.done).length > 0 && (
              <span style={{ background: 'var(--pac-navy)', color: '#fff', borderRadius: 999, fontSize: 10, padding: '0 5px', fontWeight: 700 }}>
                {todos.filter(t => !t.done).length}
              </span>
            )}
          </button>
          <button className="btn ghost sm"><Icon name="sliders" size={12} /> Filtros</button>
          <button className="btn sm" onClick={() => setShowNew(true)}><Icon name="plus" size={12} /> Nova tarefa</button>
        </div>
      </div>

      <div className="kb-board">
        {COLS.map(col => {
          const items = byCol[col.key] || [];
          const isOver = dragOver === col.key;
          return (
            <div key={col.key} className={`kb-col ${isOver ? 'drag-over' : ''}`}
              onDragOver={(e) => onColDragOver(e, col.key)}
              onDragLeave={() => setDragOver(o => o === col.key ? null : o)}
              onDrop={(e) => onColDrop(e, col.key)}>
              <div className="kb-col-head">
                <span className="swatch" style={{
                  background: col.key === 'concluido' ? 'var(--pac-neon)' :
                               col.key === 'externos' ? '#D49A1A' :
                               col.key === 'cliente' ? '#C2253E' : 'var(--pac-navy)',
                  opacity: 0.6
                }} />
                <span className="lbl">{col.label}</span>
                <span className="num">{items.length}</span>
                <Icon name="plus" size={13}
                  style={{ marginLeft: 'auto', color: 'var(--fg-muted)', cursor: 'pointer' }}
                  onClick={() => handleNewInCol(col.key)}
                />
              </div>
              <div className="kb-col-list">
                {items.map(t => (
                  <TaskCard key={t.id} task={t} dragging={dragId === t.id}
                    onDragStart={onDragStart} onDragEnd={onDragEnd}
                    layout={layout} timer={timer} currentUser={currentUser}
                    onCardClick={onCardClick} />
                ))}
                {items.length === 0 && (
                  <div style={{ padding: '20px 8px', textAlign: 'center', color: 'rgba(13,13,107,.35)', fontSize: 11.5, border: '1px dashed var(--border)', borderRadius: 4, margin: 4 }}>
                    Arraste tarefas para esta coluna
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      <button className="fab" onClick={() => setShowNew(true)}><Icon name="plus" size={16} /> Nova tarefa</button>

      {showNew && (
        <NewTaskModal
          onClose={() => { setShowNew(false); setNewInCol(null); setPrefillTitle(''); }}
          onCreated={onTaskCreated}
          prefillTitle={prefillTitle}
          defaultColumn={newInCol || 'novo'}
          clients={clients}
          cases={cases}
          users={users}
        />
      )}

      {openTask && (
        <TaskDetailDrawer
          task={openTask}
          clients={clients}
          cases={cases}
          users={users}
          clientMap={clientMap}
          userMap={userMap}
          onClose={() => setOpenTask(null)}
          onSaved={onTaskSaved}
          onDeleted={onTaskDeleted}
        />
      )}
      </div>
    </>
  );
};

window.Tasks = Tasks;
window.TaskDetailDrawer = TaskDetailDrawer;
