// Wave 5a — Projetos & OS (2 telas)

// =============================================================
// 1. Projetos — Kanban / Lista / Gantt / Calendário
// =============================================================
const PROJETOS = [
  { id: 'PRJ-042', nome: 'Novo site institucional · v3', cliente: 'Bighorse Studio', status: 'em-andamento', prog: 72, prazo: '28/05', prazoDias: 12, equipe: ['AS', 'BO', 'CM'], tarefas: 28, done: 20, sprint: 'Sprint 14', orcamento: 45000, consumido: 32400, tag: 'Web', color: '#8b5cf6' },
  { id: 'PRJ-041', nome: 'Integração ERP → NF-e SEFAZ-MG', cliente: 'Padaria Pão Dourado', status: 'em-andamento', prog: 55, prazo: '10/06', prazoDias: 25, equipe: ['DF', 'ES'], tarefas: 42, done: 23, sprint: 'Sprint 7', orcamento: 28000, consumido: 15400, tag: 'Fiscal', color: '#06b6d4' },
  { id: 'PRJ-040', nome: 'App mobile · cardápio digital', cliente: 'Restaurante Xapuri', status: 'atrasado', prog: 38, prazo: '20/04', prazoDias: -5, equipe: ['FC', 'GA', 'HM'], tarefas: 54, done: 21, sprint: 'Sprint 11', orcamento: 62000, consumido: 58900, tag: 'Mobile', color: '#ef4444' },
  { id: 'PRJ-039', nome: 'Dashboard executivo · Looker', cliente: 'Grupo Três Marias', status: 'em-andamento', prog: 84, prazo: '30/04', prazoDias: 5, equipe: ['IF'], tarefas: 18, done: 15, sprint: 'Sprint 6', orcamento: 18000, consumido: 14200, tag: 'BI', color: '#10b981' },
  { id: 'PRJ-038', nome: 'Migração Cloud AWS · produção', cliente: 'Bighorse Studio', status: 'em-andamento', prog: 22, prazo: '15/07', prazoDias: 58, equipe: ['JB', 'KL', 'LM'], tarefas: 96, done: 21, sprint: 'Sprint 3', orcamento: 120000, consumido: 18600, tag: 'DevOps', color: '#f59e0b' },
  { id: 'PRJ-037', nome: 'Redesign do app de delivery', cliente: 'Padaria Pão Dourado', status: 'revisao', prog: 95, prazo: '22/04', prazoDias: 2, equipe: ['MP', 'NR'], tarefas: 34, done: 33, sprint: 'Sprint 9', orcamento: 52000, consumido: 49800, tag: 'Design', color: '#ec4899' },
  { id: 'PRJ-036', nome: 'Automação fluxo de caixa', cliente: 'Grupo Três Marias', status: 'concluido', prog: 100, prazo: '15/04', prazoDias: -3, equipe: ['OS', 'PR'], tarefas: 22, done: 22, sprint: 'Finalizado', orcamento: 22000, consumido: 21400, tag: 'Finanças', color: '#22c55e' },
  { id: 'PRJ-035', nome: 'Refactor sistema de pedidos', cliente: 'Restaurante Xapuri', status: 'planejamento', prog: 8, prazo: '30/08', prazoDias: 100, equipe: ['QS'], tarefas: 12, done: 1, sprint: 'Backlog', orcamento: 38000, consumido: 1200, tag: 'Web', color: '#64748b' },
];

