// Tasks screen — list, filter, IA suggestions, new task sheet

// Helpers de recorrência (compartilhados via window)
const todayISO = () => new Date().toISOString().slice(0, 10);
const RECURRENCE_LABEL = {
  diaria: 'Todos os dias',
  'dias-uteis': 'Dias úteis',
  'fim-de-semana': 'Fim de semana',
  semanal: 'Semanal',
  mensal: 'Mensal',
};
// Decide se uma tarefa recorrente deve aparecer hoje
function recurrenceAppliesToday(rec) {
  if (!rec) return true;
  const dow = new Date().getDay(); // 0 dom .. 6 sab
  if (rec === 'diaria') return true;
  if (rec === 'dias-uteis') return dow >= 1 && dow <= 5;
  if (rec === 'fim-de-semana') return dow === 0 || dow === 6;
  if (rec === 'semanal' || rec === 'mensal') return true; // simplificado: sempre visível
  return true;
}
// Reseta tarefas recorrentes cujo lastCompletedAt é de outro dia
function resetRecurringTasks(tasks) {
  const today = todayISO();
  let changed = false;
  const next = tasks.map(t => {
    if (!t.recurrence) return t;
    if (t.lastCompletedAt && t.lastCompletedAt !== today && t.done) {
      changed = true;
      return { ...t, done: false };
    }
    return t;
  });
  return changed ? next : tasks;
}
window.recurrenceAppliesToday = recurrenceAppliesToday;
window.resetRecurringTasks = resetRecurringTasks;
window.RECURRENCE_LABEL = RECURRENCE_LABEL;

