// Meu Painel — tela única de comando (tarefas, casos, calendário, eventos).
// Coexiste com o Dashboard antigo durante validação; depois o substitui.

// ── Helpers de data (dia local, sem UTC drift) ───────────────────────────────
const pIsoDay = (d = new Date()) => {
  const y = d.getFullYear(), m = String(d.getMonth() + 1).padStart(2, '0'), dd = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${dd}`;
};
const pAddDays = (iso, n) => {
  const [y, m, d] = iso.split('-').map(Number);
  const dt = new Date(y, m - 1, d + n);
  return pIsoDay(dt);
};
const pFmtShort = (iso) => {
  if (!iso) return '';
  const [y, m, d] = iso.slice(0, 10).split('-').map(Number);
  return new Date(y, m - 1, d).toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' });
};
const pRelTime = (ts) => {
  const diff = Date.now() - new Date(ts).getTime();
  const min = Math.floor(diff / 60000);
  if (min < 1) return 'agora';
  if (min < 60) return `há ${min} min`;
  const h = Math.floor(min / 60);
  if (h < 24) return `há ${h}h`;
  const dd = Math.floor(h / 24);
  return dd === 1 ? 'ontem' : `há ${dd} dias`;
};

const P_PRIORITY_COLOR = { 'Alta': '#ef4444', 'Média': '#f97316', 'Baixa': '#14b8a6' };
const P_HIST_LABEL = {
  criou: 'criou a tarefa',
  alterou_titulo: 'alterou o título',
  alterou_data: 'alterou a data',
  alterou_responsavel: 'alterou o responsável',
  alterou_prioridade: 'alterou a prioridade',
  concluiu: 'concluiu a tarefa',
  reabriu: 'reabriu a tarefa',
  duplicou: 'duplicou a partir de outra tarefa',
};

const PAvatar = ({ user, size = 24 }) => (
  <span title={user?.name || ''} style={{
    width: size, height: size, borderRadius: '50%', flexShrink: 0,
    background: user?.color || '#0D0D6B', color: '#fff',
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    fontSize: size * 0.38, fontWeight: 700, letterSpacing: '.02em',
    backgroundImage: user?.avatar_url ? `url(${user.avatar_url})` : undefined,
    backgroundSize: 'cover', backgroundPosition: 'center',
  }}>
    {!user?.avatar_url && (user?.initials || '?')}
  </span>
);

// ── Toast simples (padrão documentos.jsx) ────────────────────────────────────
const usePToast = () => {
  const [toast, setToast] = React.useState('');
  const show = (msg) => { setToast(msg); setTimeout(() => setToast(''), 3000); };
  const node = toast ? (
    <div style={{ position: 'fixed', bottom: '1.5rem', left: '50%', transform: 'translateX(-50%)', background: '#1f2937', color: '#fff', padding: '.625rem 1.25rem', borderRadius: 8, fontSize: '.875rem', fontWeight: 500, zIndex: 500, whiteSpace: 'nowrap' }}>
      {toast}
    </div>
  ) : null;
  return [show, node];
};

// ── Menu contextual genérico (portal, fecha em clique fora) ──────────────────
const PMenu = ({ anchor, onClose, children }) => {
  React.useEffect(() => {
    const onDown = (e) => {
      const el = document.getElementById('p-menu');
      if (el && !el.contains(e.target)) onClose();
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [onClose]);
  if (!anchor) return null;
  const r = anchor.getBoundingClientRect();
  const left = Math.min(r.left, window.innerWidth - 230);
  return ReactDOM.createPortal(
    <div id="p-menu" style={{
      position: 'fixed', top: r.bottom + 4, left, zIndex: 400, minWidth: 210,
      background: '#fff', border: '1px solid var(--border, #e8e8f0)', borderRadius: 8,
      boxShadow: '0 8px 32px rgba(0,0,0,.14)', padding: 4, fontSize: 13,
    }}>
      {children}
    </div>,
    document.body
  );
};

const PMenuItem = ({ onClick, danger, children }) => (
  <div
    onClick={onClick}
    style={{ padding: '7px 10px', borderRadius: 6, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, color: danger ? '#b91c1c' : 'var(--pac-black, #1a1a2e)' }}
    onMouseEnter={e => e.currentTarget.style.background = 'var(--surface, #f4f4f6)'}
    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
  >
    {children}
  </div>
);

// ── Confirm dialog ────────────────────────────────────────────────────────────
const PConfirm = ({ open, title, message, confirmLabel = 'Confirmar', onConfirm, onCancel }) => {
  if (!open) return null;
  return ReactDOM.createPortal(
    <div className="scrim" style={{ zIndex: 450 }} onClick={onCancel}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 12, padding: '1.25rem 1.5rem', maxWidth: 420, width: '92%', boxShadow: '0 20px 60px rgba(0,0,0,.25)' }}>
        <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 8, color: 'var(--pac-navy, #0D0D6B)' }}>{title}</div>
        <div style={{ fontSize: 13.5, color: '#4b5563', marginBottom: 16, lineHeight: 1.5 }}>{message}</div>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button className="btn ghost sm" onClick={onCancel}>Cancelar</button>
          <button className="btn sm" onClick={onConfirm}>{confirmLabel}</button>
        </div>
      </div>
    </div>,
    document.body
  );
};

// ── Modal rápido de criação (tarefa / evento) ────────────────────────────────
const PQuickModal = ({ title, open, onClose, children }) => {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);
  if (!open) return null;
  return ReactDOM.createPortal(
    <div className="scrim" style={{ zIndex: 420 }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ background: '#fff', borderRadius: 12, padding: '1.25rem 1.5rem', maxWidth: 460, width: '94%', boxShadow: '0 20px 60px rgba(0,0,0,.25)' }}>
        <div style={{ fontWeight: 700, fontSize: 15, marginBottom: 14, color: 'var(--pac-navy, #0D0D6B)' }}>{title}</div>
        {children}
      </div>
    </div>,
    document.body
  );
};

// ── Dropdown "+ Adicionar" ────────────────────────────────────────────────────
const AdicionarDropdown = ({ onNovaTarefa, onNovoEvento, onNavigate }) => {
  const [anchor, setAnchor] = React.useState(null);
  const items = [
    { section: 'No painel' },
    { label: 'Tarefa', icon: 'checkSquare', run: onNovaTarefa },
    { label: 'Evento', icon: 'calendar', run: onNovoEvento },
    { label: 'Caso', icon: 'briefcase', run: () => onNavigate('cases') },
    { section: 'Para a organização' },
    { label: 'Cliente', icon: 'users', run: () => onNavigate('clients') },
    { label: 'Usuário', icon: 'building', run: () => onNavigate('team') },
  ];
  return (
    <>
      <button className="btn sm" aria-label="Adicionar item" onClick={e => setAnchor(anchor ? null : e.currentTarget)} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <Icon name="plus" size={14} /> Adicionar
      </button>
      {anchor && (
        <PMenu anchor={anchor} onClose={() => setAnchor(null)}>
          {items.map((it, i) => it.section ? (
            <div key={i} style={{ padding: '6px 10px 3px', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--fg-muted, #9ca3af)' }}>{it.section}</div>
          ) : (
            <PMenuItem key={i} onClick={() => { setAnchor(null); it.run(); }}>
              <Icon name={it.icon} size={14} style={{ opacity: .6 }} /> {it.label}
            </PMenuItem>
          ))}
        </PMenu>
      )}
    </>
  );
};

// ── Mini calendário ───────────────────────────────────────────────────────────
const MiniCalendario = ({ filtro, onFiltro }) => {
  const hoje = pIsoDay();
  const [viewYm, setViewYm] = React.useState(hoje.slice(0, 7)); // 'YYYY-MM'

  const [vy, vm] = viewYm.split('-').map(Number);
  const first = new Date(vy, vm - 1, 1);
  const startWeekday = first.getDay(); // 0=dom
  const daysInMonth = new Date(vy, vm, 0).getDate();
  const monthLabel = first.toLocaleDateString('pt-BR', { month: 'long', year: 'numeric' });
  const isCurrentMonth = viewYm === hoje.slice(0, 7);
  const range7 = [...Array(7)].map((_, i) => pAddDays(hoje, i));

  const nav = (dir) => {
    const d = new Date(vy, vm - 1 + dir, 1);
    setViewYm(`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`);
  };

  const cells = [];
  for (let i = 0; i < startWeekday; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(`${viewYm}-${String(d).padStart(2, '0')}`);

  const dayStyle = (iso) => {
    const base = { width: 30, height: 30, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, cursor: 'pointer', margin: '0 auto', transition: 'background .12s' };
    if (iso === hoje) return { ...base, background: '#2563eb', color: '#fff', fontWeight: 700 };
    if (filtro.tipo === 'dia' && filtro.data === iso) return { ...base, background: '#bfdbfe', color: '#1e3a8a', fontWeight: 700 };
    if (filtro.tipo === 'proximos7' && range7.includes(iso)) return { ...base, background: '#60a5fa', color: '#fff' };
    return base;
  };

  const filterBtn = (active) => ({
    flex: 1, padding: '7px 8px', borderRadius: 7, fontSize: 12, fontWeight: 600, cursor: 'pointer',
    border: `1.5px solid ${active ? 'var(--pac-navy, #0D0D6B)' : 'var(--border, #e8e8f0)'}`,
    background: active ? 'var(--pac-navy, #0D0D6B)' : '#fff',
    color: active ? '#fff' : 'var(--pac-black, #1a1a2e)',
  });

  return (
    <div className="panel" style={{ padding: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <b style={{ fontSize: 13, textTransform: 'capitalize' }}>{monthLabel}</b>
        <div style={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          {!isCurrentMonth && (
            <button className="btn ghost sm" aria-label="Voltar para o mês atual" style={{ height: 24, padding: '0 8px', fontSize: 11 }} onClick={() => setViewYm(hoje.slice(0, 7))}>Hoje</button>
          )}
          <button className="tb-ic-btn" aria-label="Mês anterior" onClick={() => nav(-1)} style={{ width: 26, height: 26 }}><Icon name="chevronLeft" size={14} /></button>
          <button className="tb-ic-btn" aria-label="Próximo mês" onClick={() => nav(1)} style={{ width: 26, height: 26 }}><Icon name="chevronRight" size={14} /></button>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2, marginBottom: 4 }}>
        {['D', 'S', 'T', 'Q', 'Q', 'S', 'S'].map((w, i) => (
          <div key={i} style={{ textAlign: 'center', fontSize: 10, fontWeight: 700, color: 'var(--fg-muted, #9ca3af)' }}>{w}</div>
        ))}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 2 }}>
        {cells.map((iso, i) => iso ? (
          <div key={i} style={dayStyle(iso)} onClick={() => onFiltro({ tipo: 'dia', data: iso })}>
            {Number(iso.slice(8))}
          </div>
        ) : <div key={i} />)}
      </div>
      <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
        <button style={filterBtn(filtro.tipo === 'proximos7')} onClick={() => onFiltro({ tipo: 'proximos7' })}>Próximos 7 dias</button>
        <button style={filterBtn(filtro.tipo === 'sem_data')} onClick={() => onFiltro({ tipo: 'sem_data' })}>Sem data</button>
        <span
          title="Para selecionar múltiplos dias, clique na data inicial e, segurando CTRL, clique na data final."
          style={{ alignSelf: 'center', width: 20, height: 20, borderRadius: '50%', border: '1.5px solid var(--border, #e8e8f0)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, color: 'var(--fg-muted, #9ca3af)', cursor: 'help', flexShrink: 0 }}
        >?</span>
      </div>
      {filtro.tipo !== 'hoje' && (
        <button className="btn ghost sm" style={{ width: '100%', marginTop: 8, fontSize: 12 }} onClick={() => onFiltro({ tipo: 'hoje' })}>
          Limpar filtro (voltar para Hoje)
        </button>
      )}
    </div>
  );
};

// ── Sheet de detalhe da tarefa ────────────────────────────────────────────────
const TarefaDetailSheet = ({ taskId, users, onClose, onChanged, showToast }) => {
  const [task, setTask] = React.useState(null);
  const [history, setHistory] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [title, setTitle] = React.useState('');
  const [desc, setDesc] = React.useState('');
  const [taskEmail, setTaskEmail] = React.useState(null);
  const [showEmail, setShowEmail] = React.useState(false);

  const load = React.useCallback(() => {
    setLoading(true);
    Promise.all([
      window.PACApi.tasks.get(taskId),
      window.PACApi.tasks.history(taskId).catch(() => []),
      window.PACApi.tasks.email(taskId).catch(() => null),
    ]).then(([t, h, em]) => {
      setTask(t); setTitle(t.title); setDesc(t.description || ''); setHistory(h); setTaskEmail(em || null);
    }).finally(() => setLoading(false));
  }, [taskId]);
  React.useEffect(load, [load]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const save = async (fields) => {
    try {
      const updated = await window.PACApi.tasks.update(taskId, fields);
      setTask(updated);
      onChanged();
      window.PACApi.tasks.history(taskId).then(setHistory).catch(() => {});
    } catch (e) {
      showToast(e.message || 'Erro ao salvar.');
    }
  };

  const userById = (id) => users.find(u => u.id === id);

  return ReactDOM.createPortal(
    <div className="scrim" style={{ zIndex: 380, justifyContent: 'flex-end', alignItems: 'stretch', display: 'flex' }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ width: 'min(620px, 100%)', height: '100%', background: '#fff', boxShadow: '-12px 0 40px rgba(0,0,0,.18)', display: 'flex', flexDirection: 'column', animation: 'fade 160ms' }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--border, #e8e8f0)', display: 'flex', alignItems: 'center', gap: 10 }}>
          <b style={{ fontSize: 13, color: 'var(--fg-muted, #9ca3af)' }}>Detalhe da tarefa</b>
          <button className="tb-ic-btn" aria-label="Fechar painel" onClick={onClose} style={{ marginLeft: 'auto' }}><Icon name="x" size={16} /></button>
        </div>

        {loading || !task ? (
          <div style={{ padding: 24, color: 'var(--fg-muted)' }}>Carregando…</div>
        ) : (
          <div style={{ flex: 1, overflowY: 'auto', padding: '18px 20px' }}>
            <input
              value={title}
              onChange={e => setTitle(e.target.value)}
              onBlur={() => { if (title.trim() && title !== task.title) save({ title: title.trim() }); }}
              style={{ width: '100%', border: 'none', outline: 'none', fontSize: 18, fontWeight: 700, color: 'var(--pac-black, #1a1a2e)', marginBottom: 14, background: 'transparent' }}
            />

            <label className="pac-label" style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--fg-muted, #9ca3af)', fontWeight: 700 }}>Descrição</label>
            <textarea
              rows={5}
              value={desc}
              onChange={e => setDesc(e.target.value)}
              onBlur={() => { if (desc !== (task.description || '')) save({ description: desc || null }); }}
              placeholder="Adicione uma descrição…"
              style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 8, padding: '10px 12px', fontSize: 13.5, fontFamily: 'inherit', resize: 'vertical', outline: 'none', marginTop: 4, marginBottom: 16 }}
            />

            {taskEmail && (
              <div style={{ marginBottom: 16, display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: 'rgba(13,13,107,.04)', border: '1px solid rgba(13,13,107,.14)', borderRadius: 8 }}>
                <Icon name="mail" size={15} style={{ color: 'var(--pac-navy, #0D0D6B)', flexShrink: 0 }} />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--pac-black, #1a1a2e)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {taskEmail.subject || '(sem assunto)'}
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--fg-muted, #9ca3af)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    De: {taskEmail.from_address || '—'}
                  </div>
                </div>
                <button className="btn ghost sm" onClick={() => setShowEmail(true)} style={{ flexShrink: 0 }}>
                  <Icon name="mail" size={12} /> Ver e-mail
                </button>
              </div>
            )}

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 20 }}>
              <div>
                <label className="pac-label" style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)' }}>Data de vencimento</label>
                <input type="date" value={task.due_date || ''} onChange={e => save({ due_date: e.target.value || null })}
                  style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 6, padding: '7px 10px', fontSize: 13, marginTop: 3 }} />
              </div>
              <div>
                <label className="pac-label" style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)' }}>Prioridade</label>
                <select value={task.priority || 'Média'} onChange={e => save({ priority: e.target.value })}
                  style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 6, padding: '7px 10px', fontSize: 13, marginTop: 3, background: '#fff' }}>
                  {['Alta', 'Média', 'Baixa'].map(p => <option key={p} value={p}>{p}</option>)}
                </select>
              </div>
              <div>
                <label className="pac-label" style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)' }}>Responsável</label>
                <select value={task.owner_user_id || ''} onChange={e => save({ owner_user_id: e.target.value || null })}
                  style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 6, padding: '7px 10px', fontSize: 13, marginTop: 3, background: '#fff' }}>
                  <option value="">— Sem responsável —</option>
                  {users.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                </select>
              </div>
              <div>
                <label className="pac-label" style={{ fontSize: 11, fontWeight: 700, color: 'var(--fg-muted)' }}>Caso vinculado</label>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3, minHeight: 32 }}>
                  {task.case_id ? (
                    <span style={{ fontSize: 12.5, background: '#eff6ff', color: '#1d4ed8', borderRadius: 8, padding: '4px 10px', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {task.cases?.title || 'Caso'}
                    </span>
                  ) : <span style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>—</span>}
                </div>
              </div>
            </div>

            <div style={{ borderTop: '1px solid var(--border, #e8e8f0)', paddingTop: 14 }}>
              <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--fg-muted, #9ca3af)', fontWeight: 700, marginBottom: 10 }}>Histórico</div>
              {history.length === 0 ? (
                <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>Sem registros ainda. Alterações passam a ser registradas a partir de agora.</div>
              ) : history.map(h => (
                <div key={h.id} style={{ display: 'flex', gap: 10, padding: '7px 0', alignItems: 'flex-start' }}>
                  <PAvatar user={h.author} size={22} />
                  <div style={{ flex: 1, fontSize: 12.5, lineHeight: 1.45 }}>
                    <b>{h.author?.name || 'Sistema'}</b> {P_HIST_LABEL[h.action] || h.action}
                    {h.details?.de !== undefined && h.details?.para !== undefined && (
                      <span style={{ color: '#6b7280' }}> — de <b>{String(h.details.de ?? '—')}</b> para <b>{String(h.details.para ?? '—')}</b></span>
                    )}
                    <div style={{ fontSize: 11, color: 'var(--fg-muted, #9ca3af)' }}>{pRelTime(h.created_at)}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
      {showEmail && taskEmail && window.EmailReaderModal && (
        <window.EmailReaderModal
          email={taskEmail}
          onClose={() => setShowEmail(false)}
          snapshotNote="Cópia do e-mail vinculada a esta tarefa — salva no momento da criação do card."
        />
      )}
    </div>,
    document.body
  );
};

// ── Linha de tarefa (ou subtarefa normalizada pelo backend) ──────────────────
const TarefaRow = ({ task, users, onToggle, onOpen, onChanged, showToast }) => {
  const [menuAnchor, setMenuAnchor] = React.useState(null);
  const [confirmDel, setConfirmDel] = React.useState(false);
  const isSub = !!task.is_subtask;
  const done = task.kanban_column === 'concluido';
  const hoje = pIsoDay();
  const overdue = !done && task.due_date && task.due_date < hoje;
  const owner = users.find(u => u.id === task.owner_user_id);

  const setPriority = async (p) => {
    setMenuAnchor(null);
    try {
      await window.PACApi.tasks.update(task.id, { priority: p });
      showToast(`Prioridade alterada para ${p}.`);
      onChanged();
    } catch (e) { showToast(e.message || 'Erro.'); }
  };

  const duplicate = async () => {
    setMenuAnchor(null);
    try {
      await window.PACApi.tasks.duplicate(task.id);
      showToast('Tarefa duplicada.');
      onChanged();
    } catch (e) { showToast(e.message || 'Erro ao duplicar.'); }
  };

  const remove = async () => {
    setConfirmDel(false);
    try {
      await window.PACApi.tasks.delete(task.id);
      showToast('Tarefa excluída.');
      onChanged();
    } catch (e) { showToast(e.message || 'Erro ao excluir.'); }
  };

  return (
    <div
      style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 8, transition: 'background .1s' }}
      onMouseEnter={e => e.currentTarget.style.background = 'var(--surface, #f7f7fa)'}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
    >
      <button
        aria-label={done ? 'Reabrir tarefa' : 'Concluir tarefa'}
        onClick={() => onToggle(task)}
        onKeyDown={e => { if (e.key === ' ') { e.preventDefault(); onToggle(task); } }}
        style={{
          width: 17, height: 17, borderRadius: 4, flexShrink: 0, cursor: 'pointer',
          border: `1.5px solid ${done ? 'var(--pac-navy, #0D0D6B)' : '#c7c7d1'}`,
          background: done ? 'var(--pac-navy, #0D0D6B)' : 'transparent',
          display: 'grid', placeItems: 'center', padding: 0,
        }}
      >
        {done && <svg width="9" height="7" viewBox="0 0 9 7" fill="none"><path d="M1 3.5l2.5 2.5 4.5-5.5" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>}
      </button>

      {task.priority && !done && (
        <span title={`Prioridade ${task.priority}`} style={{ width: 7, height: 7, borderRadius: '50%', background: P_PRIORITY_COLOR[task.priority] || '#c7c7d1', flexShrink: 0 }} />
      )}

      <span
        onClick={() => onOpen(isSub ? task.parent_task_id : task.id)}
        style={{ flex: 1, minWidth: 0, fontSize: 13.5, cursor: 'pointer', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textDecoration: done ? 'line-through' : 'none', color: done ? 'var(--fg-muted, #9ca3af)' : 'var(--pac-black, #1a1a2e)' }}
      >
        {isSub && <span style={{ color: 'var(--fg-muted, #9ca3af)', marginRight: 5 }}>↳</span>}
        {task.title}
      </span>

      {isSub && task.parent_title && (
        <span title={`Subtarefa de: ${task.parent_title}`} style={{ fontSize: 11, background: '#f5f3ff', color: '#6d28d9', borderRadius: 6, padding: '2px 8px', fontWeight: 600, maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flexShrink: 0 }}>
          {task.parent_title}
        </span>
      )}

      {task.cases?.title && (
        <span title={task.cases.title} style={{ fontSize: 11, background: '#eff6ff', color: '#1d4ed8', borderRadius: 6, padding: '2px 8px', fontWeight: 600, maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flexShrink: 0 }}>
          {task.cases.title}
        </span>
      )}

      {task.due_date && (
        <span style={{ fontSize: 11.5, fontWeight: 600, color: overdue ? '#dc2626' : 'var(--fg-muted, #9ca3af)', flexShrink: 0 }}>
          {pFmtShort(task.due_date)}
        </span>
      )}

      {task.description && (
        <span title="Tem descrição — abrir detalhe" onClick={() => onOpen(task.id)} style={{ cursor: 'pointer', color: 'var(--fg-muted, #9ca3af)', flexShrink: 0, display: 'flex' }}>
          <Icon name="fileText" size={13} />
        </span>
      )}

      {owner && <PAvatar user={owner} size={22} />}

      {!isSub && (
        <button className="tb-ic-btn" aria-label="Mais ações" onClick={e => setMenuAnchor(menuAnchor ? null : e.currentTarget)} style={{ width: 24, height: 24, flexShrink: 0 }}>
          <span style={{ fontSize: 15, lineHeight: 1, color: 'var(--fg-muted)' }}>⋯</span>
        </button>
      )}
      <button className="tb-ic-btn" aria-label="Abrir detalhe" onClick={() => onOpen(isSub ? task.parent_task_id : task.id)} style={{ width: 22, height: 24, flexShrink: 0 }}>
        <Icon name="chevronRight" size={14} />
      </button>

      {menuAnchor && (
        <PMenu anchor={menuAnchor} onClose={() => setMenuAnchor(null)}>
          <div style={{ padding: '6px 10px 3px', fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--fg-muted, #9ca3af)' }}>Prioridade</div>
          {['Alta', 'Média', 'Baixa'].map(p => (
            <PMenuItem key={p} onClick={() => setPriority(p)}>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: P_PRIORITY_COLOR[p] }} />
              {p} {task.priority === p && <Icon name="check" size={12} style={{ marginLeft: 'auto' }} />}
            </PMenuItem>
          ))}
          <div style={{ height: 1, background: 'var(--border, #e8e8f0)', margin: '4px 0' }} />
          <PMenuItem onClick={duplicate}><Icon name="plus" size={13} style={{ opacity: .6 }} /> Duplicar</PMenuItem>
          <PMenuItem danger onClick={() => { setMenuAnchor(null); setConfirmDel(true); }}>
            <Icon name="x" size={13} /> Excluir
          </PMenuItem>
        </PMenu>
      )}

      <PConfirm
        open={confirmDel}
        title="Excluir tarefa"
        message={`Excluir permanentemente a tarefa "${task.title}"? Esta ação não pode ser desfeita.`}
        confirmLabel="Excluir"
        onConfirm={remove}
        onCancel={() => setConfirmDel(false)}
      />
    </div>
  );
};

// ── Seção Tarefas ─────────────────────────────────────────────────────────────
const P_FILTER_SELECT_STYLE = {
  border: '1px solid var(--border, #e8e8f0)', borderRadius: 6, padding: '4px 8px',
  fontSize: 12, background: '#fff', maxWidth: 150, color: 'var(--pac-black, #1a1a2e)',
};

const TarefasSection = ({ filtro, palavra, users, currentUser, reloadKey, onReload, onOpenTask, showToast }) => {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [quick, setQuick] = React.useState('');
  const [confirmBulk, setConfirmBulk] = React.useState(false);
  // Filtros locais da seção: tipo, responsável, revisor, ordenação por data
  const [tipo, setTipo] = React.useState('tarefas');
  const [responsavel, setResponsavel] = React.useState(''); // '' = eu (padrão)
  const [revisor, setRevisor] = React.useState('');
  const [ordenar, setOrdenar] = React.useState('asc');

  React.useEffect(() => {
    setLoading(true);
    window.PACApi.painel.tarefas({
      filtro: filtro.tipo,
      data: filtro.tipo === 'dia' ? filtro.data : undefined,
      q: palavra || undefined,
      tipo,
      responsavel: responsavel || undefined,
      revisor: (tipo === 'tarefas' && revisor) ? revisor : undefined,
      ordenar,
    }).then(setData).catch(e => showToast(e.message || 'Erro ao carregar tarefas.')).finally(() => setLoading(false));
  }, [filtro, palavra, reloadKey, tipo, responsavel, revisor, ordenar]);

  const toggle = async (task) => {
    const to = task.kanban_column === 'concluido' ? 'novo' : 'concluido';
    // Otimista: atualiza localmente antes do servidor
    setData(prev => {
      if (!prev) return prev;
      const map = (t) => t.id === task.id ? { ...t, kanban_column: to } : t;
      return { ...prev, atrasadas: prev.atrasadas.map(map), grupoAtual: { ...prev.grupoAtual, tarefas: prev.grupoAtual.tarefas.map(map) } };
    });
    try {
      if (task.is_subtask) {
        await window.PACApi.tasks.toggleSubtask(task.id);
      } else {
        await window.PACApi.tasks.moveColumn(task.id, to);
      }
      onReload();
    } catch (e) {
      showToast(e.message || 'Erro ao atualizar.');
      onReload();
    }
  };

  const quickAdd = async () => {
    const t = quick.trim();
    if (!t) return;
    setQuick('');
    try {
      await window.PACApi.tasks.create({
        title: t,
        due_date: filtro.tipo === 'dia' ? filtro.data : pIsoDay(),
        owner_user_id: currentUser?.id,
      });
      showToast('Tarefa criada.');
      onReload();
    } catch (e) { showToast(e.message || 'Erro ao criar tarefa.'); }
  };

  const bulkUpdate = async () => {
    setConfirmBulk(false);
    try {
      const n = await window.PACApi.tasks.updateOverdueToToday();
      showToast(`${n} tarefa${n === 1 ? '' : 's'} atualizada${n === 1 ? '' : 's'} para hoje.`);
      onReload();
    } catch (e) { showToast(e.message || 'Erro na atualização em massa.'); }
  };

  const atrasadas = data?.atrasadas || [];
  const grupo = data?.grupoAtual;

  return (
    <div className="panel" style={{ padding: '14px 12px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, padding: '0 6px' }}>
        <h3 style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--pac-navy, #0D0D6B)' }}>Tarefas</h3>
        {loading && <span className="spinner" style={{ width: 12, height: 12, borderColor: 'rgba(13,13,107,.15)', borderTopColor: 'var(--pac-navy)' }} />}
      </div>

      {/* Filtros: tipo, responsável, revisor, ordenação por data */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', marginBottom: 10, padding: '0 6px' }}>
        <select value={tipo} onChange={e => setTipo(e.target.value)} aria-label="Tipo" style={P_FILTER_SELECT_STYLE}>
          <option value="tarefas">Tarefas</option>
          <option value="subtarefas">Subtarefas</option>
        </select>
        <select value={responsavel} onChange={e => setResponsavel(e.target.value)} aria-label="Responsável" style={P_FILTER_SELECT_STYLE}>
          <option value="">Resp.: eu</option>
          <option value="todos">Resp.: todos</option>
          {users.filter(u => u.id !== currentUser?.id).map(u => (
            <option key={u.id} value={u.id}>Resp.: {u.name.split(' ')[0]}</option>
          ))}
        </select>
        {tipo === 'tarefas' && (
          <select value={revisor} onChange={e => setRevisor(e.target.value)} aria-label="Revisor" style={P_FILTER_SELECT_STYLE}>
            <option value="">Revisor: todos</option>
            {users.map(u => <option key={u.id} value={u.id}>Revisor: {u.name.split(' ')[0]}</option>)}
          </select>
        )}
        <select value={ordenar} onChange={e => setOrdenar(e.target.value)} aria-label="Ordenar por data" style={P_FILTER_SELECT_STYLE}>
          <option value="asc">Data ↑ mais próximas</option>
          <option value="desc">Data ↓ mais distantes</option>
        </select>
        {(tipo !== 'tarefas' || responsavel || revisor || ordenar !== 'asc') && (
          <button
            onClick={() => { setTipo('tarefas'); setResponsavel(''); setRevisor(''); setOrdenar('asc'); }}
            style={{ border: 'none', background: 'none', cursor: 'pointer', fontSize: 11.5, fontWeight: 600, color: 'var(--pac-navy, #0D0D6B)', textDecoration: 'underline' }}
          >
            Limpar
          </button>
        )}
      </div>

      {atrasadas.length > 0 && (
        <div style={{ marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', padding: '0 6px', marginBottom: 2 }}>
            <span style={{ fontSize: 11.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', color: '#dc2626' }}>
              Atrasadas <span style={{ opacity: .7 }}>({atrasadas.length})</span>
            </span>
            {tipo === 'tarefas' && !responsavel && (
              <button
                onClick={() => setConfirmBulk(true)}
                style={{ marginLeft: 'auto', border: 'none', background: 'none', cursor: 'pointer', fontSize: 11.5, fontWeight: 600, color: 'var(--pac-navy, #0D0D6B)', textDecoration: 'underline' }}
              >
                Atualizar todas para hoje
              </button>
            )}
          </div>
          {atrasadas.map(t => (
            <TarefaRow key={t.id} task={t} users={users} onToggle={toggle} onOpen={onOpenTask} onChanged={onReload} showToast={showToast} />
          ))}
        </div>
      )}

      <div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 6px', marginBottom: 2 }}>
          <span style={{ fontSize: 11.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--fg-muted, #6b7280)' }}>
            {grupo?.label || 'Hoje'} {grupo && <span style={{ opacity: .7 }}>({grupo.tarefas.length})</span>}
          </span>
          {grupo?.percentualConcluido != null && (
            <div style={{ flex: 1, maxWidth: 160, display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ flex: 1, height: 5, borderRadius: 3, background: 'var(--border, #e8e8f0)', overflow: 'hidden' }}>
                <div style={{ width: `${grupo.percentualConcluido}%`, height: '100%', background: 'var(--pac-navy, #0D0D6B)' }} />
              </div>
              <span style={{ fontSize: 10.5, color: 'var(--fg-muted)' }}>{grupo.percentualConcluido}%</span>
            </div>
          )}
        </div>

        {!loading && grupo && grupo.tarefas.length === 0 && (
          <div style={{ padding: '14px 6px', fontSize: 13, color: 'var(--fg-muted, #9ca3af)' }}>
            Nenhuma tarefa {grupo.label === 'Hoje' ? 'para hoje' : `em "${grupo.label}"`}. Que tal criar uma?
          </div>
        )}
        {grupo?.tarefas.map(t => (
          <TarefaRow key={t.id} task={t} users={users} onToggle={toggle} onOpen={onOpenTask} onChanged={onReload} showToast={showToast} />
        ))}

        {tipo === 'tarefas' && (filtro.tipo === 'hoje' || filtro.tipo === 'dia') && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 10px' }}>
            <Icon name="plus" size={14} style={{ color: 'var(--fg-muted, #9ca3af)', flexShrink: 0 }} />
            <input
              value={quick}
              onChange={e => setQuick(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') quickAdd(); }}
              placeholder="Insira o nome da tarefa e pressione Enter"
              style={{ flex: 1, border: 'none', outline: 'none', fontSize: 13, background: 'transparent', padding: '4px 0' }}
            />
          </div>
        )}
      </div>

      <PConfirm
        open={confirmBulk}
        title="Atualizar tarefas atrasadas"
        message={`Isso vai mover ${atrasadas.length} tarefa${atrasadas.length === 1 ? '' : 's'} atrasada${atrasadas.length === 1 ? '' : 's'} para hoje. Confirmar?`}
        onConfirm={bulkUpdate}
        onCancel={() => setConfirmBulk(false)}
      />
    </div>
  );
};

// ── Cards recentes do Kanban (tarefas por última atualização) ────────────────
const P_COL_LABEL = {
  novo: 'Novo', analise: 'Em análise', em_analise: 'Em análise',
  cliente: 'Aguardando cliente', aguardando_cliente: 'Aguardando cliente',
  redacao: 'Em redação', em_redacao: 'Em redação',
  revisao: 'Em revisão', em_revisao: 'Em revisão',
  externos: 'Aguardando externos', aguardando_externos: 'Aguardando externos',
  concluido: 'Concluído',
};

const KanbanCard = ({ card, users, onOpen, onNavigate }) => {
  const [menuAnchor, setMenuAnchor] = React.useState(null);
  const owner = users.find(u => u.id === card.owner_user_id);
  const hoje = pIsoDay();
  const overdue = card.due_date && card.due_date < hoje;

  return (
    <div className="panel" style={{ minWidth: 235, maxWidth: 235, scrollSnapAlign: 'start', padding: 14, display: 'flex', flexDirection: 'column', gap: 8, flexShrink: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        {card.priority && (
          <span title={`Prioridade ${card.priority}`} style={{ width: 8, height: 8, borderRadius: '50%', background: P_PRIORITY_COLOR[card.priority] || '#c7c7d1', flexShrink: 0 }} />
        )}
        <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--pac-navy, #0D0D6B)', background: 'rgba(13,13,107,.06)', borderRadius: 5, padding: '2px 7px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {P_COL_LABEL[card.kanban_column] || card.kanban_column}
        </span>
        <button className="tb-ic-btn" aria-label="Mais ações do card" onClick={e => setMenuAnchor(menuAnchor ? null : e.currentTarget)} style={{ marginLeft: 'auto', width: 24, height: 24, flexShrink: 0 }}>
          <span style={{ fontSize: 15, lineHeight: 1, color: 'var(--fg-muted)' }}>⋯</span>
        </button>
      </div>

      <div
        onClick={() => onOpen(card.id)}
        style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.4, cursor: 'pointer', color: 'var(--pac-black, #1a1a2e)', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', minHeight: 38 }}
      >
        {card.title}
      </div>

      <div style={{ fontSize: 11.5, color: 'var(--fg-muted, #9ca3af)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minHeight: 15 }}>
        {card.cases?.title || card.clients?.name || '—'}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 'auto' }}>
        {owner && <PAvatar user={owner} size={22} />}
        {card.due_date && (
          <span style={{ fontSize: 11, fontWeight: 600, color: overdue ? '#dc2626' : 'var(--fg-muted, #9ca3af)', marginLeft: 'auto' }}>
            {pFmtShort(card.due_date)}
          </span>
        )}
      </div>

      {menuAnchor && (
        <PMenu anchor={menuAnchor} onClose={() => setMenuAnchor(null)}>
          <PMenuItem onClick={() => { setMenuAnchor(null); onOpen(card.id); }}>
            <Icon name="fileText" size={13} style={{ opacity: .6 }} /> Abrir detalhe
          </PMenuItem>
          <PMenuItem onClick={() => { setMenuAnchor(null); onNavigate('tasks'); }}>
            <Icon name="kanban" size={13} style={{ opacity: .6 }} /> Ver no Kanban
          </PMenuItem>
        </PMenu>
      )}
    </div>
  );
};

// Card de e-mail — mesma formatação dos cards do Kanban.
const EmailCard = ({ email, onOpen, onCreateTask, onDismiss }) => {
  const [menuAnchor, setMenuAnchor] = React.useState(null);
  // "Nome <endereco@x>" → mostra só o nome; e-mail puro fica como está
  const senderName = (email.from || '').replace(/<[^>]*>/, '').replace(/"/g, '').trim() || email.from || '—';
  const fmtDay = (iso) => {
    if (!iso) return '';
    const d = new Date(iso);
    return isNaN(d.getTime()) ? '' : d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' }).replace('.', '');
  };

  return (
    <div className="panel" style={{ minWidth: 235, maxWidth: 235, scrollSnapAlign: 'start', padding: 14, display: 'flex', flexDirection: 'column', gap: 8, flexShrink: 0 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        {email.unread && (
          <span title="Não lida" style={{ width: 8, height: 8, borderRadius: '50%', background: '#2563eb', flexShrink: 0 }} />
        )}
        <span style={{ fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--pac-navy, #0D0D6B)', background: 'rgba(13,13,107,.06)', borderRadius: 5, padding: '2px 7px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {email.unread ? 'Nova' : 'E-mail'}
        </span>
        <button className="tb-ic-btn" aria-label="Mais ações do e-mail" onClick={e => setMenuAnchor(menuAnchor ? null : e.currentTarget)} style={{ marginLeft: 'auto', width: 24, height: 24, flexShrink: 0 }}>
          <span style={{ fontSize: 15, lineHeight: 1, color: 'var(--fg-muted)' }}>⋯</span>
        </button>
        <button
          className="tb-ic-btn"
          aria-label="Remover do painel"
          title="Remover do painel (não apaga do Gmail)"
          onClick={() => onDismiss && onDismiss(email)}
          style={{ width: 24, height: 24, flexShrink: 0 }}
        >
          <span style={{ fontSize: 15, lineHeight: 1, color: 'var(--fg-muted)' }}>✕</span>
        </button>
      </div>

      <div
        onClick={() => onOpen(email)}
        style={{ fontSize: 13.5, fontWeight: email.unread ? 700 : 600, lineHeight: 1.4, cursor: 'pointer', color: 'var(--pac-black, #1a1a2e)', display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden', minHeight: 38 }}
      >
        {email.subject}
      </div>

      <div style={{ fontSize: 11.5, color: 'var(--fg-muted, #9ca3af)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minHeight: 15 }}>
        {email.snippet || '—'}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 'auto', minWidth: 0 }}>
        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--pac-navy, #0D0D6B)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
          {senderName}
        </span>
        <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--fg-muted, #9ca3af)', marginLeft: 'auto', flexShrink: 0 }}>
          {fmtDay(email.date)}
        </span>
      </div>

      {menuAnchor && (
        <PMenu anchor={menuAnchor} onClose={() => setMenuAnchor(null)}>
          <PMenuItem onClick={() => { setMenuAnchor(null); onOpen(email); }}>
            <Icon name="mail" size={13} style={{ opacity: .6 }} /> Abrir e-mail
          </PMenuItem>
          <PMenuItem onClick={() => { setMenuAnchor(null); onCreateTask(email); }}>
            <Icon name="checkSquare" size={13} style={{ opacity: .6 }} /> Criar tarefa
          </PMenuItem>
          <PMenuItem onClick={() => { setMenuAnchor(null); onDismiss && onDismiss(email); }}>
            <span style={{ fontSize: 13, opacity: .6, width: 13, textAlign: 'center' }}>✕</span> Remover do painel
          </PMenuItem>
        </PMenu>
      )}
    </div>
  );
};

// Seção "Recentes" com abas: E-mails (Gmail) | Cards do Kanban.
// A aba E-mails só funciona após login com Google (gmail.readonly).
const CardsRecentesSection = ({ palavra, users, reloadKey, onOpenTask, onNavigate, onTaskCreated, showToast }) => {
  const [tab, setTab] = React.useState(() => localStorage.getItem('pac_painel_recentes_tab') || 'emails');
  const setTabPersist = (t) => { setTab(t); localStorage.setItem('pac_painel_recentes_tab', t); };

  // ── Cards do Kanban ──
  const [cards, setCards] = React.useState([]);
  const [loadingCards, setLoadingCards] = React.useState(true);

  // ── E-mails ──
  const [gmailConnected, setGmailConnected] = React.useState(null); // null = verificando
  const [emails, setEmails] = React.useState([]);
  const [loadingEmails, setLoadingEmails] = React.useState(false);
  const [emailError, setEmailError] = React.useState('');
  const [emailReload, setEmailReload] = React.useState(0);
  const [openEmail, setOpenEmail] = React.useState(null);       // e-mail completo no leitor
  const [openingEmailId, setOpeningEmailId] = React.useState(null);
  const [taskFromEmail, setTaskFromEmail] = React.useState(null); // e-mail no modal de tarefa

  const scrollRef = React.useRef(null);
  const [overflow, setOverflow] = React.useState(false);
  const checkOverflow = () => setTimeout(() => {
    const el = scrollRef.current;
    setOverflow(!!el && el.scrollWidth > el.clientWidth);
  }, 50);

  React.useEffect(() => {
    setLoadingCards(true);
    window.PACApi.painel.cards({ q: palavra || undefined }).then(cs => {
      setCards(cs);
      if (tab === 'cards') checkOverflow();
    }).catch(() => {}).finally(() => setLoadingCards(false));
  }, [palavra, reloadKey]);

  React.useEffect(() => {
    window.PACApi.gmail.status().then(({ connected }) => {
      setGmailConnected(connected);
      // Sem Gmail conectado, cai na aba de cards para não mostrar área vazia
      if (!connected && tab === 'emails') setTab('cards');
    }).catch(() => setGmailConnected(false));
  }, []);

  React.useEffect(() => {
    if (tab !== 'emails' || !gmailConnected) return;
    setLoadingEmails(true);
    setEmailError('');
    window.PACApi.gmail.messages({ q: palavra || undefined }).then(({ messages }) => {
      setEmails(messages);
      checkOverflow();
    }).catch(e => {
      setEmailError(e.message || 'Erro ao carregar e-mails.');
      if (/expirou|não conectado/i.test(e.message || '')) setGmailConnected(false);
    }).finally(() => setLoadingEmails(false));
  }, [tab, gmailConnected, palavra, emailReload]);

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

  const scrollBy = (dir) => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    scrollRef.current?.scrollBy({ left: dir * 500, behavior: reduce ? 'auto' : 'smooth' });
  };

  const handleOpenEmail = async (summary) => {
    setOpeningEmailId(summary.id);
    try {
      const full = await window.PACApi.gmail.message(summary.id);
      setOpenEmail(full);
      setEmails(prev => prev.map(m => m.id === summary.id ? { ...m, unread: false } : m));
    } catch (e) {
      if (showToast) showToast(e.message || 'Erro ao abrir e-mail.', 'error');
    } finally {
      setOpeningEmailId(null);
    }
  };

  const handleDismissEmail = async (email) => {
    const prev = emails;
    setEmails(list => list.filter(m => m.id !== email.id)); // remoção otimista
    try {
      await window.PACApi.gmail.dismiss(email.id);
      if (showToast) showToast('E-mail removido do painel.');
    } catch (e) {
      setEmails(prev); // reverte em caso de erro
      if (showToast) showToast(e.message || 'Erro ao remover o e-mail do painel.');
    }
  };

  const handleCreateTaskFromEmail = async (summaryOrFull) => {
    // Garante id + assunto; o modal usa o e-mail completo se já aberto
    if (openEmail && openEmail.id === summaryOrFull.id) {
      setTaskFromEmail(openEmail);
    } else {
      setTaskFromEmail(summaryOrFull);
    }
  };

  const loading = tab === 'emails' ? loadingEmails : loadingCards;

  const tabBtn = (id, label) => (
    <button
      onClick={() => setTabPersist(id)}
      style={{
        border: 'none', background: 'none', cursor: 'pointer', padding: '2px 0',
        fontSize: 14.5, fontWeight: 700,
        color: tab === id ? 'var(--pac-navy, #0D0D6B)' : 'var(--fg-muted, #9ca3af)',
        borderBottom: tab === id ? '2px solid var(--pac-lime, #C8F135)' : '2px solid transparent',
      }}
    >
      {label}
    </button>
  );

  return (
    <div className="panel" style={{ padding: '14px 12px' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 10, padding: '0 6px' }}>
        {tabBtn('emails', 'E-mails')}
        {tabBtn('cards', 'Cards recentes')}
        {tab === 'cards' && (
          <button
            onClick={() => onNavigate('tasks')}
            style={{ border: 'none', background: 'none', cursor: 'pointer', fontSize: 11.5, fontWeight: 600, color: 'var(--pac-navy, #0D0D6B)', textDecoration: 'underline' }}
          >
            Abrir Kanban
          </button>
        )}
        {tab === 'emails' && gmailConnected && (
          <>
            <a
              href="https://mail.google.com"
              target="_blank"
              rel="noopener noreferrer"
              style={{ fontSize: 11.5, fontWeight: 600, color: 'var(--pac-navy, #0D0D6B)', textDecoration: 'underline' }}
            >
              Abrir Gmail
            </a>
            <button className="tb-ic-btn" aria-label="Atualizar e-mails" title="Atualizar" onClick={() => setEmailReload(k => k + 1)} style={{ width: 24, height: 24 }}>
              <Icon name="refresh" size={13} />
            </button>
          </>
        )}
        {loading && <span className="spinner" style={{ width: 12, height: 12, borderColor: 'rgba(13,13,107,.15)', borderTopColor: 'var(--pac-navy)' }} />}
        {overflow && (
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 2 }}>
            <button className="tb-ic-btn" aria-label="Rolar para a esquerda" onClick={() => scrollBy(-1)} style={{ width: 26, height: 26 }}><Icon name="chevronLeft" size={14} /></button>
            <button className="tb-ic-btn" aria-label="Rolar para a direita" onClick={() => scrollBy(1)} style={{ width: 26, height: 26 }}><Icon name="chevronRight" size={14} /></button>
          </div>
        )}
      </div>

      {tab === 'cards' && !loadingCards && cards.length === 0 && (
        <div style={{ padding: '10px 6px', fontSize: 13, color: 'var(--fg-muted, #9ca3af)' }}>Nenhum card aberto no Kanban.</div>
      )}

      {tab === 'emails' && gmailConnected === false && (
        <div style={{ padding: '14px 6px', fontSize: 13, color: 'var(--fg-muted, #9ca3af)', lineHeight: 1.6 }}>
          Conecte sua conta Google para ver seus e-mails aqui: saia e entre novamente
          usando o botão <b>"Entrar com Google"</b> na tela de login.
        </div>
      )}
      {tab === 'emails' && gmailConnected && emailError && (
        <div style={{ padding: '10px 6px', fontSize: 12.5, color: '#C2253E' }}>{emailError}</div>
      )}
      {tab === 'emails' && gmailConnected && !loadingEmails && !emailError && emails.length === 0 && (
        <div style={{ padding: '10px 6px', fontSize: 13, color: 'var(--fg-muted, #9ca3af)' }}>Caixa de entrada vazia.</div>
      )}

      <div ref={scrollRef} style={{ display: 'flex', gap: 10, overflowX: 'auto', scrollSnapType: 'x mandatory', paddingBottom: 6, scrollbarWidth: 'thin' }}>
        {tab === 'cards' && cards.map(c => <KanbanCard key={c.id} card={c} users={users} onOpen={onOpenTask} onNavigate={onNavigate} />)}
        {tab === 'emails' && gmailConnected && emails.map(m => (
          <EmailCard key={m.id} email={m} onOpen={handleOpenEmail} onCreateTask={handleCreateTaskFromEmail} onDismiss={handleDismissEmail} />
        ))}
      </div>

      {openingEmailId && (
        <div style={{ padding: '4px 6px', fontSize: 11.5, color: 'var(--fg-muted, #9ca3af)' }}>Abrindo e-mail…</div>
      )}

      {openEmail && window.EmailReaderModal && (
        <window.EmailReaderModal
          email={openEmail}
          onClose={() => setOpenEmail(null)}
          onCreateTask={() => setTaskFromEmail(openEmail)}
        />
      )}

      {taskFromEmail && window.EmailToTaskModal && (
        <window.EmailToTaskModal
          email={taskFromEmail}
          users={users}
          onClose={() => setTaskFromEmail(null)}
          onCreated={(task, emailLinked) => {
            setTaskFromEmail(null);
            setOpenEmail(null);
            if (showToast) {
              showToast(emailLinked
                ? 'Tarefa criada com o e-mail vinculado.'
                : 'Tarefa criada, mas o e-mail não pôde ser vinculado.', emailLinked ? 'success' : 'error');
            }
            if (onTaskCreated) onTaskCreated();
          }}
        />
      )}
    </div>
  );
};

// ── Agenda · próximos 7 dias (mesma área do Dashboard: PAC + Google Calendar,
//    clique no evento abre o modal "transformar em tarefa") ───────────────────
const EVENT_TYPE_LABEL = { meeting: 'Reunião', hearing: 'Audiência', deadline: 'Prazo', internal: 'Interno', signing: 'Assinatura' };

const AgendaSection = ({ users, reloadKey, onNovoEvento, onTaskCreated }) => {
  const EventToTaskModal = window.EventToTaskModal || null;
  const [events, setEvents] = React.useState([]);
  const [googleEvents, setGoogleEvents] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [taskFromEvent, setTaskFromEvent] = React.useState(null);
  const [refs, setRefs] = React.useState({ clients: [], cases: [] }); // p/ modal

  const hoje = pIsoDay();

  React.useEffect(() => {
    setLoading(true);
    const [y, m, d] = hoje.split('-').map(Number);
    const from = new Date(y, m - 1, d, 0, 0, 0).toISOString();
    const to = new Date(y, m - 1, d + 7, 23, 59, 59).toISOString();
    window.PACApi.events.list({ from, to })
      .then(evs => setEvents(evs || [])).catch(() => {}).finally(() => setLoading(false));

    // Google Calendar em paralelo, sem bloquear (mesmo padrão do Dashboard)
    window.PACApi.calendar.getGoogleEvents()
      .then(evs => {
        if (!evs?.length) return;
        const now = new Date();
        const limit = new Date(now); limit.setDate(now.getDate() + 7);
        setGoogleEvents(evs.filter(e => {
          if (!e.starts_at) return false;
          const dt = new Date(e.starts_at);
          return dt >= now && dt <= limit;
        }));
      })
      .catch(() => {});
  }, [reloadKey]);

  const openEvent = async (ev) => {
    if (!EventToTaskModal) return;
    // Clientes/casos só são necessários dentro do modal — carrega sob demanda
    if (refs.clients.length === 0 && refs.cases.length === 0) {
      const [clients, cases] = await Promise.all([
        window.PACApi.clients.list().catch(() => []),
        window.PACApi.cases.list().catch(() => []),
      ]);
      setRefs({ clients: clients || [], cases: cases || [] });
    }
    setTaskFromEvent(ev);
  };

  const allAgenda = [
    ...events.map(e => ({ ...e, _src: 'pac' })),
    ...googleEvents.map(e => ({ ...e, _src: 'google' })),
  ].sort((a, b) => new Date(a.starts_at) - new Date(b.starts_at));

  const fmtTime = (iso) => new Date(iso).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });

  return (
    <div className="panel" style={{ padding: 14 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 10 }}>
        <h3 style={{ fontSize: 14.5, fontWeight: 700, color: 'var(--pac-navy, #0D0D6B)' }}>Agenda · próximos 7 dias</h3>
        {googleEvents.length > 0 && (
          <span title="Inclui Google Calendar" style={{ fontSize: 10, background: 'rgba(66,133,244,.1)', color: '#4285F4', borderRadius: 4, padding: '1px 6px', fontWeight: 600 }}>G</span>
        )}
        <span style={{ fontSize: 11, color: 'var(--fg-muted, #9ca3af)', fontWeight: 600 }}>{allAgenda.length}</span>
        <button className="tb-ic-btn" aria-label="Novo evento" onClick={onNovoEvento} style={{ marginLeft: 'auto', width: 26, height: 26 }}>
          <Icon name="plus" size={14} />
        </button>
      </div>
      {loading ? (
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted)' }}>Carregando…</div>
      ) : allAgenda.length === 0 ? (
        <div style={{ fontSize: 12.5, color: 'var(--fg-muted, #9ca3af)' }}>Nenhum evento agendado para esta semana.</div>
      ) : allAgenda.slice(0, 10).map(ev => (
        <div
          key={`${ev._src}-${ev.id}`}
          onClick={() => openEvent(ev)}
          style={{ display: 'flex', gap: 10, padding: '7px 4px', alignItems: 'flex-start', cursor: EventToTaskModal ? 'pointer' : 'default', borderRadius: 6 }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--surface, #f7f7fa)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
        >
          <div style={{ width: 40, textAlign: 'center', flexShrink: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--pac-navy, #0D0D6B)', lineHeight: 1.1 }}>{pFmtShort(ev.starts_at?.slice(0, 10))}</div>
            <div style={{ fontSize: 10, color: 'var(--fg-muted, #9ca3af)' }}>{fmtTime(ev.starts_at)}</div>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{ev.title}</div>
            <div style={{ fontSize: 11, color: 'var(--fg-muted, #9ca3af)', display: 'flex', alignItems: 'center', gap: 5 }}>
              {EVENT_TYPE_LABEL[ev.type] || ev.type || 'Evento'}
              {ev._src === 'google' && (
                <span style={{ fontSize: 9.5, color: '#4285F4', background: 'rgba(66,133,244,.08)', borderRadius: 4, padding: '0 4px', fontWeight: 600 }}>G</span>
              )}
            </div>
          </div>
          {EventToTaskModal && (
            <span title="Transformar em tarefa" style={{ fontSize: 10, color: 'var(--fg-muted, #9ca3af)', background: 'var(--surface, #f7f7fa)', borderRadius: 4, padding: '2px 6px', border: '1px solid var(--border, #e8e8f0)', fontWeight: 600, flexShrink: 0 }}>
              + tarefa
            </span>
          )}
        </div>
      ))}

      {taskFromEvent && EventToTaskModal && (
        <EventToTaskModal
          event={taskFromEvent}
          clients={refs.clients}
          cases={refs.cases}
          users={users}
          onClose={() => setTaskFromEvent(null)}
          onCreated={() => { setTaskFromEvent(null); onTaskCreated?.(); }}
        />
      )}
    </div>
  );
};

// ── Cards de resumo (mesmas métricas do dashboard atual) ─────────────────────
const ResumoCards = ({ currentUser }) => {
  const [stats, setStats] = React.useState(null);

  React.useEffect(() => {
    const hoje = pIsoDay();
    const [y, m, d] = hoje.split('-').map(Number);
    const weekFrom = new Date(y, m - 1, d, 0, 0, 0).toISOString();
    const weekTo = new Date(y, m - 1, d + 7, 23, 59, 59).toISOString();
    Promise.all([
      window.PACApi.cases.list().catch(() => []),
      window.PACApi.tasks.list().catch(() => []),
      window.PACApi.events.list({ from: weekFrom, to: weekTo }).catch(() => []),
      window.PACApi.clients.list().catch(() => []),
    ]).then(([cases, tasks, events, clients]) => {
      const open = tasks.filter(t => t.kanban_column !== 'concluido');
      const eventsToday = events.filter(e => e.starts_at.slice(0, 10) === hoje);
      setStats({
        casosAtivos: cases.filter(c => c.status === 'ativo').length,
        clientes: clients.length,
        tarefasAbertas: open.length,
        minhas: open.filter(t => t.owner_user_id === currentUser?.id).length,
        vencendoHoje: open.filter(t => t.due_date === hoje).length,
        eventosSemana: events.length,
        eventosHoje: eventsToday.length,
      });
    });
  }, [currentUser]);

  const card = (label, value, sub, color) => (
    <div className="panel" style={{ flex: 1, minWidth: 170, padding: '14px 16px' }}>
      <div style={{ fontSize: 10.5, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.06em', color: 'var(--fg-muted, #9ca3af)', marginBottom: 6 }}>{label}</div>
      <div style={{ fontSize: 26, fontWeight: 800, color: color || 'var(--pac-navy, #0D0D6B)', lineHeight: 1 }}>{value ?? '—'}</div>
      <div style={{ fontSize: 11.5, color: 'var(--fg-muted, #9ca3af)', marginTop: 5 }}>{sub}</div>
    </div>
  );

  return (
    <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', marginBottom: 16 }}>
      {card('Casos ativos', stats?.casosAtivos, `${stats?.clientes ?? '—'} clientes cadastrados`)}
      {card('Tarefas abertas', stats?.tarefasAbertas, `${stats?.minhas ?? '—'} sob minha responsabilidade`)}
      {card('Vencendo hoje', stats?.vencendoHoje, 'Atenção requerida', stats?.vencendoHoje > 0 ? '#dc2626' : undefined)}
      {card('Eventos esta semana', stats?.eventosSemana, `${stats?.eventosHoje ?? '—'} hoje`)}
    </div>
  );
};

// ── Modais de criação rápida ──────────────────────────────────────────────────
const NovaTarefaModal = ({ open, onClose, currentUser, onCreated, showToast }) => {
  const [title, setTitle] = React.useState('');
  const [due, setDue] = React.useState(pIsoDay());
  const [prio, setPrio] = React.useState('Média');
  const [busy, setBusy] = React.useState(false);

  const create = async () => {
    if (!title.trim()) return;
    setBusy(true);
    try {
      await window.PACApi.tasks.create({ title: title.trim(), due_date: due || undefined, priority: prio, owner_user_id: currentUser?.id });
      showToast('Tarefa criada.');
      setTitle(''); setDue(pIsoDay()); setPrio('Média');
      onCreated(); onClose();
    } catch (e) { showToast(e.message || 'Erro ao criar tarefa.'); }
    finally { setBusy(false); }
  };

  return (
    <PQuickModal title="Nova tarefa" open={open} onClose={onClose}>
      <input autoFocus value={title} onChange={e => setTitle(e.target.value)} onKeyDown={e => e.key === 'Enter' && create()} placeholder="Nome da tarefa *"
        style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '9px 12px', fontSize: 13.5, marginBottom: 10, outline: 'none' }} />
      <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
        <input type="date" value={due} onChange={e => setDue(e.target.value)}
          style={{ flex: 1, border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '8px 10px', fontSize: 13 }} />
        <select value={prio} onChange={e => setPrio(e.target.value)}
          style={{ flex: 1, border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '8px 10px', fontSize: 13, background: '#fff' }}>
          {['Alta', 'Média', 'Baixa'].map(p => <option key={p} value={p}>{p}</option>)}
        </select>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <button className="btn ghost sm" onClick={onClose}>Cancelar</button>
        <button className="btn sm" disabled={busy || !title.trim()} onClick={create}>{busy ? 'Criando…' : 'Criar tarefa'}</button>
      </div>
    </PQuickModal>
  );
};

const NovoEventoModal = ({ open, onClose, onCreated, showToast }) => {
  const [title, setTitle] = React.useState('');
  const [dia, setDia] = React.useState(pIsoDay());
  const [hora, setHora] = React.useState('09:00');
  const [dur, setDur] = React.useState(60);
  const [type, setType] = React.useState('meeting');
  const [busy, setBusy] = React.useState(false);

  const create = async () => {
    if (!title.trim()) return;
    setBusy(true);
    try {
      const [y, m, d] = dia.split('-').map(Number);
      const [hh, mm] = hora.split(':').map(Number);
      const starts = new Date(y, m - 1, d, hh, mm);
      const ends = new Date(starts.getTime() + dur * 60000);
      await window.PACApi.events.create({ title: title.trim(), type, starts_at: starts.toISOString(), ends_at: ends.toISOString() });
      showToast('Evento criado.');
      setTitle('');
      onCreated(); onClose();
    } catch (e) { showToast(e.message || 'Erro ao criar evento.'); }
    finally { setBusy(false); }
  };

  return (
    <PQuickModal title="Novo evento" open={open} onClose={onClose}>
      <input autoFocus value={title} onChange={e => setTitle(e.target.value)} placeholder="Título do evento *"
        style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '9px 12px', fontSize: 13.5, marginBottom: 10, outline: 'none' }} />
      <div style={{ display: 'flex', gap: 8, marginBottom: 10 }}>
        <input type="date" value={dia} onChange={e => setDia(e.target.value)} style={{ flex: 1.4, border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '8px 10px', fontSize: 13 }} />
        <input type="time" value={hora} onChange={e => setHora(e.target.value)} style={{ flex: 1, border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '8px 10px', fontSize: 13 }} />
        <select value={dur} onChange={e => setDur(Number(e.target.value))} style={{ flex: 1, border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '8px 10px', fontSize: 13, background: '#fff' }}>
          <option value={30}>30 min</option><option value={60}>1h</option><option value={90}>1h30</option><option value={120}>2h</option>
        </select>
      </div>
      <select value={type} onChange={e => setType(e.target.value)} style={{ width: '100%', boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 7, padding: '8px 10px', fontSize: 13, background: '#fff', marginBottom: 14 }}>
        {Object.entries(EVENT_TYPE_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
      </select>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <button className="btn ghost sm" onClick={onClose}>Cancelar</button>
        <button className="btn sm" disabled={busy || !title.trim()} onClick={create}>{busy ? 'Criando…' : 'Criar evento'}</button>
      </div>
    </PQuickModal>
  );
};

// ── View principal ────────────────────────────────────────────────────────────
const MeuPainel = ({ user, onNavigate }) => {
  const [filtro, setFiltro] = React.useState({ tipo: 'hoje' });
  const [palavraInput, setPalavraInput] = React.useState('');
  const [palavra, setPalavra] = React.useState('');
  const [users, setUsers] = React.useState([]);
  const [reloadKey, setReloadKey] = React.useState(0);
  const [openTaskId, setOpenTaskId] = React.useState(null);
  const [modalTarefa, setModalTarefa] = React.useState(false);
  const [modalEvento, setModalEvento] = React.useState(false);
  const [showToast, toastNode] = usePToast();

  const reload = React.useCallback(() => setReloadKey(k => k + 1), []);
  const navigate = (view, id) => onNavigate?.(view, id);

  // Debounce 300ms da busca por palavra
  React.useEffect(() => {
    const t = setTimeout(() => setPalavra(palavraInput.trim()), 300);
    return () => clearTimeout(t);
  }, [palavraInput]);

  React.useEffect(() => {
    window.PACApi.users.list().then(us => setUsers(us || [])).catch(() => {});
  }, []);

  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Bom dia' : hour < 18 ? 'Boa tarde' : 'Boa noite';
  const firstName = (user?.name || '').split(' ')[0];
  const todayLabel = new Date().toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });

  return (
    <div style={{ padding: '1.5rem', maxWidth: 1280, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16, flexWrap: 'wrap', marginBottom: 16 }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <div style={{ fontSize: 11, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--fg-muted, #9ca3af)' }}>{todayLabel}</div>
          <h1 style={{ fontSize: '1.5rem', fontWeight: 800, color: 'var(--pac-navy, #0D0D6B)', margin: '2px 0 0' }}>{greeting}, {firstName}.</h1>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <div style={{ position: 'relative' }}>
            <Icon name="search" size={13} style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', color: 'var(--fg-muted, #9ca3af)' }} />
            <input
              value={palavraInput}
              onChange={e => setPalavraInput(e.target.value)}
              placeholder="Filtrar por palavra…"
              aria-label="Filtrar tarefas e casos por palavra"
              style={{ width: 200, boxSizing: 'border-box', border: '1px solid var(--border, #e8e8f0)', borderRadius: 8, padding: '8px 10px 8px 30px', fontSize: 13, outline: 'none', background: '#fff' }}
            />
          </div>
          <AdicionarDropdown
            onNovaTarefa={() => setModalTarefa(true)}
            onNovoEvento={() => setModalEvento(true)}
            onNavigate={navigate}
          />
          <PAvatar user={user} size={34} />
        </div>
      </div>

      {/* Cards de resumo */}
      <ResumoCards currentUser={user} />

      {/* Duas colunas */}
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 300px', gap: 16, alignItems: 'start' }} className="painel-cols">
        <style>{`@media (max-width: 900px){ .painel-cols { grid-template-columns: 1fr !important; } }`}</style>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minWidth: 0 }}>
          <TarefasSection
            filtro={filtro} palavra={palavra} users={users} currentUser={user}
            reloadKey={reloadKey} onReload={reload} onOpenTask={setOpenTaskId} showToast={showToast}
          />
          <CardsRecentesSection
            palavra={palavra} users={users} reloadKey={reloadKey}
            onOpenTask={setOpenTaskId} onNavigate={navigate}
            onTaskCreated={reload} showToast={showToast}
          />
          {/* Feed logo abaixo dos cards (no lugar do antigo "Fluxos favoritos") */}
          {window.GlobalFeedPanel && <window.GlobalFeedPanel currentUser={user} />}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <MiniCalendario filtro={filtro} onFiltro={setFiltro} />
          <AgendaSection users={users} reloadKey={reloadKey} onNovoEvento={() => setModalEvento(true)} onTaskCreated={reload} />
          {window.DashTodo && <window.DashTodo />}
        </div>
      </div>

      {openTaskId && (
        <TarefaDetailSheet taskId={openTaskId} users={users} onClose={() => setOpenTaskId(null)} onChanged={reload} showToast={showToast} />
      )}
      <NovaTarefaModal open={modalTarefa} onClose={() => setModalTarefa(false)} currentUser={user} onCreated={reload} showToast={showToast} />
      <NovoEventoModal open={modalEvento} onClose={() => setModalEvento(false)} onCreated={reload} showToast={showToast} />
      {toastNode}
    </div>
  );
};

window.MeuPainel = MeuPainel;