const PageProjetos = ({ onNavigate }) => {
  const [view, setView] = React.useState('kanban');
  const [selected, setSelected] = React.useState(null);
  const cols = [
    { id: 'planejamento', label: 'Planejamento', color: '#64748b' },
    { id: 'em-andamento', label: 'Em andamento', color: 'var(--accent-1)' },
    { id: 'revisao', label: 'Em revisão', color: '#f59e0b' },
    { id: 'concluido', label: 'Concluído', color: '#22c55e' },
  ];
  const atrasados = PROJETOS.filter(p => p.status === 'atrasado');

  return (
    <AppShell current="projetos" onNavigate={onNavigate}>
      <PageContainer
        title="Projetos"
        subtitle="Kanban, Gantt e timesheet integrados · visibilidade ponta a ponta."
        maxWidth={1720}
        actions={<>
          <button className="btn btn-outline btn-sm"><Icon name="filter" size={13}/> Filtros</button>
          <button className="btn btn-primary btn-sm"><Icon name="plus" size={13}/> Novo projeto</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 18 }}>
          <Tile icon="layers" label="Ativos" value={PROJETOS.filter(p => p.status !== 'concluido' && p.status !== 'atrasado').length} sub={`${PROJETOS.length} no total`}/>
          <Tile icon="alert" label="Atrasados" value={atrasados.length} sub={atrasados.length ? atrasados[0].nome.slice(0, 28) + '…' : '—'} deltaDir="down"/>
          <Tile icon="trending-up" label="Progresso médio" value={Math.round(PROJETOS.filter(p => p.status !== 'concluido').reduce((a, p) => a + p.prog, 0) / PROJETOS.filter(p => p.status !== 'concluido').length) + '%'} sub="projetos em aberto"/>
          <Tile icon="wallet" label="Orçamento consumido" value="58%" sub="R$ 211k de R$ 385k"/>
        </div>

        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14, flexWrap: 'wrap', gap: 10 }}>
          <div style={{ display: 'inline-flex', background: 'var(--bg-2)', border: '1px solid var(--line-2)', borderRadius: 9, padding: 3 }}>
            {[
              { id: 'kanban', l: 'Kanban', i: 'grid' },
              { id: 'lista', l: 'Lista', i: 'list' },
              { id: 'gantt', l: 'Gantt', i: 'bar-chart' },
              { id: 'calendario', l: 'Calendário', i: 'calendar' },
            ].map(v => (
              <button key={v.id} onClick={() => setView(v.id)} style={{
                padding: '6px 12px', borderRadius: 6, fontSize: 12, fontWeight: 500,
                background: view === v.id ? 'var(--bg-3)' : 'transparent',
                color: view === v.id ? 'var(--text-0)' : 'var(--text-3)',
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                <Icon name={v.i} size={12}/> {v.l}
              </button>
            ))}
          </div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 12, color: 'var(--text-3)' }}>
            <span>Agrupar por:</span>
            <select style={{ background: 'var(--bg-2)', border: '1px solid var(--line-2)', borderRadius: 6, color: 'var(--text-1)', padding: '5px 8px', fontSize: 12 }}>
              <option>Status</option><option>Cliente</option><option>Responsável</option>
            </select>
          </div>
        </div>

        {view === 'kanban' && (
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 12 }}>
            {cols.map(c => {
              const items = PROJETOS.filter(p => p.status === c.id || (c.id === 'em-andamento' && p.status === 'atrasado'));
              return (
                <div key={c.id} style={{ background: 'var(--bg-1)', border: '1px solid var(--line-1)', borderRadius: 14, padding: 10, minHeight: 540 }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 6px 10px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ width: 8, height: 8, borderRadius: 2, background: c.color }}/>
                      <span style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-1)' }}>{c.label}</span>
                      <span style={{ fontSize: 11, color: 'var(--text-4)' }}>{items.length}</span>
                    </div>
                    <button style={{ color: 'var(--text-4)', width: 22, height: 22, borderRadius: 5, display: 'grid', placeItems: 'center' }}><Icon name="plus" size={12}/></button>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {items.map(p => (
                      <div key={p.id} onClick={() => setSelected(p)} style={{
                        background: 'var(--bg-2)', border: '1px solid var(--line-2)', borderRadius: 11, padding: 12, cursor: 'pointer',
                        borderLeft: `3px solid ${p.color}`,
                      }}>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                          <span style={{ fontSize: 10, color: 'var(--text-4)', fontFamily: 'JetBrains Mono, monospace' }}>{p.id}</span>
                          {p.status === 'atrasado' && <span style={{ fontSize: 9, padding: '2px 6px', borderRadius: 4, background: 'rgba(239,68,68,.18)', color: '#fca5a5', fontWeight: 600 }}>ATRASADO</span>}
                        </div>
                        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-0)', lineHeight: 1.35, marginBottom: 8 }}>{p.nome}</div>
                        <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 10 }}>{p.cliente}</div>
                        <div style={{ height: 4, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden', marginBottom: 8 }}>
                          <div style={{ width: p.prog + '%', height: '100%', background: p.color }}/>
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11 }}>
                          <div style={{ display: 'flex', gap: -4 }}>
                            {p.equipe.map((a, i) => (
                              <span key={i} style={{
                                width: 22, height: 22, borderRadius: '50%',
                                background: `linear-gradient(135deg, hsl(${i * 50 + 220},60%,55%), hsl(${i * 50 + 260},60%,45%))`,
                                display: 'grid', placeItems: 'center', fontSize: 9, fontWeight: 700, color: '#fff',
                                border: '2px solid var(--bg-2)', marginLeft: i ? -6 : 0,
                              }}>{a}</span>
                            ))}
                          </div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                            <span style={{ color: p.prazoDias < 0 ? '#fca5a5' : p.prazoDias < 10 ? '#fcd34d' : 'var(--text-3)' }}>
                              <Icon name="calendar" size={10}/> {p.prazo}
                            </span>
                            <span style={{ color: 'var(--text-4)' }}>{p.done}/{p.tarefas}</span>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {view === 'lista' && (
          <div className="tile" style={{ padding: 0, overflow: 'hidden' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: 'var(--bg-2)', color: 'var(--text-3)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.05em' }}>
                  <th style={{ textAlign: 'left', padding: '11px 16px', fontWeight: 600 }}>Projeto</th>
                  <th style={{ textAlign: 'left', padding: '11px 14px', fontWeight: 600 }}>Cliente</th>
                  <th style={{ textAlign: 'left', padding: '11px 14px', fontWeight: 600 }}>Progresso</th>
                  <th style={{ textAlign: 'left', padding: '11px 14px', fontWeight: 600 }}>Equipe</th>
                  <th style={{ textAlign: 'left', padding: '11px 14px', fontWeight: 600 }}>Prazo</th>
                  <th style={{ textAlign: 'right', padding: '11px 14px', fontWeight: 600 }}>Orçamento</th>
                  <th style={{ width: 30 }}/>
                </tr>
              </thead>
              <tbody>
                {PROJETOS.map(p => (
                  <tr key={p.id} onClick={() => setSelected(p)} style={{ borderTop: '1px solid var(--line-1)', cursor: 'pointer' }}>
                    <td style={{ padding: '12px 16px' }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-0)' }}>{p.nome}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-4)', fontFamily: 'JetBrains Mono, monospace' }}>{p.id}</div>
                    </td>
                    <td style={{ padding: '12px 14px', color: 'var(--text-2)' }}>{p.cliente}</td>
                    <td style={{ padding: '12px 14px', minWidth: 160 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <div style={{ flex: 1, height: 5, background: 'var(--bg-3)', borderRadius: 3, overflow: 'hidden' }}>
                          <div style={{ width: p.prog + '%', height: '100%', background: p.color }}/>
                        </div>
                        <span style={{ fontSize: 11.5, color: 'var(--text-1)', fontWeight: 600, minWidth: 28, textAlign: 'right' }}>{p.prog}%</span>
                      </div>
                    </td>
                    <td style={{ padding: '12px 14px' }}>
                      <div style={{ display: 'flex' }}>
                        {p.equipe.map((a, i) => (
                          <span key={i} style={{
                            width: 24, height: 24, borderRadius: '50%',
                            background: `linear-gradient(135deg, hsl(${i * 50 + 220},60%,55%), hsl(${i * 50 + 260},60%,45%))`,
                            display: 'grid', placeItems: 'center', fontSize: 10, fontWeight: 700, color: '#fff',
                            border: '2px solid var(--bg-1)', marginLeft: i ? -7 : 0,
                          }}>{a}</span>
                        ))}
                      </div>
                    </td>
                    <td style={{ padding: '12px 14px' }}>
                      <span style={{ color: p.prazoDias < 0 ? '#fca5a5' : p.prazoDias < 10 ? '#fcd34d' : 'var(--text-2)', fontSize: 12.5 }}>
                        {p.prazo} <span style={{ color: 'var(--text-4)' }}>· {p.prazoDias < 0 ? Math.abs(p.prazoDias) + 'd atrasado' : p.prazoDias + 'd'}</span>
                      </span>
                    </td>
                    <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', fontSize: 12 }}>
                      <div style={{ color: 'var(--text-0)' }}>R$ {(p.consumido / 1000).toFixed(1)}k / {(p.orcamento / 1000).toFixed(0)}k</div>
                      <div style={{ fontSize: 10, color: p.consumido / p.orcamento > 0.9 ? '#fca5a5' : 'var(--text-4)' }}>{Math.round(p.consumido / p.orcamento * 100)}% usado</div>
                    </td>
                    <td style={{ padding: '12px 14px', color: 'var(--text-4)' }}><Icon name="chevron-right" size={13}/></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {view === 'gantt' && (
          <div className="tile" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '280px 1fr' }}>
              <div style={{ borderRight: '1px solid var(--line-1)' }}>
                <div style={{ padding: '10px 14px', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--text-3)', fontWeight: 600, borderBottom: '1px solid var(--line-1)', background: 'var(--bg-2)' }}>Projeto</div>
                {PROJETOS.map(p => (
                  <div key={p.id} style={{ padding: '11px 14px', borderBottom: '1px solid var(--line-1)', height: 46 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--text-0)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.nome}</div>
                    <div style={{ fontSize: 10.5, color: 'var(--text-4)' }}>{p.cliente}</div>
                  </div>
                ))}
              </div>
              <div style={{ overflowX: 'auto' }}>
                <div style={{ display: 'flex', borderBottom: '1px solid var(--line-1)', background: 'var(--bg-2)', minWidth: 900 }}>
                  {['abr', 'mai', 'jun', 'jul', 'ago', 'set'].map(m => (
                    <div key={m} style={{ flex: 1, padding: '10px 14px', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--text-3)', fontWeight: 600, textAlign: 'center', borderRight: '1px solid var(--line-1)' }}>{m}/2026</div>
                  ))}
                </div>
                {PROJETOS.map((p, idx) => {
                  const start = [5, 15, -10, 0, 20, 8, -20, 40][idx];
                  const dur = [48, 60, 45, 30, 110, 15, 25, 80][idx];
                  return (
                    <div key={p.id} style={{ position: 'relative', borderBottom: '1px solid var(--line-1)', height: 46, minWidth: 900 }}>
                      <div style={{
                        position: 'absolute', top: 12, left: `${Math.max(0, start / 180 * 100)}%`,
                        width: `${dur / 180 * 100}%`, height: 22, background: p.color, borderRadius: 6,
                        display: 'flex', alignItems: 'center', paddingLeft: 8, paddingRight: 8,
                        fontSize: 10.5, fontWeight: 600, color: '#fff', overflow: 'hidden',
                        boxShadow: '0 2px 8px rgba(0,0,0,.3)',
                      }}>
                        <span style={{ whiteSpace: 'nowrap' }}>{p.prog}% · {p.done}/{p.tarefas} tarefas</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        )}

        {view === 'calendario' && <ProjCalendar projetos={PROJETOS}/>}

        {selected && <ProjDrawer projeto={selected} onClose={() => setSelected(null)}/>}
      </PageContainer>
    </AppShell>
  );
};

const ProjCalendar = ({ projetos }) => {
  const days = Array.from({ length: 30 }, (_, i) => i + 1);
  const firstDow = 1; // terça
  return (
    <div className="tile" style={{ padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <h3 style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-0)' }}>Abril · 2026</h3>
        <div style={{ display: 'flex', gap: 6 }}>
          <button className="btn btn-outline btn-sm"><Icon name="chevron-left" size={13}/></button>
          <button className="btn btn-outline btn-sm"><Icon name="chevron-right" size={13}/></button>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 1, background: 'var(--line-1)', border: '1px solid var(--line-1)', borderRadius: 10, overflow: 'hidden' }}>
        {['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'].map(d => (
          <div key={d} style={{ background: 'var(--bg-2)', padding: '10px 12px', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--text-3)', fontWeight: 600 }}>{d}</div>
        ))}
        {Array.from({ length: firstDow }).map((_, i) => (
          <div key={'e' + i} style={{ background: 'var(--bg-1)', minHeight: 88 }}/>
        ))}
        {days.map(d => {
          const due = projetos.filter(p => parseInt(p.prazo.split('/')[0]) === d && p.prazo.split('/')[1] === '04');
          return (
            <div key={d} style={{ background: 'var(--bg-1)', padding: '8px 10px', minHeight: 88 }}>
              <div style={{ fontSize: 11.5, fontWeight: 600, color: d === 19 ? 'var(--accent-text)' : 'var(--text-1)', marginBottom: 6 }}>{d}{d === 19 && ' ·'}</div>
              {due.map(p => (
                <div key={p.id} style={{ fontSize: 10, padding: '3px 6px', borderRadius: 4, background: p.color + '22', color: p.color, marginBottom: 3, borderLeft: `2px solid ${p.color}`, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                  Entrega · {p.nome.slice(0, 18)}…
                </div>
              ))}
            </div>
          );
        })}
      </div>
    </div>
  );
};

const ProjDrawer = ({ projeto: p, onClose }) => {
  const [tab, setTab] = React.useState('tarefas');
  const tarefas = [
    { id: 1, nome: 'Wireframes home + institucional', responsavel: 'Ana', prazo: '20/04', status: 'done' },
    { id: 2, nome: 'Revisão de copy pela Comunicação', responsavel: 'Bruno', prazo: '23/04', status: 'done' },
    { id: 3, nome: 'Implementação do CMS headless', responsavel: 'Carolina', prazo: '26/04', status: 'doing' },
    { id: 4, nome: 'Integração com WhatsApp Business', responsavel: 'Ana', prazo: '02/05', status: 'todo' },
    { id: 5, nome: 'Testes de acessibilidade (WCAG AA)', responsavel: 'Bruno', prazo: '10/05', status: 'todo' },
    { id: 6, nome: 'Deploy em staging + QA final', responsavel: 'Carolina', prazo: '20/05', status: 'todo' },
  ];
  const timesheet = [
    { data: '16/04', colab: 'Ana', horas: 6.5, nota: 'Wireframes + ajustes' },
    { data: '16/04', colab: 'Carolina', horas: 4, nota: 'Setup CMS' },
    { data: '15/04', colab: 'Bruno', horas: 3, nota: 'Revisão copy' },
    { data: '15/04', colab: 'Ana', horas: 7, nota: 'Design da home' },
    { data: '14/04', colab: 'Carolina', horas: 8, nota: 'Arquitetura backend' },
  ];
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 90 }}/>
      <div style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 680, maxWidth: '100vw', zIndex: 100,
        background: 'var(--bg-1)', borderLeft: '1px solid var(--line-2)', overflowY: 'auto',
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line-1)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 10 }}>
            <span style={{ fontSize: 10, padding: '3px 8px', borderRadius: 4, background: p.color + '22', color: p.color, fontWeight: 700, letterSpacing: '.05em' }}>{p.tag.toUpperCase()}</span>
            <button onClick={onClose} style={{ color: 'var(--text-3)', width: 30, height: 30, borderRadius: 6, display: 'grid', placeItems: 'center' }}><Icon name="close" size={14}/></button>
          </div>
          <h2 style={{ fontSize: 22, fontWeight: 700, color: 'var(--text-0)', marginBottom: 4, lineHeight: 1.25 }}>{p.nome}</h2>
          <div style={{ fontSize: 13, color: 'var(--text-3)' }}>{p.cliente} · <span style={{ fontFamily: 'JetBrains Mono, monospace' }}>{p.id}</span></div>
        </div>

        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--line-1)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 10 }}>
            {[
              { l: 'Progresso', v: p.prog + '%' }, { l: 'Prazo', v: p.prazo },
              { l: 'Tarefas', v: `${p.done}/${p.tarefas}` }, { l: 'Orçamento', v: Math.round(p.consumido / p.orcamento * 100) + '%' },
            ].map(s => (
              <div key={s.l} style={{ padding: 10, background: 'var(--bg-2)', border: '1px solid var(--line-1)', borderRadius: 8 }}>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '.05em', color: 'var(--text-4)' }}>{s.l}</div>
                <div style={{ fontSize: 15, fontWeight: 700, color: 'var(--text-0)', marginTop: 2 }}>{s.v}</div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 4, padding: '10px 24px', borderBottom: '1px solid var(--line-1)' }}>
          {['tarefas', 'sprints', 'timesheet', 'anexos'].map(t => (
            <button key={t} onClick={() => setTab(t)} style={{
              padding: '6px 12px', fontSize: 12.5, fontWeight: 500, borderRadius: 7, textTransform: 'capitalize',
              background: tab === t ? 'var(--bg-3)' : 'transparent',
              color: tab === t ? 'var(--text-0)' : 'var(--text-3)',
            }}>{t}</button>
          ))}
        </div>

        <div style={{ padding: '16px 24px' }}>
          {tab === 'tarefas' && tarefas.map(t => (
            <div key={t.id} style={{ padding: '10px 0', borderBottom: '1px solid var(--line-1)', display: 'flex', alignItems: 'center', gap: 12 }}>
              <span style={{
                width: 18, height: 18, borderRadius: 4, border: `1.5px solid ${t.status === 'done' ? '#22c55e' : 'var(--line-2)'}`,
                background: t.status === 'done' ? '#22c55e' : 'transparent',
                display: 'grid', placeItems: 'center',
              }}>{t.status === 'done' && <Icon name="check" size={11} style={{ color: '#fff' }}/>}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: 'var(--text-0)', textDecoration: t.status === 'done' ? 'line-through' : 'none', opacity: t.status === 'done' ? .6 : 1 }}>{t.nome}</div>
                <div style={{ fontSize: 11, color: 'var(--text-4)', marginTop: 2 }}>{t.responsavel} · até {t.prazo}</div>
              </div>
              <span style={{ fontSize: 10, padding: '3px 7px', borderRadius: 4, background: 'var(--bg-2)', color: 'var(--text-3)', textTransform: 'uppercase' }}>{t.status}</span>
            </div>
          ))}
          {tab === 'sprints' && (
            <div>
              {['Sprint 14 · atual', 'Sprint 13', 'Sprint 12'].map((s, i) => (
                <div key={s} style={{ padding: 12, border: '1px solid var(--line-1)', borderRadius: 9, marginBottom: 8, background: i === 0 ? 'var(--accent-soft-08)' : 'var(--bg-2)' }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-0)' }}>{s}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 3 }}>{i === 0 ? '12 tarefas · 8 done · 3 doing' : '14 tarefas · 14 done · encerrada'}</div>
                  <div style={{ height: 4, background: 'var(--bg-3)', borderRadius: 2, marginTop: 8, overflow: 'hidden' }}>
                    <div style={{ width: i === 0 ? '72%' : '100%', height: '100%', background: i === 0 ? 'var(--accent-1)' : '#22c55e' }}/>
                  </div>
                </div>
              ))}
            </div>
          )}
          {tab === 'timesheet' && (
            <table style={{ width: '100%', fontSize: 12.5 }}>
              <thead><tr style={{ color: 'var(--text-4)', fontSize: 11, textTransform: 'uppercase' }}>
                <th style={{ textAlign: 'left', padding: '6px 0' }}>Data</th>
                <th style={{ textAlign: 'left', padding: '6px 0' }}>Colaborador</th>
                <th style={{ textAlign: 'left', padding: '6px 0' }}>Horas</th>
                <th style={{ textAlign: 'left', padding: '6px 0' }}>Descrição</th>
              </tr></thead>
              <tbody>
                {timesheet.map((t, i) => (
                  <tr key={i} style={{ borderTop: '1px solid var(--line-1)' }}>
                    <td style={{ padding: '9px 0', fontFamily: 'JetBrains Mono, monospace', color: 'var(--text-3)' }}>{t.data}</td>
                    <td style={{ color: 'var(--text-1)' }}>{t.colab}</td>
                    <td style={{ color: 'var(--text-0)', fontWeight: 600 }}>{t.horas}h</td>
                    <td style={{ color: 'var(--text-3)' }}>{t.nota}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
          {tab === 'anexos' && (
            <div>
              {[
                { n: 'Briefing-v3.pdf', sz: '2,4 MB', d: '10/04' },
                { n: 'Wireframes-home.fig', sz: '14 MB', d: '14/04' },
                { n: 'Contrato-assinado.pdf', sz: '1,1 MB', d: '02/04' },
              ].map(a => (
                <div key={a.n} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--line-1)' }}>
                  <div style={{ width: 34, height: 34, borderRadius: 8, background: 'var(--bg-3)', display: 'grid', placeItems: 'center', color: 'var(--text-3)' }}><Icon name="doc" size={16}/></div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, color: 'var(--text-0)', fontWeight: 500 }}>{a.n}</div>
                    <div style={{ fontSize: 11, color: 'var(--text-4)' }}>{a.sz} · {a.d}</div>
                  </div>
                  <button className="btn btn-outline btn-sm"><Icon name="download" size={11}/></button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </>
  );
};

// =============================================================
// 2. Ordens de Serviço
// =============================================================
const OSS = [
  { id: 'OS-0421', cliente: 'Restaurante Xapuri', servico: 'Manutenção preventiva · câmara fria', tecnico: 'Carlos Mendonça', status: 'agendada', data: '22/04 · 09h', valor: 480, sla: 'ok' },
  { id: 'OS-0420', cliente: 'Padaria Pão Dourado', servico: 'Instalação forno rotativo · setup inicial', tecnico: 'Marcos Silveira', status: 'em-execucao', data: '19/04 · 14h', valor: 2800, sla: 'ok' },
  { id: 'OS-0419', cliente: 'Bighorse Studio', servico: 'Troca do ar-condicionado da sala de reunião', tecnico: 'Roberto Ferraz', status: 'em-execucao', data: '19/04 · 11h', valor: 1250, sla: 'atencao' },
  { id: 'OS-0418', cliente: 'Grupo Três Marias', servico: 'Emergência: vazamento no chiller · refrigeração', tecnico: 'Carlos Mendonça', status: 'em-execucao', data: '19/04 · 07h', valor: 3200, sla: 'critico' },
  { id: 'OS-0417', cliente: 'Restaurante Xapuri', servico: 'Limpeza química coifa + filtros (trimestral)', tecnico: 'Henrique Alves', status: 'concluida', data: '18/04 · 08h', valor: 620, sla: 'ok' },
  { id: 'OS-0416', cliente: 'Padaria Pão Dourado', servico: 'Inspeção anual de gás GLP · laudo NR-13', tecnico: 'Marcos Silveira', status: 'concluida', data: '17/04 · 15h', valor: 890, sla: 'ok' },
  { id: 'OS-0415', cliente: 'Café Savassi', servico: 'Reparo máquina de café expresso · rolamento', tecnico: 'Henrique Alves', status: 'concluida', data: '17/04 · 10h', valor: 340, sla: 'ok' },
  { id: 'OS-0414', cliente: 'Bighorse Studio', servico: 'Pintura externa fachada · 2 demãos', tecnico: 'Time externo', status: 'concluida', data: '15/04', valor: 4800, sla: 'ok' },
  { id: 'OS-0413', cliente: 'Grupo Três Marias', servico: 'Substituição compressor · OS-0398 retorno', tecnico: 'Carlos Mendonça', status: 'pendente-aprov', data: '14/04', valor: 5400, sla: 'ok' },
  { id: 'OS-0412', cliente: 'Café Savassi', servico: 'Manutenção preventiva · ar-condicionado 2 unid.', tecnico: 'Roberto Ferraz', status: 'concluida', data: '12/04', valor: 720, sla: 'ok' },
];

const PageOS = ({ onNavigate }) => {
  const [selected, setSelected] = React.useState(null);
  const [status, setStatus] = React.useState('todas');
  const statusMeta = {
    'agendada': { l: 'Agendada', c: '#93c5fd', bg: 'rgba(59,130,246,.14)' },
    'em-execucao': { l: 'Em execução', c: '#fcd34d', bg: 'rgba(245,158,11,.14)' },
    'concluida': { l: 'Concluída', c: '#86efac', bg: 'rgba(34,197,94,.14)' },
    'pendente-aprov': { l: 'Pendente aprov.', c: '#c4b5fd', bg: 'var(--accent-soft-14)' },
  };
  const slaColor = { ok: '#86efac', atencao: '#fcd34d', critico: '#fca5a5' };
  const filtered = OSS.filter(o => status === 'todas' || o.status === status);
  const total = OSS.reduce((a, o) => a + o.valor, 0);

  return (
    <AppShell current="os" onNavigate={onNavigate}>
      <PageContainer
        title="Ordens de Serviço"
        subtitle="Fluxo de OS · agendamento, execução, checklist e assinatura digital."
        maxWidth={1620}
        actions={<>
          <button className="btn btn-outline btn-sm"><Icon name="download" size={13}/> Exportar</button>
          <button className="btn btn-primary btn-sm"><Icon name="plus" size={13}/> Nova OS</button>
        </>}
      >
        <div className="row-4" style={{ marginBottom: 18 }}>
          <Tile icon="wrench" label="OS abertas" value={OSS.filter(o => o.status !== 'concluida').length} sub={`${OSS.filter(o => o.status === 'em-execucao').length} em execução`}/>
          <Tile icon="alert" label="SLA crítico" value={OSS.filter(o => o.sla === 'critico').length} sub="requer atenção imediata" deltaDir="down"/>
          <Tile icon="wallet" label="Faturamento do mês" value={`R$ ${(total / 1000).toFixed(1)}k`} delta="+18%" sub="vs abril/2025"/>
          <Tile icon="clock" label="Tempo médio exec." value="2h 40m" delta="-22min" sub="meta: < 3h"/>
        </div>

        <div className="tile" style={{ padding: 0, overflow: 'hidden' }}>
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--line-1)', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ display: 'inline-flex', background: 'var(--bg-2)', border: '1px solid var(--line-2)', borderRadius: 9, padding: 3 }}>
              {[['todas', 'Todas'], ['agendada', 'Agendadas'], ['em-execucao', 'Em execução'], ['concluida', 'Concluídas'], ['pendente-aprov', 'Aprovação']].map(([v, l]) => (
                <button key={v} onClick={() => setStatus(v)} style={{
                  padding: '5px 11px', borderRadius: 6, fontSize: 11.5, fontWeight: 500,
                  background: status === v ? 'var(--bg-3)' : 'transparent',
                  color: status === v ? 'var(--text-0)' : 'var(--text-3)',
                }}>{l}</button>
              ))}
            </div>
            <div style={{ marginLeft: 'auto', fontSize: 11.5, color: 'var(--text-3)' }}>{filtered.length} OS</div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ background: 'var(--bg-2)', color: 'var(--text-3)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '.05em' }}>
                <th style={{ textAlign: 'left', padding: '10px 16px', fontWeight: 600 }}>OS</th>
                <th style={{ textAlign: 'left', padding: '10px 14px', fontWeight: 600 }}>Cliente · Serviço</th>
                <th style={{ textAlign: 'left', padding: '10px 14px', fontWeight: 600 }}>Técnico</th>
                <th style={{ textAlign: 'left', padding: '10px 14px', fontWeight: 600 }}>Agendamento</th>
                <th style={{ textAlign: 'left', padding: '10px 14px', fontWeight: 600 }}>Status</th>
                <th style={{ textAlign: 'center', padding: '10px 14px', fontWeight: 600 }}>SLA</th>
                <th style={{ textAlign: 'right', padding: '10px 14px', fontWeight: 600 }}>Valor</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(o => (
                <tr key={o.id} onClick={() => setSelected(o)} style={{ borderTop: '1px solid var(--line-1)', cursor: 'pointer' }}>
                  <td style={{ padding: '12px 16px', fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: 'var(--text-2)' }}>{o.id}</td>
                  <td style={{ padding: '12px 14px' }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-0)' }}>{o.cliente}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 2 }}>{o.servico}</div>
                  </td>
                  <td style={{ padding: '12px 14px', color: 'var(--text-1)' }}>{o.tecnico}</td>
                  <td style={{ padding: '12px 14px', color: 'var(--text-2)', fontSize: 12 }}>{o.data}</td>
                  <td style={{ padding: '12px 14px' }}>
                    <span style={{ fontSize: 11, padding: '3px 8px', borderRadius: 4, background: statusMeta[o.status].bg, color: statusMeta[o.status].c, fontWeight: 600 }}>
                      {statusMeta[o.status].l}
                    </span>
                  </td>
                  <td style={{ padding: '12px 14px', textAlign: 'center' }}>
                    <span style={{ display: 'inline-block', width: 10, height: 10, borderRadius: '50%', background: slaColor[o.sla], boxShadow: `0 0 8px ${slaColor[o.sla]}88` }}/>
                  </td>
                  <td style={{ padding: '12px 14px', textAlign: 'right', fontFamily: 'JetBrains Mono, monospace', color: 'var(--text-0)', fontWeight: 600 }}>R$ {o.valor.toLocaleString('pt-BR')}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {selected && <OSDrawer os={selected} onClose={() => setSelected(null)}/>}
      </PageContainer>
    </AppShell>
  );
};

const OSDrawer = ({ os: o, onClose }) => {
  const checklist = [
    { t: 'Verificação inicial do equipamento', done: true },
    { t: 'Foto antes do serviço (entrada)', done: true },
    { t: 'Execução da manutenção', done: o.status !== 'agendada' },
    { t: 'Teste de funcionamento pós-serviço', done: o.status === 'concluida' },
    { t: 'Foto depois do serviço (saída)', done: o.status === 'concluida' },
    { t: 'Assinatura do cliente', done: o.status === 'concluida' },
  ];
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.5)', zIndex: 90 }}/>
      <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 620, maxWidth: '100vw', zIndex: 100, background: 'var(--bg-1)', borderLeft: '1px solid var(--line-2)', overflowY: 'auto' }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line-1)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
            <span style={{ fontSize: 10, padding: '3px 8px', borderRadius: 4, background: 'var(--bg-3)', color: 'var(--text-3)', fontFamily: 'JetBrains Mono, monospace', fontWeight: 700 }}>{o.id}</span>
            <button onClick={onClose} style={{ color: 'var(--text-3)', width: 30, height: 30, borderRadius: 6, display: 'grid', placeItems: 'center' }}><Icon name="close" size={14}/></button>
          </div>
          <h2 style={{ fontSize: 20, fontWeight: 700, color: 'var(--text-0)', lineHeight: 1.3, marginBottom: 6 }}>{o.servico}</h2>
          <div style={{ fontSize: 13, color: 'var(--text-3)' }}>{o.cliente} · {o.tecnico} · {o.data}</div>
        </div>

        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--line-1)' }}>
          <h4 style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--text-3)', fontWeight: 600, marginBottom: 10 }}>Checklist de execução</h4>
          {checklist.map((c, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
              <span style={{ width: 18, height: 18, borderRadius: 4, border: `1.5px solid ${c.done ? '#22c55e' : 'var(--line-2)'}`, background: c.done ? '#22c55e' : 'transparent', display: 'grid', placeItems: 'center' }}>
                {c.done && <Icon name="check" size={11} style={{ color: '#fff' }}/>}
              </span>
              <span style={{ fontSize: 13, color: c.done ? 'var(--text-1)' : 'var(--text-2)', textDecoration: c.done ? 'line-through' : 'none', opacity: c.done ? .75 : 1 }}>{c.t}</span>
            </div>
          ))}
        </div>

        <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--line-1)' }}>
          <h4 style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--text-3)', fontWeight: 600, marginBottom: 10 }}>Anexos de campo</h4>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {['Antes', 'Durante', 'Depois'].map((l, i) => (
              <div key={l} style={{ aspectRatio: '1/1', borderRadius: 10, background: `linear-gradient(135deg, hsl(${i * 60 + 220},40%,30%), hsl(${i * 60 + 260},40%,15%))`, display: 'grid', placeItems: 'center', color: 'var(--text-2)', position: 'relative', overflow: 'hidden' }}>
                <Icon name="camera" size={26}/>
                <span style={{ position: 'absolute', bottom: 6, left: 8, fontSize: 10, fontWeight: 600 }}>{l}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ padding: '16px 24px' }}>
          <h4 style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '.08em', color: 'var(--text-3)', fontWeight: 600, marginBottom: 10 }}>Assinatura do cliente</h4>
          <div style={{ padding: 14, background: 'var(--bg-2)', border: '1px dashed var(--line-2)', borderRadius: 10, textAlign: 'center' }}>
            {o.status === 'concluida' ? (
              <>
                <svg viewBox="0 0 200 60" style={{ width: '100%', maxWidth: 220, height: 60 }}>
                  <path d="M10 40 C 30 10, 50 50, 70 30 C 90 15, 100 45, 120 25 C 140 10, 160 40, 190 30" stroke="var(--accent-text)" strokeWidth="2" fill="none" strokeLinecap="round"/>
                </svg>
                <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 4 }}>Assinado por {o.cliente.split(' ')[0]} · {o.data}</div>
              </>
            ) : (
              <div style={{ fontSize: 12, color: 'var(--text-4)', padding: '14px 0' }}>Pendente de assinatura digital</div>
            )}
          </div>
          <div style={{ marginTop: 16, padding: 12, background: 'var(--accent-soft-08)', border: '1px solid var(--accent-soft-30)', borderRadius: 9, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 12.5, color: 'var(--text-2)' }}>Valor do serviço</span>
            <span style={{ fontSize: 20, fontWeight: 700, color: 'var(--text-0)', fontFamily: 'JetBrains Mono, monospace' }}>R$ {o.valor.toLocaleString('pt-BR')}</span>
          </div>
        </div>
      </div>
    </>
  );
};

Object.assign(window, { PROJETOS, OSS, PageProjetos, PageOS });