const TasksScreen = ({ state, setState, openAI, navigate, showToast }) => {
  const [filter, setFilter] = React.useState('hoje');
  const [showNew, setShowNew] = React.useState(false);
  const [detailId, setDetailId] = React.useState(null);

  // Reset diário ao abrir a tela
  React.useEffect(() => {
    const next = resetRecurringTasks(state.tasks);
    if (next !== state.tasks) setState(s => ({ ...s, tasks: next }));
  }, []);

  // Intent: abrir modal de nova tarefa via evento global (atalho do dashboard)
  React.useEffect(() => {
    const handler = () => setShowNew(true);
    window.addEventListener('cdv:open-new-task', handler);
    return () => window.removeEventListener('cdv:open-new-task', handler);
  }, []);

  const filtered = state.tasks.filter(t => {
    if (t.date !== filter) return false;
    if (t.recurrence && !recurrenceAppliesToday(t.recurrence)) return false;
    return true;
  });
  const done = filtered.filter(t => t.done).length;
  const pct = filtered.length ? (done / filtered.length) * 100 : 0;

  const detailTask = state.tasks.find(t => t.id === detailId) || null;

  const toggleTask = (id) => {
    setState(s => ({
      ...s,
      tasks: s.tasks.map(t => {
        if (t.id !== id) return t;
        const nextDone = !t.done;
        return {
          ...t,
          done: nextDone,
          lastCompletedAt: nextDone && t.recurrence ? todayISO() : t.lastCompletedAt,
        };
      })
    }));
    showToast('Tarefa atualizada');
  };
  const toggleSubtask = (taskId, subtaskId) => {
    setState(s => ({
      ...s,
      tasks: s.tasks.map(t =>
        t.id === taskId
          ? { ...t, subtasks: t.subtasks.map(sub => sub.id === subtaskId ? { ...sub, done: !sub.done } : sub) }
          : t
      )
    }));
  };
  const addSubtask = (taskId, title) => {
    setState(s => ({
      ...s,
      tasks: s.tasks.map(t =>
        t.id === taskId
          ? { ...t, subtasks: [...(t.subtasks || []), { id: 'st' + Date.now(), title, done: false }] }
          : t
      )
    }));
  };
  const deleteTask = (id) => {
    setState(s => ({ ...s, tasks: s.tasks.filter(t => t.id !== id) }));
    setDetailId(null);
    showToast('Tarefa excluída');
  };
  const updateTaskField = (id, patch) => {
    setState(s => ({ ...s, tasks: s.tasks.map(t => t.id === id ? { ...t, ...patch } : t) }));
  };

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Tarefas" subtitle="HOJE" right={
        <button onClick={() => setShowNew(true)} style={{
          background: CDV.brandGrad, border: 'none', width: 38, height: 38, borderRadius: 99,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
          boxShadow: '0 6px 20px -6px rgba(177,151,252,0.6)',
        }}><Icon name="plus" size={18} /></button>
      } />

      {/* Progress strip */}
      <div style={{ padding: '0 22px 18px' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <div style={{ fontSize: 26, fontWeight: 700, color: CDV.text, letterSpacing: -0.5 }}>{done}</div>
            <div style={{ fontSize: 14, color: CDV.textDim }}>de {filtered.length} concluídas</div>
          </div>
          <Pill color={CDV.mint}>+85 XP</Pill>
        </div>
        <ProgressBar percent={pct} gradient="linear-gradient(90deg, #B197FC, #FF8FB1)" height={8} />
      </div>

      {/* Filter pills */}
      <div style={{ padding: '0 22px 16px', display: 'flex', gap: 6, overflowX: 'auto' }}>
        {[
          { id: 'hoje', label: 'Hoje' },
          { id: 'amanha', label: 'Amanhã' },
          { id: 'semana', label: 'Esta semana' },
          { id: 'todos', label: 'Todos' },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            flex: '0 0 auto', height: 32, padding: '0 14px', borderRadius: 99,
            background: filter === f.id ? CDV.text : CDV.surface,
            color: filter === f.id ? '#000' : CDV.textDim,
            border: `1px solid ${filter === f.id ? 'transparent' : CDV.stroke}`,
            fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
          }}>{f.label}</button>
        ))}
      </div>

      {/* AI suggestion banner */}
      <div style={{ padding: '0 22px 16px' }}>
        <div style={{
          padding: 14, borderRadius: 16,
          background: 'linear-gradient(135deg, rgba(94,227,168,0.10), rgba(177,151,252,0.08))',
          border: `1px solid ${CDV.stroke}`,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 34, height: 34, borderRadius: 10, background: CDV.brandGrad,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', flexShrink: 0,
          }}><Icon name="sparkle" size={16} /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: CDV.text, lineHeight: 1.3 }}>
              Sofia sugere reorganizar suas tarefas
            </div>
            <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>
              Você produz mais entre 9h e 11h. Posso reagendar 2 tarefas?
            </div>
          </div>
          <button onClick={() => showToast('Reorganizado pela IA')} style={{
            background: CDV.text, color: '#000', border: 'none', padding: '7px 12px',
            borderRadius: 99, fontSize: 12, fontWeight: 600,
          }}>Sim</button>
        </div>
      </div>

      {/* Task groups */}
      <SectionHeader title={filter === 'hoje' ? 'Alta prioridade' : 'Prioridade alta'} />
      <div style={{ padding: '0 22px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {filtered.filter(t => t.priority === 'alta').map(t => (
          <TaskRow key={t.id} task={t} onToggle={toggleTask} onToggleSubtask={toggleSubtask} onOpenDetail={() => setDetailId(t.id)} />
        ))}
        {filtered.filter(t => t.priority === 'alta').length === 0 && <Empty>Nenhuma tarefa de alta prioridade.</Empty>}
      </div>

      <SectionHeader title="Outras tarefas" />
      <div style={{ padding: '0 22px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {filtered.filter(t => t.priority !== 'alta').map(t => (
          <TaskRow key={t.id} task={t} onToggle={toggleTask} onToggleSubtask={toggleSubtask} onOpenDetail={() => setDetailId(t.id)} />
        ))}
      </div>

      <Sheet open={showNew} onClose={() => setShowNew(false)} title="Nova tarefa">
        <NewTaskForm
          onSubmit={(task) => {
            setState(s => ({ ...s, tasks: [...s.tasks, { ...task, id: 'tn' + Date.now() }] }));
            setShowNew(false);
            showToast('Tarefa criada');
          }}
          onVoice={() => {
            setShowNew(false);
            openAI();
          }}
        />
      </Sheet>

      <Sheet open={!!detailTask} onClose={() => setDetailId(null)} title="Detalhes">
        {detailTask && (
          <TaskDetail
            task={detailTask}
            onToggle={toggleTask}
            onToggleSubtask={toggleSubtask}
            onAddSubtask={addSubtask}
            onUpdate={updateTaskField}
            onDelete={deleteTask}
            onClose={() => setDetailId(null)}
          />
        )}
      </Sheet>
    </div>
  );
};

