/* global React, Card, Badge, Button, Avatar, Icon, ICONS, Field, sb */
const { useState, useEffect } = React;

const COLS = [
  { id: 'todo',   lab: 'A fazer',      tone: '#597EF7' },
  { id: 'doing',  lab: 'Em andamento', tone: '#FADB14' },
  { id: 'review', lab: 'Em revisão',   tone: '#FA541C' },
  { id: 'done',   lab: 'Concluído',    tone: '#22C55E' },
];

function rowToTask(row) {
  return {
    id:       row.id,
    t:        row.title,
    proj:     row.project_name || '—',
    tg:       row.tag_label    || 'TASK',
    tc:       row.tag_color    || '#36CFC9',
    col:      row.kanban_col   || 'todo',
    pri:      row.priority     || 'média',
    due:      row.due_date     ? row.due_date.slice(5).split('-').reverse().join('/') : '—',
    who:      row.assignee     || '—',
    desc:     row.description  || '',
    subtasks: Array.isArray(row.subtasks_data) ? row.subtasks_data : (row.subtasks_data ? JSON.parse(row.subtasks_data) : []),
    done:     row.done || false,
  };
}

function PriorityDot({ p }) {
  const c = p === 'alta' ? '#EF4444' : p === 'média' ? '#FADB14' : '#7A859A';
  return <span title={'Prioridade ' + p} style={{ width: 6, height: 6, borderRadius: '50%', background: c, flexShrink: 0 }}/>;
}

