/* global React, BezaLogo, Icon, Pill, Card, Delta, Infotip, fmt,
   PAUTA_MONTH, TEAM, PAUTA_CLIENTS, TASKS, STATUS_META, STATUS_FLOW,
   loadOverrides, saveOverrides, dayOfWeek, isWeekend, WEEKDAY_SHORT, WEEKDAY_LONG,
   TASK_TYPE_META, RAW_DELIVERABLES */
const { useState: useStateP, useEffect: useEffectP, useMemo: useMemoP, useRef: useRefP } = React;

/* ============================================================
   MURAL DA REUNIÃO · alimentado pela transcrição da segunda-feira
   (No produto real, o Claude processa a transcrição e popula isto)
   ============================================================ */
const LAST_MEETING = {
  date: '11 de maio',
  weekday: 'segunda',
  durationMin: 38,
  attendees: ['grazi', 'reinaldy', 'lucas'],
  summary: 'Maio começou pesado por causa do Brady (20 reels). Decidimos puxar a entrega do Soldado pra primeira quinzena pra abrir folga no fim do mês. Reinaldy precisa de mais tempo pra carrosseis do Wanderson, vamos redistribuir banner do Pr. Anderson pro Lucas.',
  decisions: [
    { id: 'd1', text: 'Brady vira prioridade #1 da semana — Lucas dedica 3 dias inteiros nos reels.', who: 'lucas' },
    { id: 'd2', text: 'Banner do Pr. Anderson sai com o Lucas em vez do Reinaldy — Reinaldy fica focado nos 12 carrosseis tirinha do Wanderson.', who: 'reinaldy' },
    { id: 'd3', text: 'Entrega do Soldado de Deus puxada pro dia 18 (em vez de 25).', who: 'grazi' },
  ],
  announcements: [
    { id: 'a1', tone: 'info',    text: 'Cliente novo confirmado: Possmozer USA fechou contrato anual. Onboarding começa dia 20.' },
    { id: 'a2', tone: 'warning', text: 'Atenção: Café Graviola pausou contrato por 60 dias. Não produzir maio/junho.' },
    { id: 'a3', tone: 'success', text: 'Soldado de Deus aprovou todo o mês de abril em 2 dias. Recorde da agência.' },
  ],
  actionItems: [
    { id: 'ai1', text: 'Grazi: revisar copy dos 4 carrosséis do Wanderson até quarta.',     who: 'grazi',    due: 14, done: false },
    { id: 'ai2', text: 'Reinaldy: entregar 6 dos 12 carrosseis tirinha até sexta.',         who: 'reinaldy', due: 16, done: false },
    { id: 'ai3', text: 'Lucas: finalizar 10 reels do Brady até quinta.',                    who: 'lucas',    due: 15, done: false },
    { id: 'ai4', text: 'Todos: nova reunião com Possmozer USA quarta às 16h.',              who: null,       due: 14, done: false },
  ],
  nextMeeting: '18 de maio',
};

/* ============================================================
   APP ROOT
   ============================================================ */
function PautaApp() {
  // viewer (quem está vendo o painel)
  const [viewerId, setViewerId] = useStateP('grazi');
  const [view, setView] = useStateP('hoje');
  const [overrides, setOverrides] = useStateP(() => loadOverrides());
  const [subOverrides, setSubOverrides] = useStateP(() => loadSubOverrides());
  const [openTaskId, setOpenTaskId] = useStateP(null);

  useEffectP(() => { saveOverrides(overrides); }, [overrides]);
  useEffectP(() => { saveSubOverrides(subOverrides); }, [subOverrides]);

  const viewer = TEAM.find(t => t.id === viewerId);

  // tarefas com override aplicado
  const tasksLive = useMemoP(() => TASKS.map(t => ({
    ...t,
    status: overrides[t.id] || t.status,
  })), [overrides]);

  const cycleStatus = (taskId) => {
    setOverrides(prev => {
      const cur = prev[taskId] || TASKS.find(t => t.id === taskId)?.status;
      const idx = STATUS_FLOW.indexOf(cur);
      const next = STATUS_FLOW[(idx + 1) % STATUS_FLOW.length];
      return { ...prev, [taskId]: next };
    });
  };
  const cycleSubStatus = (taskId, subId) => {
    setSubOverrides(prev => {
      const key = `${taskId}::${subId}`;
      const detail = TASK_DETAILS[taskId];
      const original = detail?.subTasks?.find(s => s.id === subId)?.status || 'a-fazer';
      const cur = prev[key] || original;
      const idx = STATUS_FLOW.indexOf(cur);
      const next = STATUS_FLOW[(idx + 1) % STATUS_FLOW.length];
      return { ...prev, [key]: next };
    });
  };
  const resetAll = () => { setOverrides({}); setSubOverrides({}); };

  const openTask = tasksLive.find(t => t.id === openTaskId);

  // métricas gerais do mês
  const stats = useMemoP(() => {
    const total = tasksLive.length;
    const concl = tasksLive.filter(t => t.status === 'publicado' || t.status === 'aprovacao').length;
    const atras = tasksLive.filter(t => t.status === 'atrasada').length;
    const aprov = tasksLive.filter(t => t.status === 'aprovacao').length;
    const fazer = tasksLive.filter(t => t.status === 'a-fazer' || t.status === 'em-andamento').length;
    const pct = total ? Math.round((concl / total) * 100) : 0;
    return { total, concl, atras, aprov, fazer, pct };
  }, [tasksLive]);

  return (
    <div style={{ padding: 'var(--space-6) 0 0' }}>
      <PautaHeader stats={stats} viewer={viewer} setViewerId={setViewerId} onReset={resetAll} />
      <PautaTabs view={view} setView={setView} stats={stats} viewer={viewer} tasks={tasksLive} />

      <div style={{ marginTop: 'var(--space-5)' }}>
        {view === 'hoje'     && <ViewHoje    viewer={viewer} tasks={tasksLive} onCycle={cycleStatus} onOpen={setOpenTaskId} />}
        {view === 'semana'   && <ViewSemana  viewer={viewer} tasks={tasksLive} onCycle={cycleStatus} onOpen={setOpenTaskId} />}
        {view === 'clientes' && <ViewClientes tasks={tasksLive} onOpen={setOpenTaskId} />}
        {view === 'time'     && <ViewTime    tasks={tasksLive} />}
        {view === 'reuniao'  && <ViewReuniao />}
      </div>

      <TaskDetailDrawer
        open={!!openTask}
        task={openTask}
        subOverrides={subOverrides}
        onCycleSub={cycleSubStatus}
        onCycle={cycleStatus}
        onClose={() => setOpenTaskId(null)}
      />
    </div>
  );
}

/* ============================================================
   HEADER · mês + integração + viewer switcher
   ============================================================ */
function PautaHeader({ stats, viewer, setViewerId, onReset }) {
  return (
    <div style={{
      padding: 'var(--space-6)',
      background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
      border: '1px solid var(--border-strong)',
      borderRadius: 'var(--r-card-lg)',
      position: 'relative',
      overflow: 'hidden',
      marginBottom: 'var(--space-5)',
    }}>
      <div aria-hidden="true" style={{
        position: 'absolute', top: '-30%', right: '-10%',
        width: 500, height: 500, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(154,155,229,0.18), transparent 60%)',
        filter: 'blur(40px)', pointerEvents: 'none',
      }} />

      <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: 'minmax(0, 1.3fr) minmax(0, 1fr)', gap: 'var(--space-6)', alignItems: 'flex-start', flexWrap: 'wrap' }}>
        <div style={{ minWidth: 0 }}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>
            Módulo · Pauta · {PAUTA_MONTH.label} de {PAUTA_MONTH.year}
          </div>
          <h2 className="t-h1" style={{ margin: '0 0 14px', color: 'var(--text)', textWrap: 'pretty' }}>
            <span className="t-light">Hoje é </span>
            <span className="punch">{PAUTA_MONTH.todayDay} de {PAUTA_MONTH.label.toLowerCase()}</span>
            <span className="t-light">. Faltam </span>
            <span className="punch num">{PAUTA_MONTH.workDeadline - PAUTA_MONTH.todayDay}</span>
            <span className="t-light"> dias até a entrega dos radares.</span>
          </h2>

          {/* Progresso geral */}
          <div style={{ marginTop: 18, maxWidth: 580 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
              <span className="t-overline" style={{ color: 'var(--text-faint)' }}>Pauta do mês · {stats.concl} de {stats.total} entregas</span>
              <span className="num" style={{ fontSize: 22, fontWeight: 500, color: 'var(--text)' }}>{stats.pct}%</span>
            </div>
            <div style={{
              height: 12, background: 'var(--surface-soft)',
              borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)',
            }}>
              <div style={{
                height: '100%', width: stats.pct + '%',
                background: 'linear-gradient(90deg, var(--beza-purple), var(--beza-deep))',
                borderRadius: 999,
                transition: 'width var(--t-slow) var(--ease-out)',
              }} />
            </div>
            <div style={{ marginTop: 10, display: 'flex', gap: 16, fontSize: 12, color: 'var(--text-muted)', flexWrap: 'wrap' }}>
              <span><span style={dot('#F34D4D')} /> {stats.atras} atrasadas</span>
              <span><span style={dot('#F3AE4D')} /> {stats.aprov} em aprovação</span>
              <span><span style={dot('#9A9BE5')} /> {stats.fazer} a fazer/fazendo</span>
              <span><span style={dot('#6FC878')} /> {stats.concl} concluídas</span>
            </div>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, minWidth: 280 }}>
          <ViewerSwitcher viewer={viewer} setViewerId={setViewerId} />
          <SyncPanel onReset={onReset} />
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   SYNC PANEL · auto-refresh ClickUp + status integrações
   ============================================================ */