const TaskRow = ({ task, onToggle, onOpenDetail }) => {
  const catColor = CDV.cats[task.category] || CDV.brand;
  const [pressed, setPressed] = React.useState(false);
  return (
    <div
      onClick={onOpenDetail}
      onTouchStart={() => setPressed(true)}
      onTouchEnd={() => setPressed(false)}
      onMouseDown={() => setPressed(true)}
      onMouseUp={() => setPressed(false)}
      onMouseLeave={() => setPressed(false)}
      style={{
        borderRadius: 16,
        background: task.done
          ? CDV.surface
          : `linear-gradient(135deg, ${catColor}0d 0%, ${CDV.surface} 50%)`,
        border: `1px solid ${task.done ? CDV.stroke : catColor + '22'}`,
        overflow: 'hidden', cursor: 'pointer', position: 'relative',
        transform: pressed ? 'scale(0.98)' : 'scale(1)',
        transition: 'transform .15s, box-shadow .2s',
        boxShadow: task.done ? 'none' : `0 4px 14px -10px ${catColor}40`,
        opacity: task.done ? 0.7 : 1,
      }}
    >
      {/* Barra lateral categoria */}
      {!task.done && (
        <div style={{
          position: 'absolute', left: 0, top: 14, bottom: 14, width: 3, borderRadius: 99,
          background: `linear-gradient(180deg, ${catColor}, ${catColor}40)`,
          boxShadow: `0 0 10px ${catColor}80`,
        }} />
      )}
      <div style={{ padding: 14, paddingLeft: 16, display: 'flex', alignItems: 'flex-start', gap: 12, position: 'relative' }}>
        <div onClick={e => e.stopPropagation()}>
          <Checkbox checked={task.done} onChange={() => onToggle(task.id)} color={catColor} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14, fontWeight: 500, color: task.done ? CDV.textMuted : CDV.text, textDecoration: task.done ? 'line-through' : 'none', lineHeight: 1.3 }}>
            {task.title}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6, flexWrap: 'wrap' }}>
            <Pill color={catColor} size="sm" bg={catColor + '1a'}>
              <div style={{ width: 5, height: 5, borderRadius: 99, background: catColor }} /> {task.category}
            </Pill>
            <div style={{ fontSize: 11, color: CDV.textDim, display: 'flex', alignItems: 'center', gap: 4 }}>
              <Icon name="clock" size={11} /> {task.time}
              {task.duration && ` · ${task.duration}min`}
            </div>
            {task.priority === 'alta' && <Pill color={CDV.coral} size="sm">Alta</Pill>}
            {task.aiSuggested && <Pill color={CDV.brand} size="sm"><Icon name="sparkle" size={9} /> IA</Pill>}
            {task.recurrence && (
              <div style={{ fontSize: 11, color: CDV.textDim, display: 'flex', alignItems: 'center', gap: 3 }}>
                <Icon name="refresh" size={10} color={CDV.textDim} /> {RECURRENCE_LABEL[task.recurrence] || 'recorrente'}
              </div>
            )}
            {task.subtasks && task.subtasks.length > 0 && (
              <div style={{ fontSize: 11, color: CDV.textDim }}>
                {task.subtasks.filter(s => s.done).length}/{task.subtasks.length} subtarefas
              </div>
            )}
          </div>
        </div>
        <Icon name="chevronRight" size={14} color={CDV.textMuted} />
      </div>
    </div>
  );
};