function TaskDetailModal({ task, onClose, onMove, onUpdate, onDelete }) {
  const [editingTitle, setEditingTitle] = useState(false);
  const [titleDraft,   setTitleDraft]   = useState(task.t);
  const [newSub,       setNewSub]       = useState('');
  const [confirmDel,   setConfirmDel]   = useState(false);

  const subtasks = task.subtasks || [];
  const doneSubs = subtasks.filter(s => s.done).length;
  const pct      = subtasks.length ? Math.round((doneSubs / subtasks.length) * 100) : 0;

  const labelStyle = { fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8, display: 'block' };
  const inputStyle = { width: '100%', background: 'var(--bg-elevated)', border: '1px solid var(--border-subtle)', borderRadius: 8, padding: '8px 10px', color: 'var(--fg-primary)', fontSize: 13, fontFamily: 'inherit', outline: 'none', boxSizing: 'border-box' };

  function saveTitle() {
    if (titleDraft.trim()) onUpdate(task.id, { t: titleDraft.trim() });
    setEditingTitle(false);
  }
  function addSub() {
    if (!newSub.trim()) return;
    onUpdate(task.id, { subtasks: [...subtasks, { id: Date.now(), text: newSub.trim(), done: false }] });
    setNewSub('');
  }
  function toggleSub(subId) { onUpdate(task.id, { subtasks: subtasks.map(s => s.id === subId ? { ...s, done: !s.done } : s) }); }
  function deleteSub(subId) { onUpdate(task.id, { subtasks: subtasks.filter(s => s.id !== subId) }); }

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(8,12,28,0.55)', backdropFilter: 'blur(4px)', zIndex: 200, display: 'flex', alignItems: 'stretch', justifyContent: 'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 440, display: 'flex', flexDirection: 'column', background: 'var(--bg-surface)', borderLeft: '1px solid var(--border-subtle)', boxShadow: '-20px 0 60px rgba(0,0,0,0.4)' }}>
        <div style={{ padding: '18px 22px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
          <div style={{ flex: 1 }}>
            <span style={{ display: 'inline-block', fontFamily: 'var(--font-display)', fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', padding: '2px 8px', borderRadius: 4, background: task.tc + '24', color: task.tc }}>{task.tg}</span>
            {editingTitle ? (
              <input autoFocus value={titleDraft} onChange={e => setTitleDraft(e.target.value)} onBlur={saveTitle} onKeyDown={e => { if (e.key === 'Enter') saveTitle(); if (e.key === 'Escape') { setTitleDraft(task.t); setEditingTitle(false); }}} style={{ ...inputStyle, marginTop: 8, fontSize: 16, fontWeight: 700, padding: '6px 8px' }}/>
            ) : (
              <h2 onClick={() => setEditingTitle(true)} title="Clique para editar" style={{ margin: '8px 0 0', fontSize: 16, fontWeight: 700, lineHeight: 1.3, cursor: 'text', borderRadius: 6, padding: '2px 4px', marginLeft: -4 }} onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-elevated)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>{task.t}</h2>
            )}
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 4, marginTop: 2 }}><Icon d={ICONS.x} size={18}/></button>
        </div>
        <div style={{ flex: 1, overflow: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 22 }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
            <div><span style={labelStyle}>Projeto</span><div style={{ fontSize: 13, color: 'var(--fg-secondary)' }}>{task.proj}</div></div>
            <div>
              <span style={labelStyle}>Responsável</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Avatar name={task.who} size={22} idx={0}/>
                <input defaultValue={task.who} onBlur={e => onUpdate(task.id, { who: e.target.value })} style={{ ...inputStyle, padding: '3px 6px', fontSize: 12 }}/>
              </div>
            </div>
            <div>
              <span style={labelStyle}>Prioridade</span>
              <div style={{ display: 'flex', gap: 6 }}>
                {[['alta','#EF4444'],['média','#FADB14'],['baixa','#7A859A']].map(([p, c]) => (
                  <button key={p} onClick={() => onUpdate(task.id, { pri: p })} style={{ padding: '5px 10px', borderRadius: 6, fontSize: 11, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', background: task.pri === p ? c + '22' : 'var(--bg-elevated)', color: task.pri === p ? c : 'var(--fg-muted)', border: `1px solid ${task.pri === p ? c + '66' : 'var(--border-subtle)'}` }}>{p.charAt(0).toUpperCase() + p.slice(1)}</button>
                ))}
              </div>
            </div>
            <div>
              <span style={labelStyle}>Vencimento</span>
              <input defaultValue={task.due} placeholder="dd/mm" onBlur={e => onUpdate(task.id, { due: e.target.value })} style={{ ...inputStyle, padding: '5px 8px', fontSize: 12, fontFamily: 'var(--font-mono)', width: 90 }}/>
            </div>
          </div>
          <div>
            <span style={labelStyle}>Status</span>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {COLS.map(c => (
                <button key={c.id} onClick={() => onMove(task.id, c.id)} style={{ padding: '6px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', background: task.col === c.id ? c.tone + '22' : 'var(--bg-elevated)', color: task.col === c.id ? c.tone : 'var(--fg-secondary)', border: `1px solid ${task.col === c.id ? c.tone + '66' : 'var(--border-subtle)'}` }}>{c.lab}</button>
              ))}
            </div>
          </div>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
              <span style={{ ...labelStyle, marginBottom: 0 }}>Subtarefas</span>
              {subtasks.length > 0 && <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>{doneSubs}/{subtasks.length}</span>}
            </div>
            {subtasks.length > 0 && <div style={{ height: 4, background: 'var(--bg-elevated)', borderRadius: 999, overflow: 'hidden', marginBottom: 12 }}><div style={{ width: pct + '%', height: '100%', background: pct === 100 ? '#22C55E' : 'var(--primary)', borderRadius: 999, transition: 'width 200ms' }}/></div>}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {subtasks.map(s => (
                <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '7px 10px', borderRadius: 8, background: 'var(--bg-elevated)' }} onMouseEnter={e => e.currentTarget.querySelector('.sub-del').style.opacity = '1'} onMouseLeave={e => e.currentTarget.querySelector('.sub-del').style.opacity = '0'}>
                  <button onClick={() => toggleSub(s.id)} style={{ width: 18, height: 18, borderRadius: 5, flexShrink: 0, cursor: 'pointer', padding: 0, background: s.done ? '#22C55E' : 'transparent', border: `1.5px solid ${s.done ? '#22C55E' : 'var(--border-strong)'}`, display: 'grid', placeItems: 'center' }}>
                    {s.done && <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M2 5l2.5 2.5 4-4" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                  </button>
                  <span style={{ flex: 1, fontSize: 13, color: s.done ? 'var(--fg-muted)' : 'var(--fg-primary)', textDecoration: s.done ? 'line-through' : 'none' }}>{s.text}</span>
                  <button className="sub-del" onClick={() => deleteSub(s.id)} style={{ background: 'transparent', border: 'none', color: 'var(--fg-muted)', cursor: 'pointer', padding: 2, opacity: 0, transition: 'opacity 120ms', lineHeight: 1 }}><Icon d={ICONS.x} size={13}/></button>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: subtasks.length ? 8 : 0 }}>
              <input value={newSub} onChange={e => setNewSub(e.target.value)} onKeyDown={e => e.key === 'Enter' && addSub()} placeholder="Nova subtarefa…" style={{ ...inputStyle, flex: 1 }}/>
              <button onClick={addSub} style={{ background: 'var(--primary)', border: 'none', borderRadius: 8, padding: '0 14px', color: '#fff', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600, flexShrink: 0 }}>Adicionar</button>
            </div>
          </div>
          <div>
            <span style={labelStyle}>Descrição</span>
            <textarea defaultValue={task.desc || ''} onBlur={e => onUpdate(task.id, { desc: e.target.value })} placeholder="Adicione uma descrição…" rows={3} style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.5 }}/>
          </div>
        </div>
        <div style={{ padding: '12px 22px', borderTop: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          {confirmDel ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 12, color: 'var(--fg-secondary)' }}>Apagar esta tarefa?</span>
              <button onClick={() => onDelete(task.id)} style={{ padding: '6px 12px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, background: '#EF4444', color: '#fff' }}>Apagar</button>
              <button onClick={() => setConfirmDel(false)} style={{ padding: '6px 12px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, background: 'var(--bg-elevated)', color: 'var(--fg-secondary)' }}>Cancelar</button>
            </div>
          ) : (
            <button onClick={() => setConfirmDel(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 10px', borderRadius: 7, border: '1px solid transparent', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 500, background: 'transparent', color: 'var(--fg-muted)', transition: 'all 140ms' }} onMouseEnter={e => { e.currentTarget.style.background = '#EF444420'; e.currentTarget.style.color = '#EF4444'; e.currentTarget.style.borderColor = '#EF444440'; }} onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--fg-muted)'; e.currentTarget.style.borderColor = 'transparent'; }}>
              <Icon d={ICONS.trash} size={13}/>Apagar tarefa
            </button>
          )}
          <Button variant="secondary" onClick={onClose}>Fechar</Button>
        </div>
      </div>
    </div>
  );
}

function TaskCard({ t, dragging, onDragStart, onDragEnd, onClick }) {
  return (
    <div draggable={true} onDragStart={e => { e.dataTransfer.setData('text/plain', String(t.id)); e.dataTransfer.effectAllowed = 'move'; requestAnimationFrame(() => onDragStart(t.id)); }} onDragEnd={onDragEnd} onClick={onClick} className="ds-card hov" style={{ background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 10, padding: 12, display: 'flex', flexDirection: 'column', gap: 8, cursor: 'grab', boxShadow: 'var(--shadow-1)', opacity: dragging ? 0.35 : 1, transition: 'opacity 100ms', userSelect: 'none', WebkitUserSelect: 'none' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span style={{ display: 'inline-block', fontFamily: 'var(--font-display)', fontSize: 9, fontWeight: 700, letterSpacing: '0.06em', padding: '2px 8px', borderRadius: 4, background: t.tc + '24', color: t.tc }}>{t.tg}</span>
        <PriorityDot p={t.pri}/>
      </div>
      <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.35 }}>{t.t}</div>
      <div style={{ fontSize: 11, color: 'var(--fg-muted)' }}>{t.proj}</div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 4 }}>
        <Avatar name={t.who} size={22} idx={0}/>
        <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>{t.due}</span>
      </div>
    </div>
  );
}

function FilterPop({ label, icon, options, selected, onChange }) {
  const [open, setOpen] = useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    if (!open) return;
    const close = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [open]);
  const allOn = selected.size === options.length && options.length > 0;
  const toggle = v => { const next = new Set(selected); if (next.has(v)) next.delete(v); else next.add(v); onChange(next); };
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <Button variant="secondary" icon={icon} onClick={() => setOpen(o => !o)}>
        {label}{!allOn && selected.size > 0 && <span style={{ marginLeft: 6, background: 'var(--accent-primary)', color: '#fff', fontSize: 10, fontFamily: 'var(--font-mono)', fontWeight: 700, padding: '1px 5px', borderRadius: 4 }}>{selected.size}</span>}
      </Button>
      {open && (
        <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, zIndex: 60, width: 240, background: 'var(--bg-surface)', border: '1px solid var(--border-strong)', borderRadius: 10, boxShadow: '0 16px 40px rgba(0,0,0,0.5)', overflow: 'hidden' }}>
          <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{label}</span>
            <button onClick={() => onChange(new Set(allOn ? [] : options.map(o => o.v)))} style={{ background: 'transparent', border: 'none', cursor: 'pointer', fontSize: 11, color: 'var(--accent-primary)', fontWeight: 600 }}>{allOn ? 'Limpar' : 'Todos'}</button>
          </div>
          <div style={{ maxHeight: 280, overflowY: 'auto' }}>
            {options.map(o => {
              const checked = selected.has(o.v);
              return (
                <button key={o.v} onClick={() => toggle(o.v)} style={{ width: '100%', background: 'transparent', border: 'none', cursor: 'pointer', padding: '8px 12px', display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left' }} onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-elevated)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                  <div style={{ width: 16, height: 16, borderRadius: 4, border: `1.5px solid ${checked ? 'var(--accent-primary)' : 'var(--border-strong)'}`, background: checked ? 'var(--accent-primary)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    {checked && <Icon d={ICONS.check[0]} size={10} stroke="#fff"/>}
                  </div>
                  {o.dot && <span style={{ width: 8, height: 8, borderRadius: '50%', background: o.dot }}/>}
                  {o.who && <Avatar name={o.who} size={20} idx={o.idx || 0}/>}
                  <span style={{ flex: 1, fontSize: 13, color: 'var(--fg-primary)' }}>{o.l}</span>
                </button>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

function Tasks({ onNewTask }) {
  const [tasks,       setTasks]       = useState([]);
  const [loading,     setLoading]     = useState(true);
  const [view,        setView]        = useState('kanban');
  const [q,           setQ]           = useState('');
  const [draggingId,  setDraggingId]  = useState(null);
  const [dragOverCol, setDragOverCol] = useState(null);
  const [selectedTask,setSelectedTask]= useState(null);

  const allPri = ['alta', 'média', 'baixa'];
  const [pri,  setPri]  = useState(new Set(allPri));
  const [who,  setWho]  = useState(new Set());
  const [proj, setProj] = useState(new Set());

  useEffect(() => {
    (async () => {
      const { data, error } = await sb.from('tasks').select('*').order('created_at', { ascending: false });
      if (error) { window.__toast?.(error.message, { tone: 'danger' }); }
      const mapped = (data || []).map(rowToTask);
      setTasks(mapped);
      setWho(new Set(mapped.map(t => t.who)));
      setProj(new Set(mapped.map(t => t.proj)));
      setLoading(false);
    })();
  }, []);

  React.useEffect(() => {
    window.__addExternalTask = (task) => {
      setTasks(prev => [...prev, task]);
      setProj(prev => new Set([...prev, task.proj]));
      setWho(prev => new Set([...prev, task.who]));
    };
    return () => { window.__addExternalTask = null; };
  }, []);

  const allWho  = Array.from(new Set(tasks.map(t => t.who)));
  const allProj = Array.from(new Set(tasks.map(t => t.proj)));

  const filtered = tasks.filter(t =>
    (!q || t.t.toLowerCase().includes(q.toLowerCase()) || t.proj.toLowerCase().includes(q.toLowerCase()))
    && pri.has(t.pri)
    && (who.size  === 0 || who.has(t.who))
    && (proj.size === 0 || proj.has(t.proj))
  );

  async function moveTask(id, toCol) {
    setTasks(prev => prev.map(t => t.id === id ? { ...t, col: toCol } : t));
    await sb.from('tasks').update({ kanban_col: toCol, done: toCol === 'done' }).eq('id', id);
  }

  async function deleteTask(id) {
    setTasks(prev => prev.filter(t => t.id !== id));
    setSelectedTask(null);
    const { error } = await sb.from('tasks').delete().eq('id', id);
    if (error) window.__toast?.('Erro ao apagar tarefa: ' + error.message, { tone: 'danger' });
    else window.__toast?.('Tarefa apagada.', { tone: 'success' });
  }

  async function updateTask(id, changes) {
    const dbChanges = {};
    if (changes.t        !== undefined) dbChanges.title         = changes.t;
    if (changes.pri      !== undefined) dbChanges.priority      = changes.pri;
    if (changes.who      !== undefined) dbChanges.assignee      = changes.who;
    if (changes.due      !== undefined) dbChanges.due_date      = changes.due;
    if (changes.desc     !== undefined) dbChanges.description   = changes.desc;
    if (changes.subtasks !== undefined) dbChanges.subtasks_data = changes.subtasks;
    setTasks(prev => prev.map(t => t.id === id ? { ...t, ...changes } : t));
    if (Object.keys(dbChanges).length) {
      await sb.from('tasks').update(dbChanges).eq('id', id);
    }
  }

  if (loading) {
    return <div style={{ padding: 40, textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>Carregando tarefas…</div>;
  }

  return (
    <div style={{ padding: '24px 28px', display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        <div style={{ display: 'inline-flex', background: 'var(--bg-surface)', border: '1px solid var(--border-subtle)', borderRadius: 10, padding: 3 }}>
          {[{ id: 'kanban', l: 'Kanban' }, { id: 'list', l: 'Lista' }, { id: 'cal', l: 'Calendário' }, { id: 'modelos', l: 'Modelos' }].map(v => (
            <button key={v.id} onClick={() => setView(v.id)} style={{ padding: '7px 14px', borderRadius: 7, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 600, background: view === v.id ? 'var(--primary)' : 'transparent', color: view === v.id ? '#fff' : 'var(--fg-secondary)' }}>{v.l}</button>
          ))}
        </div>
        {view !== 'modelos' && <>
          <div style={{ width: 280 }}><Field icon="search" placeholder="Buscar tarefa…" value={q} onChange={e => setQ(e.target.value)}/></div>
          <FilterPop label="Prioridade" icon="filter" selected={pri} onChange={setPri} options={[{ v:'alta',l:'Alta',dot:'#EF4444' },{ v:'média',l:'Média',dot:'#FADB14' },{ v:'baixa',l:'Baixa',dot:'#7A859A' }]}/>
          <FilterPop label="Responsável" icon="users" selected={who} onChange={setWho} options={allWho.map((w, i) => ({ v: w, l: w, who: w, idx: i }))}/>
          <FilterPop label="Projeto" icon="folder" selected={proj} onChange={setProj} options={allProj.map((p, i) => ({ v: p, l: p, idx: i }))}/>
          <div style={{ flex: 1 }}/>
          <Button icon="plus" onClick={() => onNewTask?.()}>Nova tarefa</Button>
        </>}
      </div>

      {tasks.length === 0 && (
        <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--fg-muted)' }}>
          <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 6 }}>Nenhuma tarefa ainda</div>
          <div style={{ fontSize: 13 }}>Clique em "Nova tarefa" para começar.</div>
        </div>
      )}

      {view === 'kanban' && (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
          {COLS.map(col => {
            const items = filtered.filter(t => t.col === col.id);
            const isOver = dragOverCol === col.id;
            return (
              <div key={col.id}
                onDragEnter={e => { e.preventDefault(); setDragOverCol(col.id); }}
                onDragOver={e => { e.preventDefault(); }}
                onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget)) setDragOverCol(null); }}
                onDrop={e => { e.preventDefault(); const id = e.dataTransfer.getData('text/plain'); if (id) moveTask(id, col.id); setDraggingId(null); setDragOverCol(null); }}
                style={{ background: isOver ? col.tone + '14' : 'var(--bg-surface)', border: `${isOver ? 2 : 1}px solid ${isOver ? col.tone : 'var(--border-subtle)'}`, borderRadius: 14, padding: 14, display: 'flex', flexDirection: 'column', gap: 10, minHeight: 480, transition: 'background 100ms, border-color 100ms' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 4px 6px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 700, fontSize: 13 }}>
                    <span style={{ width: 10, height: 10, borderRadius: '50%', background: col.tone }}/>{col.lab}
                    <span style={{ fontSize: 11, color: 'var(--fg-muted)', fontFamily: 'var(--font-mono)' }}>{items.length}</span>
                  </div>
                  <Icon d={ICONS.plus} size={14} style={{ color: 'var(--fg-muted)', cursor: 'pointer' }}/>
                </div>
                {items.map(t => (
                  <TaskCard key={t.id} t={t} dragging={draggingId === t.id} onDragStart={id => setDraggingId(id)} onDragEnd={() => { setDraggingId(null); setDragOverCol(null); }} onClick={() => setSelectedTask(t)}/>
                ))}
                <button style={{ background: 'transparent', border: '1px dashed var(--border-subtle)', borderRadius: 8, padding: 10, color: 'var(--fg-muted)', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12 }}>+ Adicionar tarefa</button>
              </div>
            );
          })}
        </div>
      )}

      {view === 'list' && (
        <Card padding={0} style={{ overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '40px 1fr 160px 120px 110px 110px 110px', padding: '12px 18px', borderBottom: '1px solid var(--border-subtle)', fontSize: 11, fontFamily: 'var(--font-display)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--fg-muted)', alignItems: 'center' }}>
            <span/><span>Tarefa</span><span>Projeto</span><span>Etiqueta</span><span>Prioridade</span><span>Vencimento</span><span>Responsável</span>
          </div>
          {filtered.map(t => (
            <div key={t.id} onClick={() => setSelectedTask(t)} style={{ display: 'grid', gridTemplateColumns: '40px 1fr 160px 120px 110px 110px 110px', padding: '12px 18px', borderBottom: '1px solid var(--border-subtle)', fontSize: 13, alignItems: 'center', cursor: 'pointer' }} onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-elevated)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span style={{ width: 18, height: 18, borderRadius: 4, border: '1.5px solid var(--border-strong)', background: t.col === 'done' ? 'var(--accent-success)' : 'transparent', display: 'grid', placeItems: 'center' }}>{t.col === 'done' && <Icon d={ICONS.check[0]} size={11} style={{ color: '#fff' }}/>}</span>
              <span style={{ fontWeight: 600, color: t.col === 'done' ? 'var(--fg-muted)' : 'var(--fg-primary)', textDecoration: t.col === 'done' ? 'line-through' : 'none' }}>{t.t}</span>
              <span style={{ color: 'var(--fg-secondary)' }}>{t.proj}</span>
              <span><span style={{ fontFamily: 'var(--font-display)', fontSize: 9, fontWeight: 700, padding: '2px 8px', borderRadius: 4, background: t.tc + '24', color: t.tc }}>{t.tg}</span></span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6, color: 'var(--fg-secondary)' }}><PriorityDot p={t.pri}/>{t.pri}</span>
              <span style={{ color: 'var(--fg-secondary)', fontFamily: 'var(--font-mono)', fontSize: 12 }}>{t.due}</span>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Avatar name={t.who} size={22} idx={0}/><span style={{ fontSize: 12, color: 'var(--fg-secondary)' }}>{t.who.split(' ')[0]}</span></span>
            </div>
          ))}
        </Card>
      )}

      {view === 'cal' && (
        <Card padding={0} style={{ overflow: 'hidden' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', borderBottom: '1px solid var(--border-subtle)' }}>
            {['Seg','Ter','Qua','Qui','Sex','Sáb','Dom'].map(d => (
              <div key={d} style={{ padding: '12px 14px', fontSize: 11, fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--fg-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{d}</div>
            ))}
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gridAutoRows: 96 }}>
            {Array.from({ length: 28 }).map((_, i) => {
              const day = i + 1;
              const tasksOfDay = filtered.filter(t => parseInt(t.due) === day);
              return (
                <div key={i} style={{ borderRight: '1px solid var(--border-subtle)', borderBottom: '1px solid var(--border-subtle)', padding: 6, fontSize: 11 }}>
                  <div style={{ color: 'var(--fg-muted)', fontWeight: 600, marginBottom: 4 }}>{day}</div>
                  {tasksOfDay.slice(0, 2).map(t => (
                    <div key={t.id} onClick={() => setSelectedTask(t)} style={{ background: t.tc + '22', color: t.tc, fontSize: 10, padding: '3px 6px', borderRadius: 4, marginBottom: 3, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', cursor: 'pointer' }}>{t.t}</div>
                  ))}
                  {tasksOfDay.length > 2 && <div style={{ fontSize: 10, color: 'var(--fg-muted)' }}>+{tasksOfDay.length - 2}</div>}
                </div>
              );
            })}
          </div>
        </Card>
      )}

      {view === 'modelos' && (
        window.ProcessTemplates
          ? React.createElement(window.ProcessTemplates)
          : <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--fg-muted)', fontSize: 14 }}>Carregando modelos…</div>
      )}

      {selectedTask && (
        <TaskDetailModal
          task={tasks.find(t => t.id === selectedTask.id) || selectedTask}
          onClose={() => setSelectedTask(null)}
          onMove={moveTask}
          onUpdate={updateTask}
          onDelete={deleteTask}
        />
      )}
    </div>
  );
}
window.Tasks = Tasks;