function SyncPanel({ onReset }) {
  const SYNC_INTERVAL = 300; // 5 min
  const [secondsLeft, setSecondsLeft] = useStateP(SYNC_INTERVAL);
  const [syncing, setSyncing] = useStateP(false);
  const [lastSync, setLastSync] = useStateP('agora');

  useEffectP(() => {
    const id = setInterval(() => {
      setSecondsLeft(prev => {
        if (prev <= 1) {
          setSyncing(true);
          setTimeout(() => {
            setSyncing(false);
            setLastSync('agora');
          }, 1400);
          return SYNC_INTERVAL;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(id);
  }, []);

  // contador de "há X minutos" desde última sync
  useEffectP(() => {
    if (lastSync === 'agora') {
      const elapsed = SYNC_INTERVAL - secondsLeft;
      const min = Math.floor(elapsed / 60);
      if (min > 0) setLastSync(`há ${min} min`);
    }
  }, [secondsLeft, lastSync]);

  const triggerSync = () => {
    setSyncing(true);
    setTimeout(() => {
      setSyncing(false);
      setLastSync('agora');
      setSecondsLeft(SYNC_INTERVAL);
    }, 1400);
  };

  const mm = Math.floor(secondsLeft / 60);
  const ss = String(secondsLeft % 60).padStart(2, '0');

  return (
    <div style={{
      padding: 14,
      background: 'var(--surface-strong)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
      display: 'flex', flexDirection: 'column', gap: 8,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <span className="t-overline" style={{ color: 'var(--text-faint)' }}>Integrações</span>
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={triggerSync} disabled={syncing} style={{
            ...btnGhost,
            color: syncing ? 'var(--text-faint)' : 'var(--accent)',
            borderColor: syncing ? 'var(--border)' : 'rgba(154,155,229,0.30)',
          }}>
            {syncing ? '⟳ sincronizando…' : '⟳ sincronizar agora'}
          </button>
          <button onClick={onReset} style={btnGhost}>↻ resetar</button>
        </div>
      </div>

      <SyncLine name="ClickUp" subtitle={syncing ? 'puxando tasks do board…' : `${lastSync} · próxima em ${mm}:${ss}`} syncing={syncing} />
      <SyncLine name="Reunião de segunda" subtitle={`última: ${LAST_MEETING.date} · ${LAST_MEETING.durationMin}min`} />
      <SyncLine name="mLabs" subtitle="conectado · alimenta os relatórios mensais" />
      <SyncLine name="Google Calendar" subtitle="conectado · eventos pessoais" />
    </div>
  );
}

function SyncLine({ name, subtitle, syncing }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '6px 0', borderTop: '1px solid var(--border)' }}>
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{name}</div>
        <div style={{ fontSize: 11, color: 'var(--text-faint)', fontVariantNumeric: 'tabular-nums' }}>{subtitle}</div>
      </div>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, color: syncing ? 'var(--warning)' : 'var(--success)' }}>
        <span style={{
          width: 8, height: 8, borderRadius: '50%', background: 'currentColor',
          boxShadow: `0 0 0 3px ${syncing ? 'rgba(243,174,77,0.20)' : 'rgba(111,200,120,0.18)'}`,
          animation: syncing ? 'pulse 1s ease-in-out infinite' : 'none',
        }} />
      </span>
    </div>
  );
}

const dot = (c) => ({
  display: 'inline-block', width: 8, height: 8, borderRadius: '50%',
  background: c, marginRight: 6, verticalAlign: 'middle',
});

const btnGhost = {
  appearance: 'none', border: '1px solid var(--border)',
  background: 'transparent', color: 'var(--text-muted)',
  fontSize: 11, padding: '4px 8px',
  borderRadius: 'var(--r-btn)',
  cursor: 'pointer', fontFamily: 'inherit',
};

function IntegrationLine({ name, status, subtitle }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, padding: '6px 0', borderTop: '1px solid var(--border)' }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{name}</div>
        <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>{subtitle}</div>
      </div>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--success)' }}>
        <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'currentColor', boxShadow: '0 0 0 3px rgba(111,200,120,0.18)' }} />
        {status === 'online' ? 'conectado' : status}
      </span>
    </div>
  );
}

/* ============================================================
   VIEWER SWITCHER · escolhe qual membro do time está vendo
   ============================================================ */