// ── Task detail (sheet) ──────────────────────────────────────
const TaskDetail = ({ task, onToggle, onToggleSubtask, onAddSubtask, onUpdate, onDelete, onClose }) => {
  const catColor = CDV.cats[task.category] || CDV.brand;
  const priColor = task.priority === 'alta' ? CDV.coral : task.priority === 'media' ? CDV.amber : CDV.sky;
  const [newSub, setNewSub] = React.useState('');
  const [editing, setEditing] = React.useState(false);
  const [draftTitle, setDraftTitle] = React.useState(task.title);
  const [draftTime, setDraftTime] = React.useState(task.time === '—' ? '' : task.time);
  const [draftPriority, setDraftPriority] = React.useState(task.priority);
  const [draftCategory, setDraftCategory] = React.useState(task.category);
  const [draftRecurrence, setDraftRecurrence] = React.useState(task.recurrence || 'unico');
  const cats = ['trabalho', 'pessoal', 'saude', 'estudo', 'casa', 'lazer', 'outros'];

  const subs = task.subtasks || [];
  const doneSubs = subs.filter(s => s.done).length;

  const saveEdit = () => {
    onUpdate && onUpdate(task.id, {
      title: draftTitle.trim() || task.title,
      time: draftTime || '—',
      priority: draftPriority,
      category: draftCategory,
      recurrence: draftRecurrence === 'unico' ? null : draftRecurrence,
    });
    setEditing(false);
  };

  const confirmDelete = () => {
    if (window.confirm && window.confirm('Excluir esta tarefa? Esta ação não pode ser desfeita.')) {
      onDelete && onDelete(task.id);
    }
  };

  return (
    <div style={{ padding: '8px 22px 28px' }}>
      {/* Status / Título */}
      {!editing ? (
        <>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <Pill color={catColor} bg={catColor + '1a'}>
              <div style={{ width: 6, height: 6, borderRadius: 99, background: catColor }} /> {task.category}
            </Pill>
            <Pill color={priColor} bg={priColor + '1a'}>
              {task.priority === 'alta' ? 'Alta prioridade' : task.priority === 'media' ? 'Média' : 'Baixa'}
            </Pill>
            {task.recurrence && (
              <Pill color={CDV.brand} bg={CDV.brandSoft}>
                <Icon name="refresh" size={10} /> {RECURRENCE_LABEL[task.recurrence] || 'recorrente'}
              </Pill>
            )}
            {task.aiSuggested && <Pill color={CDV.brand}><Icon name="sparkle" size={10} /> Sugerido pela IA</Pill>}
          </div>
          <div style={{
            fontSize: 22, fontWeight: 700, color: task.done ? CDV.textMuted : CDV.text,
            textDecoration: task.done ? 'line-through' : 'none', letterSpacing: -0.3, lineHeight: 1.25,
            marginBottom: 14,
          }}>{task.title}</div>
        </>
      ) : (
        <>
          <input value={draftTitle} onChange={e => setDraftTitle(e.target.value)} placeholder="Título"
            style={{
              width: '100%', height: 54, borderRadius: 14, border: `1px solid ${CDV.stroke}`,
              background: CDV.surfaceHi, color: CDV.text, padding: '0 16px', fontSize: 16,
              outline: 'none', fontFamily: 'inherit', marginBottom: 12,
            }} />
          <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600, marginBottom: 6, letterSpacing: 0.3, textTransform: 'uppercase' }}>Categoria</div>
          <div style={{ display: 'flex', gap: 6, marginBottom: 12, flexWrap: 'wrap' }}>
            {cats.map(c => {
              const active = draftCategory === c;
              const cc = CDV.cats[c] || CDV.brand;
              return (
                <button key={c} onClick={() => setDraftCategory(c)} style={{
                  padding: '8px 12px', borderRadius: 99, border: `1px solid ${active ? cc : CDV.stroke}`,
                  background: active ? cc + '22' : CDV.surfaceHi, color: active ? cc : CDV.textDim,
                  fontSize: 12, fontWeight: 600, fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 5,
                }}>
                  <div style={{ width: 6, height: 6, borderRadius: 99, background: cc }} />
                  {c.charAt(0).toUpperCase() + c.slice(1)}
                </button>
              );
            })}
          </div>
          <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600, marginBottom: 6, letterSpacing: 0.3, textTransform: 'uppercase' }}>Prioridade</div>
          <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
            {[{ id: 'baixa', label: 'Baixa', c: CDV.sky }, { id: 'media', label: 'Média', c: CDV.amber }, { id: 'alta', label: 'Alta', c: CDV.coral }].map(p => {
              const active = draftPriority === p.id;
              return (
                <button key={p.id} onClick={() => setDraftPriority(p.id)} style={{
                  flex: 1, height: 40, borderRadius: 10,
                  background: active ? p.c + '22' : CDV.surfaceHi,
                  border: `1.5px solid ${active ? p.c : CDV.stroke}`,
                  color: active ? p.c : CDV.textDim, fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
                }}>{p.label}</button>
              );
            })}
          </div>
          <div style={{ fontSize: 11, color: CDV.textMuted, fontWeight: 600, marginBottom: 6, letterSpacing: 0.3, textTransform: 'uppercase' }}>Recorrência</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginBottom: 4 }}>
            {RECURRENCE_OPTIONS.map(r => {
              const active = draftRecurrence === r.id;
              return (
                <button key={r.id} onClick={() => setDraftRecurrence(r.id)} style={{
                  padding: '8px 10px', borderRadius: 10, textAlign: 'left',
                  background: active ? CDV.brandSoft : CDV.surfaceHi,
                  border: `1.5px solid ${active ? CDV.brand : CDV.stroke}`,
                  color: active ? CDV.text : CDV.textDim, fontFamily: 'inherit',
                  display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600,
                }}>
                  <Icon name={r.icon} size={12} color={active ? CDV.brand : CDV.textDim} />
                  {r.label}
                </button>
              );
            })}
          </div>
        </>
      )}

      {/* Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
        {!editing ? (
          <FieldCard label="Horário" value={task.time || '—'} icon="clock" />
        ) : (
          <TimeInputCard label="Horário" value={draftTime} onChange={setDraftTime} icon="clock" />
        )}
        <FieldCard label={task.duration ? 'Duração' : 'Data'} value={task.duration ? `${task.duration} min` : (task.date === 'hoje' ? 'Hoje' : task.date === 'amanha' ? 'Amanhã' : task.date)} icon={task.duration ? 'pomodoro' : 'calendar'} />
      </div>

      {/* Subtarefas */}
      {(subs.length > 0 || !editing) && (
        <>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 6, marginBottom: 8 }}>
            <div style={{ fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>
              Subtarefas {subs.length > 0 && `· ${doneSubs}/${subs.length}`}
            </div>
            {subs.length > 0 && (
              <ProgressBar percent={(doneSubs / subs.length) * 100} color={catColor} height={3} />
            )}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 10 }}>
            {subs.map(s => (
              <div key={s.id} style={{
                display: 'flex', alignItems: 'center', gap: 10, padding: 10,
                background: CDV.surfaceHi, borderRadius: 10, border: `1px solid ${CDV.stroke}`,
              }}>
                <Checkbox checked={s.done} onChange={() => onToggleSubtask && onToggleSubtask(task.id, s.id)} color={catColor} size={18} />
                <div style={{ flex: 1, fontSize: 13, color: s.done ? CDV.textMuted : CDV.text, textDecoration: s.done ? 'line-through' : 'none' }}>{s.title}</div>
              </div>
            ))}
            <div style={{ display: 'flex', gap: 8 }}>
              <input value={newSub} onChange={e => setNewSub(e.target.value)} placeholder="+ Adicionar subtarefa"
                onKeyDown={e => { if (e.key === 'Enter' && newSub.trim()) { onAddSubtask(task.id, newSub.trim()); setNewSub(''); } }}
                style={{
                  flex: 1, height: 42, borderRadius: 10, border: `1px solid ${CDV.stroke}`,
                  background: CDV.surfaceHi, color: CDV.text, padding: '0 12px', fontSize: 13,
                  outline: 'none', fontFamily: 'inherit',
                }} />
              {newSub.trim() && (
                <button onClick={() => { onAddSubtask(task.id, newSub.trim()); setNewSub(''); }} style={{
                  height: 42, padding: '0 14px', borderRadius: 10, background: catColor + '22',
                  border: `1px solid ${catColor}40`, color: catColor, fontWeight: 600, fontSize: 13, fontFamily: 'inherit',
                }}>Adicionar</button>
              )}
            </div>
          </div>
        </>
      )}

      {/* Ações principais */}
      <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
        {!editing ? (
          <>
            <button onClick={() => { onToggle(task.id); }} style={{
              flex: 1, height: 50, borderRadius: 14,
              background: task.done ? CDV.surfaceHi : CDV.brandGrad,
              border: task.done ? `1px solid ${CDV.strokeHi}` : 'none',
              color: '#fff', fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
            }}>{task.done ? 'Reabrir' : 'Marcar concluída'}</button>
            <button onClick={() => setEditing(true)} style={{
              height: 50, padding: '0 18px', borderRadius: 14,
              background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, color: CDV.text,
              fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
            }}>Editar</button>
          </>
        ) : (
          <>
            <button onClick={saveEdit} style={{
              flex: 1, height: 50, borderRadius: 14, background: CDV.brandGrad,
              border: 'none', color: '#fff', fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
            }}>Salvar alterações</button>
            <button onClick={() => { setEditing(false); setDraftTitle(task.title); setDraftTime(task.time === '—' ? '' : task.time); setDraftPriority(task.priority); setDraftCategory(task.category); setDraftRecurrence(task.recurrence || 'unico'); }} style={{
              height: 50, padding: '0 18px', borderRadius: 14,
              background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, color: CDV.textDim,
              fontWeight: 600, fontSize: 14, fontFamily: 'inherit',
            }}>Cancelar</button>
          </>
        )}
      </div>

      {!editing && (
        <button onClick={confirmDelete} style={{
          width: '100%', height: 44, borderRadius: 12, marginTop: 10,
          background: 'transparent', border: `1px solid ${CDV.coral}30`, color: CDV.coral,
          fontWeight: 600, fontSize: 13, fontFamily: 'inherit',
        }}>Excluir tarefa</button>
      )}
    </div>
  );
};

const Empty = ({ children }) => (
  <div style={{
    padding: 22, borderRadius: 16, background: CDV.surface, border: `1px dashed ${CDV.stroke}`,
    color: CDV.textDim, fontSize: 13, textAlign: 'center',
  }}>{children}</div>
);

const RECURRENCE_OPTIONS = [
  { id: 'unico', label: 'Único', icon: 'check' },
  { id: 'diaria', label: 'Todos os dias', icon: 'refresh' },
  { id: 'dias-uteis', label: 'Dias úteis', icon: 'briefcase' },
  { id: 'fim-de-semana', label: 'Fim de semana', icon: 'star' },
  { id: 'semanal', label: 'Semanal', icon: 'calendar' },
  { id: 'mensal', label: 'Mensal', icon: 'calendar' },
];

const NewTaskForm = ({ onSubmit, onVoice }) => {
  const [title, setTitle] = React.useState('');
  const [cat, setCat] = React.useState('trabalho');
  const [priority, setPriority] = React.useState('media');
  const [time, setTime] = React.useState('14:00');
  const [recurrence, setRecurrence] = React.useState('unico');
  const cats = ['trabalho', 'pessoal', 'saude', 'estudo', 'casa', 'lazer', 'outros'];
  const pris = [{ id: 'baixa', label: 'Baixa', c: CDV.sky }, { id: 'media', label: 'Média', c: CDV.amber }, { id: 'alta', label: 'Alta', c: CDV.coral }];

  return (
    <div style={{ padding: '12px 20px 28px' }}>
      <div style={{ position: 'relative' }}>
        <input value={title} onChange={e => setTitle(e.target.value)} placeholder="Ex: Ligar para o Roberto às 15h"
          style={{
            width: '100%', height: 54, borderRadius: 16, border: `1px solid ${CDV.stroke}`,
            background: CDV.surfaceHi, color: CDV.text, padding: '0 50px 0 16px', fontSize: 15,
            outline: 'none', fontFamily: 'inherit',
          }} />
        <button onClick={onVoice} style={{
          position: 'absolute', right: 6, top: 6, width: 42, height: 42, borderRadius: 12,
          background: CDV.brandGrad, border: 'none', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}><Icon name="mic" size={18} /></button>
      </div>
      <div style={{ marginTop: 8, fontSize: 12, color: CDV.brand, display: 'flex', alignItems: 'center', gap: 4 }}>
        <Icon name="sparkle" size={12} /> A IA detecta automaticamente data, hora e prioridade
      </div>

      <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Categoria</div>
      <div style={{ display: 'flex', gap: 6, marginTop: 8, flexWrap: 'wrap' }}>
        {cats.map(c => {
          const active = cat === c;
          const cc = CDV.cats[c];
          return (
            <button key={c} onClick={() => setCat(c)} style={{
              padding: '8px 12px', borderRadius: 99, border: `1px solid ${active ? cc : CDV.stroke}`,
              background: active ? cc + '22' : CDV.surfaceHi, color: active ? cc : CDV.textDim,
              fontSize: 12, fontWeight: 600, fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 5,
            }}>
              <div style={{ width: 6, height: 6, borderRadius: 99, background: cc }} />
              {c.charAt(0).toUpperCase() + c.slice(1)}
            </button>
          );
        })}
      </div>

      <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Prioridade</div>
      <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
        {pris.map(p => {
          const active = priority === p.id;
          return (
            <button key={p.id} onClick={() => setPriority(p.id)} style={{
              flex: 1, height: 44, borderRadius: 12,
              background: active ? p.c + '22' : CDV.surfaceHi,
              border: `1.5px solid ${active ? p.c : CDV.stroke}`,
              color: active ? p.c : CDV.textDim, fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
            }}>{p.label}</button>
          );
        })}
      </div>

      <div style={{ marginTop: 18 }}>
        <TimeInputCard label="Horário" value={time} onChange={setTime} icon="clock" />
      </div>

      <div style={{ marginTop: 14, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase' }}>Recorrência</div>
      <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
        {RECURRENCE_OPTIONS.map(r => {
          const active = recurrence === r.id;
          return (
            <button key={r.id} onClick={() => setRecurrence(r.id)} style={{
              padding: '10px 12px', borderRadius: 12, textAlign: 'left',
              background: active ? CDV.brandSoft : CDV.surfaceHi,
              border: `1.5px solid ${active ? CDV.brand : CDV.stroke}`,
              color: active ? CDV.text : CDV.textDim, fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, fontWeight: 600,
            }}>
              <Icon name={r.icon} size={13} color={active ? CDV.brand : CDV.textDim} />
              {r.label}
            </button>
          );
        })}
      </div>

      <button onClick={() => title && onSubmit({ title, category: cat, priority, time, date: 'hoje', done: false, recurrence: recurrence === 'unico' ? null : recurrence })} style={{
        marginTop: 22, width: '100%', height: 54, borderRadius: 16,
        background: CDV.brandGrad, border: 'none', color: '#fff', fontWeight: 600, fontSize: 15,
        boxShadow: '0 8px 24px -8px rgba(177,151,252,0.6)',
        opacity: title ? 1 : 0.4,
      }}>Criar tarefa</button>
    </div>
  );
};

const FieldCard = ({ label, value, icon }) => (
  <div style={{
    background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, borderRadius: 14, padding: 12,
    display: 'flex', alignItems: 'center', gap: 10,
  }}>
    <Icon name={icon} size={16} color={CDV.textDim} />
    <div style={{ flex: 1 }}>
      <div style={{ fontSize: 10, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontSize: 14, color: CDV.text, fontWeight: 500, marginTop: 1 }}>{value}</div>
    </div>
  </div>
);

const TimeInputCard = ({ label, value, onChange, icon }) => {
  const ref = React.useRef(null);
  const openPicker = () => {
    if (ref.current) {
      try { ref.current.showPicker && ref.current.showPicker(); } catch (e) {}
      ref.current.focus();
    }
  };
  return (
    <div onClick={openPicker} style={{
      background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, borderRadius: 14, padding: 12,
      display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer', position: 'relative',
    }}>
      <Icon name={icon} size={16} color={CDV.textDim} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 10, color: CDV.textMuted, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
        <input
          ref={ref}
          type="time"
          value={value}
          onChange={e => onChange(e.target.value)}
          style={{
            background: 'transparent', border: 'none', outline: 'none', padding: 0, marginTop: 1,
            color: CDV.text, fontSize: 14, fontWeight: 500, fontFamily: 'inherit',
            colorScheme: 'dark', width: '100%',
          }}
        />
      </div>
    </div>
  );
};

Object.assign(window, { TasksScreen, TaskRow, NewTaskForm, Empty, FieldCard, TimeInputCard });