function ViewerSwitcher({ viewer, setViewerId }) {
  return (
    <div style={{
      padding: 14,
      background: 'var(--surface-strong)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-card)',
    }}>
      <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 10 }}>Você está vendo como</div>
      <div style={{ display: 'flex', gap: 8 }}>
        {TEAM.map(t => {
          const active = t.id === viewer.id;
          return (
            <button
              key={t.id}
              onClick={() => setViewerId(t.id)}
              style={{
                flex: 1,
                appearance: 'none',
                background: active ? 'var(--accent-soft)' : 'transparent',
                border: '1px solid',
                borderColor: active ? 'var(--accent)' : 'var(--border)',
                borderRadius: 'var(--r-card)',
                padding: '10px 8px',
                cursor: 'pointer',
                fontFamily: 'inherit',
                display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              }}>
              <div style={{
                width: 28, height: 28, borderRadius: '50%',
                background: t.color, color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontWeight: 500, fontSize: 13,
              }}>{t.avatar}</div>
              <span style={{ fontSize: 12, fontWeight: 500, color: active ? 'var(--accent)' : 'var(--text)' }}>{t.name}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

/* ============================================================
   TABS
   ============================================================ */
function PautaTabs({ view, setView, stats, viewer, tasks }) {
  const today = PAUTA_MONTH.todayDay;
  const myToday = tasks.filter(t => t.dueDay === today && t.assignee === viewer.id).length;
  const meetingItems = LAST_MEETING.actionItems.filter(a => !a.who || a.who === viewer.id).length;

  const tabs = [
    { id: 'hoje',     label: 'Hoje',          badge: myToday > 0 ? myToday : null },
    { id: 'semana',   label: 'Esta semana',   badge: null },
    { id: 'clientes', label: 'Por cliente',   badge: null },
    { id: 'time',     label: 'Por colaborador', badge: null },
    { id: 'reuniao',  label: 'Reunião de segunda', badge: meetingItems > 0 ? meetingItems : null },
  ];
  return (
    <div style={{
      display: 'flex', gap: 6,
      padding: 6,
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 'var(--r-pill)',
      width: 'fit-content',
      flexWrap: 'wrap',
      maxWidth: '100%',
      overflowX: 'auto',
    }}>
      {tabs.map(tab => {
        const active = view === tab.id;
        return (
          <button key={tab.id} onClick={() => setView(tab.id)} style={{
            appearance: 'none', border: 'none',
            background: active ? 'var(--accent)' : 'transparent',
            color: active ? '#fff' : 'var(--text-muted)',
            padding: '8px 16px', fontSize: 13,
            fontWeight: active ? 500 : 400,
            borderRadius: 'var(--r-pill)', cursor: 'pointer',
            fontFamily: 'inherit', whiteSpace: 'nowrap',
            display: 'inline-flex', alignItems: 'center', gap: 8,
            transition: 'all var(--t-fast)',
          }}>
            {tab.label}
            {tab.badge != null && (
              <span style={{
                background: active ? 'rgba(255,255,255,0.25)' : 'var(--accent)',
                color: '#fff', fontSize: 11, fontWeight: 500,
                padding: '1px 7px', borderRadius: 999,
                fontVariantNumeric: 'tabular-nums', minWidth: 18, textAlign: 'center',
              }}>{tab.badge}</span>
            )}
          </button>
        );
      })}
    </div>
  );
}

/* ============================================================
   TASK CARD · usado em várias views
   ============================================================ */
function TaskCard({ task, onCycle, onOpen, compact = false }) {
  const meta = STATUS_META[task.status];
  const today = PAUTA_MONTH.todayDay;
  const isLate = task.status === 'atrasada';
  const isToday = task.dueDay === today && !['publicado','aprovacao'].includes(task.status);
  const isDone = task.status === 'publicado' || task.status === 'aprovacao';
  const hasDetail = !!TASK_DETAILS[task.id];

  return (
    <div
      onClick={(e) => {
        if (e.target.closest('button')) return;
        onOpen?.(task.id);
      }}
      style={{
        padding: compact ? 12 : 14,
        background: isDone ? 'var(--surface-soft)' : 'var(--surface)',
        border: '1px solid',
        borderColor: isLate ? 'rgba(243,77,77,0.40)' : (isToday ? 'rgba(154,155,229,0.40)' : 'var(--border)'),
        borderRadius: 'var(--r-card)',
        display: 'flex', flexDirection: 'column', gap: 8,
        opacity: isDone ? 0.75 : 1,
        position: 'relative',
        transition: 'transform var(--t-fast), border-color var(--t-fast)',
        cursor: onOpen ? 'pointer' : 'default',
      }}
      onMouseEnter={(e) => {
        if (!onOpen) return;
        e.currentTarget.style.borderColor = isLate ? 'rgba(243,77,77,0.60)' : 'var(--accent)';
        e.currentTarget.style.transform = 'translateY(-1px)';
      }}
      onMouseLeave={(e) => {
        if (!onOpen) return;
        e.currentTarget.style.borderColor = isLate ? 'rgba(243,77,77,0.40)' : (isToday ? 'rgba(154,155,229,0.40)' : 'var(--border)');
        e.currentTarget.style.transform = '';
      }}>
      {/* Faixa lateral colorida do tipo */}
      <div style={{
        position: 'absolute', top: 0, bottom: 0, left: 0, width: 3,
        background: task.typeColor, borderTopLeftRadius: 'var(--r-card)', borderBottomLeftRadius: 'var(--r-card)',
      }} />

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, paddingLeft: 6 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            fontSize: 10, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
            color: task.typeColor,
          }}>
            {task.typeLabel}
          </span>
          {hasDetail && (
            <span style={{
              fontSize: 9, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
              color: 'var(--accent)',
              padding: '2px 6px',
              background: 'var(--accent-soft)',
              borderRadius: 999, border: '1px solid var(--border-strong)',
            }}>
              ✨ exemplo
            </span>
          )}
        </div>
        <button onClick={(e) => { e.stopPropagation(); onCycle?.(task.id); }} style={{
          appearance: 'none', border: '1px solid',
          borderColor: meta.color, background: 'transparent',
          color: meta.color, fontSize: 11, padding: '3px 9px',
          borderRadius: 999, cursor: 'pointer', fontFamily: 'inherit',
          fontWeight: 500, whiteSpace: 'nowrap',
          display: 'inline-flex', alignItems: 'center', gap: 5,
        }}
        title="Clique para alterar status">
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: meta.color }} />
          {meta.label}
        </button>
      </div>

      <div style={{ paddingLeft: 6 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--text)', lineHeight: 1.3, textDecoration: isDone ? 'line-through' : 'none' }}>
          {task.title}
        </div>
        {!compact && (
          <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>
            {task.clientBrand}
          </div>
        )}
      </div>

      <div style={{ paddingLeft: 6, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginTop: 2 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11, color: 'var(--text-faint)' }}>
          <Icon.Calendar width={11} height={11} />
          {isLate ? (
            <span style={{ color: 'var(--error)', fontWeight: 500 }}>
              Atrasada · venceu dia {task.dueDay}
            </span>
          ) : isToday ? (
            <span style={{ color: 'var(--accent)', fontWeight: 500 }}>Vence hoje</span>
          ) : task.dueDay < today ? (
            <span>Entregue dia {task.dueDay}</span>
          ) : (
            <span>Vence dia {task.dueDay} · em {task.dueDay - today}d</span>
          )}
        </div>
        <Assignees primary={task.assignee} support={task.support} />
      </div>

      {task.quantity > 1 && !isDone && (
        <div style={{ paddingLeft: 6 }}>
          <div style={{
            height: 4, background: 'var(--surface-soft)',
            borderRadius: 999, overflow: 'hidden',
            border: '1px solid var(--border)',
          }}>
            <div style={{
              height: '100%', width: task.progress + '%',
              background: meta.color, borderRadius: 999,
              transition: 'width var(--t-base)',
            }} />
          </div>
          <div style={{ fontSize: 10, color: 'var(--text-faint)', marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>
            {task.doneCount} de {task.quantity} prontos
          </div>
        </div>
      )}
    </div>
  );
}

function Assignees({ primary, support }) {
  const all = [primary, ...support];
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: -4 }}>
      {all.map((id, i) => {
        const t = TEAM.find(m => m.id === id);
        if (!t) return null;
        return (
          <span key={id} title={t.name + ' · ' + t.role} style={{
            width: 22, height: 22, borderRadius: '50%',
            background: t.color, color: '#fff',
            border: '2px solid var(--bg-flat)',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 10, fontWeight: 500,
            marginLeft: i === 0 ? 0 : -6,
            opacity: i === 0 ? 1 : 0.85,
          }}>{t.avatar}</span>
        );
      })}
    </div>
  );
}

/* ============================================================
   VIEW · HOJE
   ============================================================ */
function ViewHoje({ viewer, tasks, onCycle, onOpen }) {
  const today = PAUTA_MONTH.todayDay;
  const my = tasks.filter(t => t.assignee === viewer.id);
  const todayTasks = my.filter(t => t.dueDay === today && !['publicado','aprovacao'].includes(t.status));
  const lateTasks = my.filter(t => t.status === 'atrasada');
  const nextTasks = my
    .filter(t => t.dueDay > today && t.dueDay <= today + 3)
    .sort((a,b) => a.dueDay - b.dueDay);
  const inApproval = my.filter(t => t.status === 'aprovacao');
  const meetingItems = LAST_MEETING.actionItems.filter(a => !a.who || a.who === viewer.id);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 2fr) minmax(0, 1fr)', gap: 'var(--space-5)' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
        {/* HOJE */}
        <section>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14, gap: 12 }}>
            <h3 className="t-h2" style={{ margin: 0 }}>
              <span className="t-light">Suas </span>
              <span className="punch">{todayTasks.length} tarefas</span>
              <span className="t-light"> de hoje</span>
            </h3>
            <span className="t-caption" style={{ color: 'var(--text-faint)' }}>
              Clique no status pra avançar ·  a-fazer → fazendo → aprovação → publicado
            </span>
          </div>

          {todayTasks.length === 0 ? (
            <EmptyState
              icon={<Icon.Sparkle width={20} height={20} />}
              title="Sem entregas marcadas pra hoje."
              body="Pode adiantar algo da semana ou descansar."
            />
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
              {todayTasks.map(t => <TaskCard key={t.id} task={t} onCycle={onCycle} onOpen={onOpen} />)}
            </div>
          )}
        </section>

        {/* ATRASADAS */}
        {lateTasks.length > 0 && (
          <section>
            <h3 className="t-h3" style={{ margin: '0 0 14px', color: 'var(--error)' }}>
              {lateTasks.length} atrasada{lateTasks.length === 1 ? '' : 's'} · puxa pra cá primeiro
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
              {lateTasks.map(t => <TaskCard key={t.id} task={t} onCycle={onCycle} onOpen={onOpen} />)}
            </div>
          </section>
        )}

        {/* PRÓXIMOS 3 DIAS */}
        <section>
          <h3 className="t-h3" style={{ margin: '0 0 14px' }}>
            Próximos 3 dias
          </h3>
          {nextTasks.length === 0 ? (
            <EmptyState body="Nada agendado pra os próximos 3 dias." />
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
              {nextTasks.map(t => <TaskCard key={t.id} task={t} onCycle={onCycle} onOpen={onOpen} />)}
            </div>
          )}
        </section>
      </div>

      {/* SIDEBAR */}
      <aside style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
        <PersonalSpace viewer={viewer} />

        {/* Reunião */}
        <div style={cardSurfacePauta}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 10 }}>
            Da reunião de {LAST_MEETING.weekday}
          </div>
          <h4 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 500, color: 'var(--text)' }}>
            {meetingItems.length} ação{meetingItems.length === 1 ? '' : 'es'} pra você
          </h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {meetingItems.map(ai => (
              <div key={ai.id} style={{
                padding: 10,
                background: 'var(--surface-soft)',
                border: '1px solid var(--border)',
                borderRadius: 'var(--r-btn)',
                fontSize: 12, color: 'var(--text)', lineHeight: 1.4,
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8, marginBottom: 4 }}>
                  <span className="t-overline" style={{ color: 'var(--text-faint)' }}>vence dia {ai.due}</span>
                  {ai.who && <Pill tone="purple">{TEAM.find(t => t.id === ai.who)?.name}</Pill>}
                </div>
                {ai.text}
              </div>
            ))}
          </div>
        </div>

        {/* Em aprovação */}
        {inApproval.length > 0 && (
          <div style={cardSurfacePauta}>
            <div className="t-overline" style={{ color: 'var(--warning)', marginBottom: 10 }}>
              Em aprovação · {inApproval.length}
            </div>
            <p style={{ margin: '0 0 12px', fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>
              Aguardando o cliente aprovar. Quando aprovar, marca como publicado.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {inApproval.map(t => (
                <button key={t.id} onClick={() => onCycle(t.id)} style={{
                  appearance: 'none', textAlign: 'left',
                  padding: 10,
                  background: 'var(--surface-soft)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--r-btn)',
                  cursor: 'pointer', fontFamily: 'inherit',
                  display: 'flex', flexDirection: 'column', gap: 4,
                }}>
                  <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{t.title}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{t.clientBrand}</span>
                </button>
              ))}
            </div>
          </div>
        )}
      </aside>
    </div>
  );
}

const cardSurfacePauta = {
  padding: 'var(--space-4)',
  background: 'var(--surface)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--r-card-lg)',
  backdropFilter: 'blur(20px)',
};

function EmptyState({ icon, title, body }) {
  return (
    <div style={{
      padding: 'var(--space-5)',
      background: 'var(--surface-soft)',
      border: '1px dashed var(--border-strong)',
      borderRadius: 'var(--r-card-lg)',
      textAlign: 'center', color: 'var(--text-muted)',
    }}>
      {icon && <div style={{ marginBottom: 8, color: 'var(--accent)' }}>{icon}</div>}
      {title && <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text)', marginBottom: 4 }}>{title}</div>}
      {body && <div style={{ fontSize: 13 }}>{body}</div>}
    </div>
  );
}

/* ============================================================
   VIEW · SEMANA · kanban Seg–Sex do viewer
   ============================================================ */
function ViewSemana({ viewer, tasks, onCycle, onOpen }) {
  const today = PAUTA_MONTH.todayDay;
  // calcula o início da semana (segunda) atual
  const todayDow = dayOfWeek(today);
  const mondayDay = today - todayDow;
  const weekDays = [0,1,2,3,4].map(i => mondayDay + i);

  const my = tasks.filter(t => t.assignee === viewer.id);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18, gap: 12 }}>
        <h3 className="t-h2" style={{ margin: 0 }}>
          <span className="t-light">Semana de </span>
          <span className="punch">{viewer.name}</span>
        </h3>
        <span className="t-caption" style={{ color: 'var(--text-faint)' }}>
          {mondayDay > 0 ? `${mondayDay}` : `${mondayDay + 30}/abr`} – {weekDays[4]} de {PAUTA_MONTH.label}
        </span>
      </div>

      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(5, minmax(160px, 1fr))',
        gap: 12,
        overflowX: 'auto',
      }}>
        {weekDays.map((d, i) => {
          const dayTasks = my.filter(t => t.dueDay === d);
          const isToday = d === today;
          const isPast = d < today;
          return (
            <div key={d} style={{
              display: 'flex', flexDirection: 'column', gap: 8,
              padding: 12,
              background: isToday ? 'var(--accent-soft)' : 'var(--surface-soft)',
              border: '1px solid',
              borderColor: isToday ? 'var(--accent)' : 'var(--border)',
              borderRadius: 'var(--r-card)',
              minHeight: 200,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: isToday ? 'var(--accent)' : 'var(--text-faint)', fontWeight: 500 }}>
                  {WEEKDAY_SHORT[i]}
                </span>
                <span className="num" style={{ fontSize: 22, fontWeight: isToday ? 500 : 400, color: isToday ? 'var(--accent)' : (isPast ? 'var(--text-faint)' : 'var(--text)') }}>
                  {d > 0 && d <= 31 ? d : '·'}
                </span>
              </div>
              {dayTasks.length === 0 ? (
                <span style={{ fontSize: 12, color: 'var(--text-faint)', marginTop: 8 }}>—</span>
              ) : (
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {dayTasks.map(t => <TaskCard key={t.id} task={t} onCycle={onCycle} onOpen={onOpen} compact />)}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ============================================================
   VIEW · CLIENTES · progresso de cada cliente até 100%
   ============================================================ */
function ViewClientes({ tasks, onOpen }) {
  const clients = PAUTA_CLIENTS.map(c => {
    const myTasks = tasks.filter(t => t.clientId === c.id);
    const total = myTasks.length;
    const done = myTasks.filter(t => t.status === 'publicado' || t.status === 'aprovacao').length;
    const atr  = myTasks.filter(t => t.status === 'atrasada').length;
    const pct  = total ? Math.round((done / total) * 100) : 0;
    return { ...c, myTasks, total, done, atr, pct };
  });

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 18, gap: 12 }}>
        <h3 className="t-h2" style={{ margin: 0 }}>
          <span className="t-light">Progresso por </span>
          <span className="punch">cliente</span>
        </h3>
        <span className="t-caption" style={{ color: 'var(--text-faint)' }}>
          Quando bater 100%, o relatório do mês fecha automaticamente.
        </span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(360px, 1fr))', gap: 12 }}>
        {clients.map(c => <ClientProgressCard key={c.id} client={c} onOpen={onOpen} />)}
      </div>
    </div>
  );
}

function ClientProgressCard({ client, onOpen }) {
  const [expanded, setExpanded] = useStateP(false);
  const isComplete = client.pct === 100;
  const hasLate = client.atr > 0;

  return (
    <div style={{
      padding: 16,
      background: 'var(--surface)',
      border: '1px solid',
      borderColor: hasLate ? 'rgba(243,77,77,0.30)' : (isComplete ? 'rgba(111,200,120,0.30)' : 'var(--border)'),
      borderRadius: 'var(--r-card-lg)',
      display: 'flex', flexDirection: 'column', gap: 12,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12 }}>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 2 }}>
            {client.contact}
          </div>
          <h4 style={{ margin: 0, fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>
            {client.brand}
          </h4>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="num" style={{ fontSize: 24, fontWeight: 500, color: isComplete ? 'var(--success)' : 'var(--text)', lineHeight: 1 }}>
            {client.pct}%
          </div>
          <div className="t-caption" style={{ color: 'var(--text-faint)' }}>
            {client.done} de {client.total}
          </div>
        </div>
      </div>

      <p style={{ margin: 0, fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
        {client.summary}
      </p>

      <div style={{
        height: 8, background: 'var(--surface-soft)',
        borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)',
      }}>
        <div style={{
          height: '100%', width: client.pct + '%',
          background: hasLate ? 'linear-gradient(90deg, #F34D4D, #F3AE4D)' : (isComplete ? '#6FC878' : 'linear-gradient(90deg, var(--beza-purple), var(--beza-deep))'),
          borderRadius: 999,
          transition: 'width var(--t-slow)',
        }} />
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {client.atr > 0 && <Pill tone="error">{client.atr} atrasada{client.atr === 1 ? '' : 's'}</Pill>}
          {client.hasRoteiro && <Pill tone="purple">Tem roteiro</Pill>}
          {isComplete && <Pill tone="success">Pronto pra cliente</Pill>}
        </div>
        <button onClick={() => setExpanded(!expanded)} style={{
          appearance: 'none', border: 'none', background: 'transparent',
          color: 'var(--accent)', fontSize: 12, fontWeight: 500,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>
          {expanded ? 'Recolher' : 'Ver tarefas'} →
        </button>
      </div>

      {expanded && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 4, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
          {client.myTasks.map(t => (
            <div
              key={t.id}
              onClick={() => onOpen?.(t.id)}
              style={{
                display: 'flex', alignItems: 'center', gap: 10,
                padding: '8px 10px', borderRadius: 'var(--r-btn)',
                background: 'var(--surface-soft)', border: '1px solid var(--border)',
                cursor: 'pointer',
                transition: 'background var(--t-fast), border-color var(--t-fast)',
              }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border)'; }}
            >
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: STATUS_META[t.status].color }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{t.title}</div>
                <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>
                  {STATUS_META[t.status].label} · vence dia {t.dueDay}
                </div>
              </div>
              <Assignees primary={t.assignee} support={t.support} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ============================================================
   VIEW · TIME · gestão · carga de cada um
   ============================================================ */
function ViewTime({ tasks }) {
  return (
    <div>
      <div style={{ marginBottom: 18 }}>
        <h3 className="t-h2" style={{ margin: 0 }}>
          <span className="t-light">Como o </span>
          <span className="punch">time tá indo</span>
        </h3>
        <p style={{ margin: '6px 0 0', fontSize: 13, color: 'var(--text-faint)' }}>
          Visibilidade entre o time. A visão gerencial completa (acompanhamento, datas-chave, demandas novas) vem num módulo separado.
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: 16 }}>
        {TEAM.map(member => {
          const myTasks = tasks.filter(t => t.assignee === member.id);
          const done = myTasks.filter(t => t.status === 'publicado' || t.status === 'aprovacao').length;
          const late = myTasks.filter(t => t.status === 'atrasada').length;
          const inProgress = myTasks.filter(t => t.status === 'em-andamento').length;
          const todo = myTasks.filter(t => t.status === 'a-fazer').length;
          const pct = myTasks.length ? Math.round((done / myTasks.length) * 100) : 0;
          const today = PAUTA_MONTH.todayDay;
          const todayCount = myTasks.filter(t => t.dueDay === today && !['publicado','aprovacao'].includes(t.status)).length;

          return (
            <div key={member.id} style={{
              padding: 20,
              background: 'var(--surface)',
              border: '1px solid var(--border)',
              borderRadius: 'var(--r-card-lg)',
              display: 'flex', flexDirection: 'column', gap: 16,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                <div style={{
                  width: 52, height: 52, borderRadius: '50%',
                  background: member.color, color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontWeight: 500, fontSize: 22,
                }}>{member.avatar}</div>
                <div>
                  <h4 style={{ margin: 0, fontSize: 20, fontWeight: 400, color: 'var(--text)' }}>{member.name}</h4>
                  <div style={{ fontSize: 12, color: 'var(--text-faint)' }}>{member.role}</div>
                </div>
              </div>

              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
                <span className="t-overline" style={{ color: 'var(--text-faint)' }}>Pauta do mês</span>
                <span className="num" style={{ fontSize: 22, fontWeight: 500, color: 'var(--text)' }}>{pct}%</span>
              </div>
              <div style={{ height: 8, background: 'var(--surface-soft)', borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)' }}>
                <div style={{
                  height: '100%', width: pct + '%',
                  background: member.color, borderRadius: 999,
                  transition: 'width var(--t-slow)',
                }} />
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <MemberStat label="Hoje" value={todayCount} color={'var(--accent)'} />
                <MemberStat label="Atrasadas" value={late} color={late > 0 ? 'var(--error)' : 'var(--text-muted)'} />
                <MemberStat label="Fazendo" value={inProgress} />
                <MemberStat label="A fazer" value={todo} />
              </div>

              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 4 }}>
                {Object.entries(myTasks.reduce((acc, t) => {
                  acc[t.typeLabel] = (acc[t.typeLabel] || 0) + 1;
                  return acc;
                }, {})).map(([type, n]) => (
                  <Pill key={type}>{type} · {n}</Pill>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function MemberStat({ label, value, color }) {
  return (
    <div>
      <div className="t-overline" style={{ color: 'var(--text-faint)', fontSize: 10 }}>{label}</div>
      <div className="num" style={{ fontSize: 22, fontWeight: 400, color: color || 'var(--text)', lineHeight: 1.1 }}>{value}</div>
    </div>
  );
}

/* ============================================================
   VIEW · REUNIÃO · mural alimentado pela transcrição
   ============================================================ */
function ViewReuniao() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 2fr) minmax(0, 1fr)', gap: 'var(--space-5)' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
        {/* Header */}
        <div style={{
          padding: 'var(--space-5)',
          background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
          border: '1px solid rgba(154,155,229,0.30)',
          borderRadius: 'var(--r-card-lg)',
        }}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>
            Reunião de {LAST_MEETING.weekday} · {LAST_MEETING.date}
          </div>
          <h3 className="t-h2" style={{ margin: '0 0 14px', textWrap: 'pretty' }}>
            <span className="t-light">A semana foi planejada. </span>
            <span className="punch">Aqui está o resumo.</span>
          </h3>
          <p style={{ margin: 0, fontSize: 15, lineHeight: 1.6, color: 'var(--text-muted)', maxWidth: 760 }}>
            {LAST_MEETING.summary}
          </p>
          <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap', gap: 12 }}>
            <span style={{ fontSize: 12, color: 'var(--text-faint)' }}>
              Duração · {LAST_MEETING.durationMin} min · {LAST_MEETING.attendees.length} presentes
            </span>
            <span style={{ fontSize: 12, color: 'var(--accent)', fontWeight: 500 }}>
              Próxima · {LAST_MEETING.nextMeeting}
            </span>
          </div>
        </div>

        {/* Decisões */}
        <section>
          <h4 className="t-h3" style={{ margin: '0 0 12px' }}>
            <span className="t-overline" style={{ color: 'var(--accent)' }}>01 · </span>
            Decisões
          </h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {LAST_MEETING.decisions.map(d => {
              const who = d.who ? TEAM.find(t => t.id === d.who) : null;
              return (
                <div key={d.id} style={{
                  padding: 14,
                  background: 'var(--surface)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--r-card)',
                  display: 'grid', gridTemplateColumns: '36px 1fr', gap: 14, alignItems: 'flex-start',
                }}>
                  <span style={{
                    width: 28, height: 28, borderRadius: '50%',
                    background: 'var(--accent-soft)', color: 'var(--accent)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 500, fontSize: 13, marginTop: 1,
                  }}>✓</span>
                  <div>
                    <div style={{ fontSize: 14, color: 'var(--text)', lineHeight: 1.5 }}>{d.text}</div>
                    {who && <div style={{ marginTop: 6, display: 'inline-flex' }}><Pill tone="purple">Responsável · {who.name}</Pill></div>}
                  </div>
                </div>
              );
            })}
          </div>
        </section>

        {/* Action items */}
        <section>
          <h4 className="t-h3" style={{ margin: '0 0 12px' }}>
            <span className="t-overline" style={{ color: 'var(--accent)' }}>02 · </span>
            Ações com prazo
          </h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {LAST_MEETING.actionItems.map(ai => {
              const who = ai.who ? TEAM.find(t => t.id === ai.who) : null;
              return (
                <div key={ai.id} style={{
                  padding: 12,
                  background: 'var(--surface-soft)',
                  border: '1px solid var(--border)',
                  borderRadius: 'var(--r-btn)',
                  display: 'flex', alignItems: 'center', gap: 12,
                }}>
                  <span style={{ flex: 1, fontSize: 13, color: 'var(--text)' }}>{ai.text}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-faint)', whiteSpace: 'nowrap' }}>
                    dia {ai.due}
                  </span>
                  {who && (
                    <span style={{
                      width: 24, height: 24, borderRadius: '50%',
                      background: who.color, color: '#fff',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontWeight: 500, fontSize: 11,
                    }}>{who.avatar}</span>
                  )}
                </div>
              );
            })}
          </div>
        </section>
      </div>

      {/* Avisos / sidebar */}
      <aside style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
        <section>
          <h4 className="t-h3" style={{ margin: '0 0 12px' }}>
            <span className="t-overline" style={{ color: 'var(--accent)' }}>03 · </span>
            Avisos do mural
          </h4>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {LAST_MEETING.announcements.map(a => {
              const toneMap = {
                info:    { color: 'var(--accent)',  bg: 'rgba(119,184,241,0.08)' },
                warning: { color: 'var(--warning)', bg: 'rgba(243,174,77,0.10)' },
                success: { color: 'var(--success)', bg: 'rgba(111,200,120,0.10)' },
              };
              const t = toneMap[a.tone] || toneMap.info;
              return (
                <div key={a.id} style={{
                  padding: 14,
                  background: t.bg,
                  border: `1px solid ${t.color}`,
                  borderLeft: `3px solid ${t.color}`,
                  borderRadius: 'var(--r-card)',
                  fontSize: 13, color: 'var(--text)', lineHeight: 1.5,
                }}>
                  {a.text}
                </div>
              );
            })}
          </div>
        </section>

        {/* Upload de próxima transcrição */}
        <section style={{
          padding: 'var(--space-4)',
          background: 'var(--surface)',
          border: '1px dashed var(--border-strong)',
          borderRadius: 'var(--r-card-lg)',
        }}>
          <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 8 }}>
            Próxima sincronização
          </div>
          <h5 style={{ margin: '0 0 10px', fontSize: 15, fontWeight: 500 }}>
            Subir transcrição da reunião
          </h5>
          <p style={{ margin: '0 0 14px', fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
            Toda segunda, após a call, cole a transcrição aqui. O Claude vai extrair decisões, ações e avisos automaticamente.
          </p>
          <button style={{
            appearance: 'none', border: '1px solid var(--accent)',
            background: 'var(--accent-soft)', color: 'var(--accent)',
            padding: '10px 14px', borderRadius: 'var(--r-btn)',
            fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
            cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', gap: 8, width: '100%', justifyContent: 'center',
          }}>
            <Icon.Sparkle width={14} height={14} />
            Colar transcrição
          </button>
        </section>
      </aside>
    </div>
  );
}

Object.assign(window, {
  PautaApp, PautaHeader, PautaTabs, ViewerSwitcher, SyncPanel, SyncLine,
  TaskCard, Assignees, TaskDetailDrawer, PersonalSpace,
  ViewHoje, ViewSemana, ViewClientes, ClientProgressCard,
  ViewTime, MemberStat, ViewReuniao, LAST_MEETING,
});

/* ============================================================
   PERSONAL SPACE · espaço pessoal por colaborador
   ----
   Cada pessoa do time tem o próprio bloco: foco do dia, notas
   livres, lembretes pessoais (que NÃO são tarefas de cliente),
   atalhos pra colocar coisas no calendário.
   ============================================================ */
const FOCUS_OPTIONS = [
  { id: 'focus',     label: 'Em foco',         emoji: '🎯', color: '#9A9BE5', subtitle: 'modo deep work' },
  { id: 'meeting',   label: 'Em reunião',      emoji: '💬', color: '#77B8F1', subtitle: 'não chamem' },
  { id: 'creative',  label: 'Em criação',      emoji: '🎨', color: '#F3AE4D', subtitle: 'fluxo criativo' },
  { id: 'tired',     label: 'Cansado',         emoji: '☕', color: '#8B89A3', subtitle: 'tirando o pé' },
  { id: 'available', label: 'Disponível',      emoji: '✓',  color: '#6FC878', subtitle: 'aceita interrupção' },
];

function PersonalSpace({ viewer }) {
  const [notesMap, setNotesMap] = useStateP(() => loadNotes());
  const [personalMap, setPersonalMap] = useStateP(() => loadPersonal());
  const [focusMap, setFocusMap] = useStateP(() => loadFocus());
  const [draft, setDraft] = useStateP('');

  useEffectP(() => { saveNotes(notesMap); }, [notesMap]);
  useEffectP(() => { savePersonal(personalMap); }, [personalMap]);
  useEffectP(() => { saveFocus(focusMap); }, [focusMap]);

  const myNotes = notesMap[viewer.id] || '';
  const myPersonal = personalMap[viewer.id] || [];
  const myFocus = focusMap[viewer.id] || 'available';
  const currentFocus = FOCUS_OPTIONS.find(f => f.id === myFocus);

  const setNotes = (text) => setNotesMap(prev => ({ ...prev, [viewer.id]: text }));
  const setFocus = (id) => setFocusMap(prev => ({ ...prev, [viewer.id]: id }));
  const addPersonal = (text) => {
    if (!text.trim()) return;
    setPersonalMap(prev => ({
      ...prev,
      [viewer.id]: [...(prev[viewer.id] || []), { id: 'p-' + Date.now(), text: text.trim(), done: false, calendar: false }],
    }));
    setDraft('');
  };
  const togglePersonal = (id) => {
    setPersonalMap(prev => ({
      ...prev,
      [viewer.id]: (prev[viewer.id] || []).map(p => p.id === id ? { ...p, done: !p.done } : p),
    }));
  };
  const removePersonal = (id) => {
    setPersonalMap(prev => ({
      ...prev,
      [viewer.id]: (prev[viewer.id] || []).filter(p => p.id !== id),
    }));
  };

  return (
    <div style={{
      padding: 'var(--space-4)',
      background: `linear-gradient(135deg, ${hexToRgba(viewer.color, 0.10)}, ${hexToRgba(viewer.color, 0.02)})`,
      border: `1px solid ${hexToRgba(viewer.color, 0.30)}`,
      borderRadius: 'var(--r-card-lg)',
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 32, height: 32, borderRadius: '50%',
          background: viewer.color, color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontWeight: 500, fontSize: 13,
        }}>{viewer.avatar}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="t-overline" style={{ color: 'var(--text-faint)' }}>Seu espaço</div>
          <h4 style={{ margin: 0, fontSize: 16, fontWeight: 500, color: 'var(--text)' }}>
            {viewer.name}
          </h4>
        </div>
      </div>

      {/* FOCO DO DIA */}
      <div>
        <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 8 }}>Como você está agora</div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
          {FOCUS_OPTIONS.map(f => {
            const active = f.id === myFocus;
            return (
              <button key={f.id} onClick={() => setFocus(f.id)} style={{
                appearance: 'none', border: '1px solid',
                borderColor: active ? f.color : 'var(--border)',
                background: active ? hexToRgba(f.color, 0.12) : 'transparent',
                color: active ? f.color : 'var(--text-muted)',
                padding: '5px 10px', borderRadius: 999,
                fontSize: 12, fontFamily: 'inherit',
                cursor: 'pointer', fontWeight: active ? 500 : 400,
                display: 'inline-flex', alignItems: 'center', gap: 5,
              }}
              title={f.subtitle}>
                <span>{f.emoji}</span>
                {f.label}
              </button>
            );
          })}
        </div>
        {currentFocus && (
          <div style={{ marginTop: 6, fontSize: 11, color: 'var(--text-faint)', fontStyle: 'italic' }}>
            {currentFocus.subtitle} · o time vê seu status
          </div>
        )}
      </div>

      {/* NOTAS LIVRES */}
      <div>
        <div className="t-overline" style={{ color: 'var(--text-faint)', marginBottom: 8 }}>Suas notas</div>
        <textarea
          value={myNotes}
          onChange={(e) => setNotes(e.target.value)}
          placeholder={`Anota aqui, ${viewer.name}. Ideias soltas, decisões, recados, o que precisar. Só você vê.`}
          style={{
            width: '100%', minHeight: 92, resize: 'vertical',
            appearance: 'none', border: '1px solid var(--border)',
            background: 'var(--surface)', color: 'var(--text)',
            padding: '10px 12px', borderRadius: 'var(--r-btn)',
            fontFamily: 'inherit', fontSize: 13, lineHeight: 1.5,
            outline: 'none',
          }}
        />
      </div>

      {/* LEMBRETES PESSOAIS */}
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
          <span className="t-overline" style={{ color: 'var(--text-faint)' }}>Lembretes pessoais</span>
          <span style={{ fontSize: 11, color: 'var(--text-faint)' }}>{myPersonal.filter(p => !p.done).length} ativos</span>
        </div>
        <form onSubmit={(e) => { e.preventDefault(); addPersonal(draft); }} style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
          <input
            type="text"
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            placeholder="+ adicionar lembrete (não-cliente)"
            style={{
              flex: 1, appearance: 'none',
              border: '1px solid var(--border)',
              background: 'var(--surface)', color: 'var(--text)',
              padding: '8px 12px', borderRadius: 'var(--r-btn)',
              fontSize: 13, fontFamily: 'inherit', outline: 'none',
            }}
          />
          <button type="submit" style={{
            appearance: 'none', border: '1px solid',
            borderColor: viewer.color, background: viewer.color, color: '#fff',
            padding: '8px 12px', borderRadius: 'var(--r-btn)',
            fontSize: 12, fontWeight: 500, fontFamily: 'inherit',
            cursor: 'pointer',
          }}>adicionar</button>
        </form>

        {myPersonal.length === 0 ? (
          <div style={{
            padding: 12, textAlign: 'center',
            background: 'var(--surface-soft)',
            border: '1px dashed var(--border)',
            borderRadius: 'var(--r-btn)',
            fontSize: 12, color: 'var(--text-faint)',
          }}>
            Sem lembretes ainda.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {myPersonal.map(p => (
              <div key={p.id} style={{
                display: 'grid', gridTemplateColumns: '22px 1fr auto auto', gap: 10,
                padding: '8px 10px', borderRadius: 'var(--r-btn)',
                background: 'var(--surface)', border: '1px solid var(--border)',
                alignItems: 'center',
              }}>
                <button onClick={() => togglePersonal(p.id)} aria-label="Marcar feito" style={{
                  appearance: 'none', border: '1.5px solid',
                  borderColor: p.done ? viewer.color : 'var(--border-strong)',
                  background: p.done ? viewer.color : 'transparent',
                  color: '#fff', width: 18, height: 18, borderRadius: '50%',
                  cursor: 'pointer', fontFamily: 'inherit', fontSize: 10, fontWeight: 700,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {p.done ? '✓' : ''}
                </button>
                <span style={{
                  fontSize: 13, color: 'var(--text)',
                  textDecoration: p.done ? 'line-through' : 'none',
                  opacity: p.done ? 0.55 : 1,
                  lineHeight: 1.3,
                }}>{p.text}</span>
                <a
                  href={googleCalendarUrl({
                    title: `[Beza · pessoal] ${p.text}`,
                    description: `Lembrete pessoal de ${viewer.name}`,
                    day: PAUTA_MONTH.todayDay,
                  })}
                  target="_blank"
                  rel="noopener noreferrer"
                  title="Adicionar ao Google Calendar"
                  style={{
                    color: 'var(--text-faint)', textDecoration: 'none',
                    padding: 4, display: 'inline-flex',
                  }}>
                  <Icon.Calendar width={14} height={14} />
                </a>
                <button onClick={() => removePersonal(p.id)} aria-label="Remover" style={{
                  appearance: 'none', border: 'none', background: 'transparent',
                  color: 'var(--text-faint)', cursor: 'pointer', padding: 4,
                  fontSize: 14, lineHeight: 1, fontFamily: 'inherit',
                }}>×</button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function hexToRgba(hex, a) {
  const m = hex.match(/^#([0-9a-f]{6})$/i);
  if (!m) return hex;
  const n = parseInt(m[1], 16);
  return `rgba(${(n>>16)&255}, ${(n>>8)&255}, ${n&255}, ${a})`;
}

/* ============================================================
   TASK DETAIL DRAWER · gaveta lateral com o template completo
   ============================================================ */
function TaskDetailDrawer({ open, task, subOverrides, onCycleSub, onCycle, onClose }) {
  useEffectP(() => {
    if (!open) return;
    const onEsc = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onEsc);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onEsc);
      document.body.style.overflow = '';
    };
  }, [open, onClose]);

  if (!task) return null;
  const detail = TASK_DETAILS[task.id] || null;
  const isExample = detail?.isExample;
  const meta = STATUS_META[task.status];
  const client = PAUTA_CLIENTS.find(c => c.id === task.clientId);
  const today = PAUTA_MONTH.todayDay;

  // sub-tasks aplicando overrides
  const subTasks = (detail?.subTasks || []).map(s => ({
    ...s,
    status: subOverrides[`${task.id}::${s.id}`] || s.status,
  }));
  const subDone = subTasks.filter(s => s.status === 'publicado' || s.status === 'aprovacao').length;
  const subPct = subTasks.length ? Math.round((subDone / subTasks.length) * 100) : task.progress;

  return (
    <>
      <div
        aria-hidden={!open}
        onClick={onClose}
        style={{
          position: 'fixed', inset: 0,
          background: 'rgba(8,8,12,0.55)',
          backdropFilter: 'blur(4px)',
          opacity: open ? 1 : 0,
          pointerEvents: open ? 'auto' : 'none',
          transition: 'opacity 250ms var(--ease-out)',
          zIndex: 100,
        }}
      />
      <aside
        role="dialog"
        aria-modal="true"
        aria-label={task.title}
        style={{
          position: 'fixed',
          top: 16, right: 16, bottom: 16,
          width: 'min(640px, calc(100vw - 32px))',
          background: 'var(--bg)',
          color: 'var(--text)',
          border: '1px solid var(--border-strong)',
          borderRadius: 'var(--r-card-lg)',
          boxShadow: 'var(--shadow-xl)',
          transform: open ? 'translateX(0)' : 'translateX(110%)',
          opacity: open ? 1 : 0,
          transition: 'transform 320ms var(--ease-out), opacity 320ms var(--ease-out)',
          zIndex: 101,
          overflow: 'auto',
        }}
      >
        {/* HEADER */}
        <div style={{
          padding: 'var(--space-5) var(--space-5) var(--space-4)',
          borderBottom: '1px solid var(--border)',
          position: 'sticky', top: 0,
          background: 'var(--surface-strong)',
          backdropFilter: 'blur(20px)',
          zIndex: 2,
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 12 }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <span style={{
                  fontSize: 10, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
                  color: task.typeColor, padding: '3px 8px',
                  background: 'var(--surface)', border: '1px solid var(--border)',
                  borderRadius: 999,
                }}>{task.typeLabel}</span>
                {isExample && (
                  <span style={{
                    fontSize: 10, fontWeight: 500, letterSpacing: '0.08em', textTransform: 'uppercase',
                    color: 'var(--accent)', padding: '3px 8px',
                    background: 'var(--accent-soft)', border: '1px solid var(--border-strong)',
                    borderRadius: 999,
                  }}>✨ exemplo · template</span>
                )}
              </div>
              <h2 className="t-h2" style={{ margin: 0, color: 'var(--text)' }}>
                {task.title}
              </h2>
              <div style={{ fontSize: 13, color: 'var(--text-muted)', marginTop: 4 }}>
                {client?.brand} · {client?.contact}
              </div>
            </div>
            <button onClick={onClose} aria-label="Fechar" style={{
              appearance: 'none', border: '1px solid var(--border-strong)',
              background: 'var(--surface)',
              width: 32, height: 32, borderRadius: 999,
              cursor: 'pointer', flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--text-muted)', fontFamily: 'inherit',
            }}>×</button>
          </div>

          {/* Status + progresso */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <button onClick={() => onCycle(task.id)} style={{
                appearance: 'none', border: '1px solid', borderColor: meta.color,
                background: 'transparent', color: meta.color,
                fontSize: 12, padding: '6px 12px', borderRadius: 999,
                cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500,
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                <span style={{ width: 7, height: 7, borderRadius: '50%', background: meta.color }} />
                {meta.label} · clique pra avançar
              </button>
              <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>
                {task.dueDay < today
                  ? `venceu dia ${task.dueDay}`
                  : task.dueDay === today ? 'vence hoje'
                  : `vence dia ${task.dueDay} · em ${task.dueDay - today}d`}
              </span>
            </div>
            <Assignees primary={task.assignee} support={task.support} />
          </div>

          {detail && (
            <div style={{ marginTop: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
                <span className="t-overline" style={{ color: 'var(--text-faint)' }}>Progresso · {subDone}/{subTasks.length} sub-entregas</span>
                <span className="num" style={{ fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>{subPct}%</span>
              </div>
              <div style={{ height: 6, background: 'var(--surface-soft)', borderRadius: 999, overflow: 'hidden', border: '1px solid var(--border)' }}>
                <div style={{
                  height: '100%', width: subPct + '%',
                  background: 'linear-gradient(90deg, var(--beza-purple), var(--beza-deep))',
                  borderRadius: 999, transition: 'width var(--t-slow)',
                }} />
              </div>
            </div>
          )}
        </div>

        {/* CONTEÚDO */}
        <div style={{ padding: 'var(--space-5)', display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
          {!detail ? (
            <DetailTemplate task={task} />
          ) : (
            <>
              <DetailSection kicker="01 · brief" title="Como entregar">
                <p style={{ margin: 0, fontSize: 14, lineHeight: 1.6, color: 'var(--text)' }}>
                  {detail.brief}
                </p>
              </DetailSection>

              <DetailSection kicker="02 · referências" title="Material de apoio">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {detail.references.map((r, i) => (
                    <a key={i} href={r.url} style={{
                      display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
                      padding: '10px 14px', borderRadius: 'var(--r-btn)',
                      background: 'var(--surface)', border: '1px solid var(--border)',
                      textDecoration: 'none', color: 'var(--text)',
                      transition: 'border-color var(--t-fast)',
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent)'}
                    onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border)'}>
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{r.label}</div>
                        {r.meta && <div style={{ fontSize: 11, color: 'var(--text-faint)', marginTop: 2 }}>{r.meta}</div>}
                      </div>
                      <Icon.External width={14} height={14} style={{ color: 'var(--text-faint)', flexShrink: 0 }} />
                    </a>
                  ))}
                </div>
              </DetailSection>

              <DetailSection kicker="03 · sub-entregas" title="Cada peça, individualmente">
                <p className="t-caption" style={{ color: 'var(--text-faint)', margin: '0 0 12px' }}>
                  Clique no status de cada uma pra avançar. A barra de progresso da tarefa atualiza sozinha.
                </p>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                  {subTasks.map((s, i) => {
                    const sMeta = STATUS_META[s.status];
                    const sDone = s.status === 'publicado' || s.status === 'aprovacao';
                    return (
                      <div key={s.id} style={{
                        display: 'grid', gridTemplateColumns: '28px 1fr auto', gap: 12, alignItems: 'center',
                        padding: '10px 12px',
                        background: sDone ? 'var(--surface-soft)' : 'var(--surface)',
                        border: '1px solid var(--border)',
                        borderRadius: 'var(--r-btn)',
                        opacity: sDone ? 0.7 : 1,
                      }}>
                        <button onClick={() => onCycleSub(task.id, s.id)} aria-label={`Status do ${s.label}`} style={{
                          appearance: 'none', border: '1.5px solid', borderColor: sMeta.color,
                          background: sDone ? sMeta.color : 'transparent',
                          color: sDone ? '#fff' : sMeta.color,
                          width: 22, height: 22, borderRadius: '50%',
                          cursor: 'pointer', fontFamily: 'inherit',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontSize: 12, fontWeight: 600,
                        }}>
                          {sDone ? '✓' : ''}
                        </button>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', textDecoration: sDone ? 'line-through' : 'none' }}>
                            {s.label}
                          </div>
                          <div style={{ fontSize: 12, color: 'var(--text-muted)', fontStyle: s.hook?.startsWith('"') ? 'italic' : 'normal' }}>
                            {s.hook}
                          </div>
                        </div>
                        <button onClick={() => onCycleSub(task.id, s.id)} style={{
                          appearance: 'none', border: 'none',
                          background: 'transparent', color: sMeta.color,
                          fontSize: 11, padding: '3px 8px',
                          borderRadius: 999, cursor: 'pointer', fontFamily: 'inherit',
                          fontWeight: 500, whiteSpace: 'nowrap',
                        }}>
                          {sMeta.label}
                        </button>
                      </div>
                    );
                  })}
                </div>
              </DetailSection>

              <DetailSection kicker="04 · conversa do time" title="Comentários">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
                  {detail.comments.map(c => {
                    const who = TEAM.find(t => t.id === c.author);
                    return (
                      <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '32px 1fr', gap: 12, alignItems: 'flex-start' }}>
                        <span style={{
                          width: 28, height: 28, borderRadius: '50%',
                          background: who?.color || 'var(--text-muted)', color: '#fff',
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          fontWeight: 500, fontSize: 11, marginTop: 2,
                        }}>{who?.avatar || '?'}</span>
                        <div style={{
                          padding: '10px 12px',
                          background: 'var(--surface)',
                          border: '1px solid var(--border)',
                          borderRadius: 'var(--r-btn)',
                        }}>
                          <div style={{ fontSize: 11, color: 'var(--text-faint)', marginBottom: 4 }}>
                            <span style={{ fontWeight: 500, color: 'var(--text-muted)' }}>{who?.name}</span> · {c.when}
                          </div>
                          <div style={{ fontSize: 13, color: 'var(--text)', lineHeight: 1.5 }}>{c.text}</div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </DetailSection>

              <DetailSection kicker="05 · histórico" title="Linha do tempo">
                <div style={{ display: 'flex', flexDirection: 'column', gap: 0, position: 'relative' }}>
                  {detail.history.map((h, i) => (
                    <div key={i} style={{
                      display: 'grid', gridTemplateColumns: '90px 1fr', gap: 14,
                      padding: '8px 0',
                      borderTop: i === 0 ? 'none' : '1px solid var(--border)',
                      alignItems: 'baseline',
                    }}>
                      <span style={{ fontSize: 12, color: 'var(--text-faint)', whiteSpace: 'nowrap' }}>{h.when}</span>
                      <span style={{ fontSize: 13, color: 'var(--text)', lineHeight: 1.5 }}>{h.text}</span>
                    </div>
                  ))}
                </div>
              </DetailSection>

              <div style={{
                padding: 'var(--space-4)',
                background: 'linear-gradient(135deg, rgba(154,155,229,0.10), rgba(154,155,229,0.02))',
                border: '1px solid rgba(154,155,229,0.30)',
                borderRadius: 'var(--r-card)',
                display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap',
              }}>
                <div>
                  <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 2 }}>Conectado ao ClickUp</div>
                  <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Mudanças aqui sincronizam com a task original.</span>
                </div>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <a
                    href={googleCalendarUrl({
                      title: `[Beza] ${task.title} · ${client?.brand}`,
                      description: `${detail.brief}\n\nResponsável: ${TEAM.find(t => t.id === task.assignee)?.name}`,
                      day: task.dueDay,
                    })}
                    target="_blank" rel="noopener noreferrer"
                    style={{
                      display: 'inline-flex', alignItems: 'center', gap: 6,
                      color: 'var(--text-muted)', fontSize: 13, fontWeight: 500,
                      padding: '8px 14px', borderRadius: 'var(--r-btn)',
                      border: '1px solid var(--border-strong)',
                      textDecoration: 'none',
                      background: 'var(--surface)',
                    }}>
                    <Icon.Calendar width={14} height={14} />
                    Adicionar ao calendar
                  </a>
                  <a href={detail.clickupLink || '#'} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 6,
                    color: 'var(--accent)', fontSize: 13, fontWeight: 500,
                    padding: '8px 14px', borderRadius: 'var(--r-btn)',
                    border: '1px solid var(--accent)',
                    textDecoration: 'none',
                  }}>
                    Abrir no ClickUp <Icon.External width={14} height={14} />
                  </a>
                </div>
              </div>
            </>
          )}
        </div>
      </aside>
    </>
  );
}

function DetailSection({ kicker, title, children }) {
  return (
    <section>
      <div className="t-overline" style={{ color: 'var(--accent)', marginBottom: 4 }}>{kicker}</div>
      <h3 className="t-h3" style={{ margin: '0 0 12px', color: 'var(--text)' }}>{title}</h3>
      {children}
    </section>
  );
}

function DetailTemplate({ task }) {
  return (
    <div style={{
      padding: 'var(--space-5)',
      background: 'var(--surface)',
      border: '1px dashed var(--border-strong)',
      borderRadius: 'var(--r-card-lg)',
      textAlign: 'center',
    }}>
      <div style={{ marginBottom: 10, color: 'var(--accent)', display: 'inline-flex' }}>
        <Icon.Sparkle width={22} height={22} />
      </div>
      <h3 style={{ margin: '0 0 8px', fontSize: 18, fontWeight: 500, color: 'var(--text)' }}>
        Use o exemplo como template
      </h3>
      <p style={{ margin: '0 auto 16px', fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6, maxWidth: 380 }}>
        Esta tarefa ainda não tem detalhamento. Abra a tarefa marcada com <span style={{ color: 'var(--accent)', fontWeight: 500 }}>✨ exemplo</span> (Reels do Soldado de Deus) pra ver o modelo completo: brief, referências, sub-entregas com check, comentários e histórico. Depois é só duplicar a estrutura aqui.
      </p>
      <div style={{ display: 'inline-flex', flexDirection: 'column', gap: 6, textAlign: 'left', maxWidth: 380, color: 'var(--text-muted)', fontSize: 12 }}>
        <div>· Brief · como entregar essa tarefa</div>
        <div>· Referências · links e materiais de apoio</div>
        <div>· Sub-entregas · {task.quantity > 1 ? task.quantity : 'cada'} peça com seu próprio check</div>
        <div>· Comentários · conversa do time sobre essa entrega</div>
        <div>· Histórico · linha do tempo</div>
        <div>· ClickUp · sincroniza com a task original</div>
      </div>
    </div>
  );
}
