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

// ── Mini Grid Preview (aba Grid dentro de ProjectView) ───────────────────────
function ProjGridPreview({ clientName, clientId, onNavToGrid }) {
  const [cells,    setCells]    = useState([]);
  const [artMap,   setArtMap]   = useState({});
  const [gridSize, setGridSize] = useState('3x3');
  const [loading,  setLoading]  = useState(true);
  const [resolvedId, setResolvedId] = useState(null);

  useEffect(() => {
    if (!clientName && !clientId) { setLoading(false); return; }
    async function load() {
      try {
        const { data: { user } } = await sb.auth.getUser();
        if (!user) { setLoading(false); return; }

        // Descobre o clientId via Supabase se não foi passado diretamente
        let cid = clientId;
        if (!cid && clientName) {
          const { data: cd } = await sb.from('clients').select('id').eq('name', clientName).maybeSingle();
          cid = cd?.id;
        }
        setResolvedId(cid || null);
        if (!cid) { setLoading(false); return; }

        // Carrega dados do localStorage
        const saved = JSON.parse(localStorage.getItem('inbrivvo_grid_v2_' + user.id) || 'null');
        const clientGrid = saved?.gridsData?.[cid];
        if (clientGrid) {
          const { cells: sc, gridSize: sg, userArts, hiddenIds } = clientGrid;
          const hiddenSet = new Set(hiddenIds || []);
          const arts = (userArts || []).filter(a => !hiddenSet.has(a.id));
          setArtMap(Object.fromEntries(arts.map(a => [a.id, a])));
          setGridSize(sg || '3x3');
          setCells(sc || []);
        }
      } catch(e) {}
      setLoading(false);
    }
    load();
  }, [clientName, clientId]);

  if (loading) return (
    <div style={{ padding:48, textAlign:'center', color:'var(--fg-muted)', fontSize:13 }}>Carregando grid...</div>
  );

  const rows      = { '3x3':3, '3x4':4, '3x5':5 }[gridSize] || 3;
  const total     = 3 * rows;
  const gridCells = Array.from({ length: total }, (_, i) => cells[i] || null);
  const hasCells  = gridCells.some(Boolean);

  const STATUS_COLOR = { rascunho:'rgba(100,100,100,0.85)', agendado:'rgba(14,165,233,0.85)', publicado:'rgba(34,197,94,0.85)' };
  const STATUS_LABEL = { rascunho:'Rasc', agendado:'Agen', publicado:'Pub' };

  if (!resolvedId || !hasCells) {
    return (
      <Card padding={40}>
        <div style={{ textAlign:'center', display:'flex', flexDirection:'column', alignItems:'center', gap:14 }}>
          <div style={{ fontSize:36 }}>📱</div>
          <div style={{ fontSize:15, fontWeight:700 }}>
            {!resolvedId ? 'Cliente não encontrado no Grid de Preview' : 'Nenhum post planejado ainda'}
          </div>
          <div style={{ fontSize:13, color:'var(--fg-muted)', maxWidth:360, lineHeight:1.6 }}>
            {!resolvedId
              ? `Este projeto está associado a "${clientName}", mas esse cliente ainda não existe na base de Clientes do app.`
              : `Ainda não há posts planejados para ${clientName} no Grid de Preview. Adicione artes no módulo Grid de Preview para visualizá-las aqui.`
            }
          </div>
          {onNavToGrid && (
            <button onClick={onNavToGrid} style={{ marginTop:8, padding:'9px 20px', borderRadius:8, background:'var(--primary)', color:'#fff', border:'none', fontSize:13, fontWeight:600, fontFamily:'inherit', cursor:'pointer' }}>
              Abrir Grid de Preview →
            </button>
          )}
        </div>
      </Card>
    );
  }

  return (
    <Card padding={20}>
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:16 }}>
        <div>
          <h3 style={{ margin:0, fontSize:16, fontWeight:700 }}>Grid de Preview — {clientName}</h3>
          <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:3 }}>{gridCells.filter(Boolean).length} posts planejados · somente leitura</div>
        </div>
        {onNavToGrid && (
          <button onClick={onNavToGrid} style={{ padding:'7px 16px', borderRadius:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', fontSize:12, fontWeight:600, fontFamily:'inherit', cursor:'pointer' }}>
            Editar no Grid de Preview →
          </button>
        )}
      </div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:4, maxWidth:480 }}>
        {gridCells.map((artId, idx) => {
          const art = artId ? artMap[artId] : null;
          return (
            <div key={idx} style={{ aspectRatio:'1', borderRadius:6, overflow:'hidden', background: art?.imageUrl ? 'transparent' : 'var(--bg-elevated)', border:'1px solid var(--border-subtle)', position:'relative' }}>
              {art?.imageUrl ? (
                <img src={art.imageUrl} alt={art.title || ''} style={{ width:'100%', height:'100%', objectFit:'cover' }} />
              ) : art ? (
                <div style={{ width:'100%', height:'100%', background: art.color || 'var(--bg-elevated)', display:'flex', alignItems:'center', justifyContent:'center', padding:6, boxSizing:'border-box' }}>
                  <span style={{ fontSize:9, color:'var(--fg-secondary)', textAlign:'center', overflow:'hidden', display:'-webkit-box', WebkitLineClamp:3, WebkitBoxOrient:'vertical' }}>{art.title}</span>
                </div>
              ) : (
                <div style={{ width:'100%', height:'100%', display:'grid', placeItems:'center' }}>
                  <span style={{ fontSize:20, opacity:0.12 }}>+</span>
                </div>
              )}
              {art && (
                <div style={{ position:'absolute', bottom:3, right:3, background: STATUS_COLOR[art.status] || STATUS_COLOR.rascunho, borderRadius:3, padding:'1px 5px', fontSize:8, color:'#fff', fontWeight:700, textTransform:'uppercase', letterSpacing:'0.04em' }}>
                  {STATUS_LABEL[art.status] || art.status}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </Card>
  );
}

function pvUuid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0;
    return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
  });
}

function fmtPV(n) {
  var num = parseFloat(n) || 0;
  return 'R$ ' + num.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

function parsePV(str) {
  return parseFloat((str || '').replace(/[^0-9.,]/g, '').replace(',', '.')) || 0;
}

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

const PROJ_TASKS_BY_PROJECT = {
  'Rebranding · Astra Cosméticos': [
    { id:1, t:'Aprovar paleta final',       col:'todo',   pri:'alta',  tg:'CLIENTE',   tc:'#1890FF', who:'Cliente',    due:'09/05' },
    { id:2, t:'Concept boards',             col:'todo',   pri:'alta',  tg:'DESIGN',    tc:'#36CFC9', who:'Ana S.',     due:'08/05' },
    { id:3, t:'Mockups embalagens',         col:'doing',  pri:'alta',  tg:'DESIGN',    tc:'#36CFC9', who:'Marcos R.',  due:'12/05' },
    { id:4, t:'Sistema de ícones',          col:'doing',  pri:'média', tg:'DESIGN',    tc:'#36CFC9', who:'Ana S.',     due:'12/05' },
    { id:5, t:'Variantes de logotipo',      col:'review', pri:'média', tg:'DESIGN',    tc:'#36CFC9', who:'Marcos R.',  due:'14/05' },
    { id:6, t:'Manual de marca v1',         col:'todo',   pri:'média', tg:'DOC',       tc:'#FA541C', who:'Ana S.',     due:'22/05' },
    { id:7, t:'Tipografia — escolha final', col:'done',   pri:'alta',  tg:'DESIGN',    tc:'#36CFC9', who:'Ana S.',     due:'05/05' },
    { id:8, t:'Moodboard · referências',    col:'done',   pri:'baixa', tg:'DESIGN',    tc:'#36CFC9', who:'Marcos R.',  due:'01/05' },
    { id:9, t:'Embalagens — 3 SKUs',        col:'doing',  pri:'alta',  tg:'DESIGN',    tc:'#36CFC9', who:'Marcos R.',  due:'20/05' },
  ],
  'Site Café Norte': [
    { id:1, t:'Wireframes home e internos',  col:'done',   pri:'alta',  tg:'UX',     tc:'#7C3AED', who:'Ana S.',     due:'18/04' },
    { id:2, t:'Layout desktop aprovado',     col:'done',   pri:'alta',  tg:'UI',     tc:'#1890FF', who:'Ana S.',     due:'24/04' },
    { id:3, t:'Responsivo mobile',           col:'review', pri:'alta',  tg:'UI',     tc:'#1890FF', who:'Ana S.',     due:'07/05' },
    { id:4, t:'Implementação header / nav',  col:'doing',  pri:'alta',  tg:'FRONT',  tc:'#22C55E', who:'Marcos R.',  due:'09/05' },
    { id:5, t:'Página Sobre Nós',            col:'todo',   pri:'média', tg:'FRONT',  tc:'#22C55E', who:'Marcos R.',  due:'12/05' },
    { id:6, t:'Formulário de contato',       col:'todo',   pri:'média', tg:'FRONT',  tc:'#22C55E', who:'Marcos R.',  due:'12/05' },
    { id:7, t:'Integração WhatsApp',         col:'todo',   pri:'baixa', tg:'FRONT',  tc:'#22C55E', who:'Lucas V.',   due:'14/05' },
    { id:8, t:'QA e testes cross-browser',   col:'todo',   pri:'alta',  tg:'QA',     tc:'#FA541C', who:'Juliana P.', due:'15/05' },
  ],
  'Identidade · Studio Bemvindo': [
    { id:1, t:'Logotipo primário',           col:'done',   pri:'alta',  tg:'DESIGN',  tc:'#36CFC9', who:'Ana S.',     due:'10/04' },
    { id:2, t:'Variações de logotipo',       col:'done',   pri:'alta',  tg:'DESIGN',  tc:'#36CFC9', who:'Ana S.',     due:'15/04' },
    { id:3, t:'Paleta de cores',             col:'done',   pri:'alta',  tg:'DESIGN',  tc:'#36CFC9', who:'Marcos R.',  due:'15/04' },
    { id:4, t:'Tipografia definida',         col:'done',   pri:'média', tg:'DESIGN',  tc:'#36CFC9', who:'Ana S.',     due:'18/04' },
    { id:5, t:'Papelaria — cartão e env.',   col:'done',   pri:'média', tg:'DESIGN',  tc:'#36CFC9', who:'Marcos R.',  due:'28/04' },
    { id:6, t:'Manual de marca',             col:'review', pri:'alta',  tg:'DOC',     tc:'#FA541C', who:'Ana S.',     due:'06/05' },
    { id:7, t:'Aprovação final do cliente',  col:'doing',  pri:'alta',  tg:'CLIENTE', tc:'#1890FF', who:'Cliente',    due:'07/05' },
    { id:8, t:'Pacote de entrega — arquivos',col:'todo',   pri:'alta',  tg:'ENTREGA', tc:'#FADB14', who:'Ana S.',     due:'09/05' },
  ],
  'Lançamento · Norte Foods': [
    { id:1, t:'Estratégia de lançamento',    col:'done',   pri:'alta',  tg:'ESTRATÉGIA', tc:'#7C3AED', who:'Juliana P.', due:'01/04' },
    { id:2, t:'Identidade visual campanha',  col:'done',   pri:'alta',  tg:'DESIGN',     tc:'#36CFC9', who:'Ana S.',     due:'10/04' },
    { id:3, t:'Peças para redes sociais',    col:'doing',  pri:'alta',  tg:'DESIGN',     tc:'#36CFC9', who:'Marcos R.',  due:'14/05' },
    { id:4, t:'Landing page de lançamento',  col:'doing',  pri:'alta',  tg:'FRONT',      tc:'#22C55E', who:'Lucas V.',   due:'16/05' },
    { id:5, t:'E-mail marketing — série',    col:'todo',   pri:'média', tg:'COPY',       tc:'#FA541C', who:'Juliana P.', due:'18/05' },
    { id:6, t:'Materiais de PDV',            col:'todo',   pri:'média', tg:'DESIGN',     tc:'#36CFC9', who:'Marcos R.',  due:'20/05' },
    { id:7, t:'Vídeo teaser 30s',            col:'review', pri:'alta',  tg:'VÍDEO',      tc:'#1890FF', who:'Lucas V.',   due:'12/05' },
    { id:8, t:'Press kit',                   col:'todo',   pri:'baixa', tg:'DOC',        tc:'#FA541C', who:'Juliana P.', due:'22/05' },
  ],
  'Material gráfico · Solar': [
    { id:1, t:'Briefing e referências',      col:'done',   pri:'alta',  tg:'BRIEFING', tc:'#1890FF', who:'Ana S.',     due:'15/03' },
    { id:2, t:'Conceito aprovado',           col:'done',   pri:'alta',  tg:'DESIGN',   tc:'#36CFC9', who:'Ana S.',     due:'28/03' },
    { id:3, t:'Catálogo de produtos',        col:'todo',   pri:'alta',  tg:'DESIGN',   tc:'#36CFC9', who:'Marcos R.',  due:'—'     },
    { id:4, t:'Folder institucional',        col:'todo',   pri:'média', tg:'DESIGN',   tc:'#36CFC9', who:'Marcos R.',  due:'—'     },
    { id:5, t:'Banners para site',           col:'todo',   pri:'baixa', tg:'DESIGN',   tc:'#36CFC9', who:'Lucas V.',   due:'—'     },
    { id:6, t:'Apresentação comercial',      col:'todo',   pri:'média', tg:'PPT',      tc:'#FA541C', who:'Juliana P.', due:'—'     },
  ],
  'Embalagem · Casa do Pão': [
    { id:1, t:'Pesquisa de mercado',         col:'done',   pri:'alta',  tg:'PESQUISA', tc:'#7C3AED', who:'Juliana P.', due:'05/04' },
    { id:2, t:'Conceito da embalagem',       col:'done',   pri:'alta',  tg:'DESIGN',   tc:'#36CFC9', who:'Ana S.',     due:'12/04' },
    { id:3, t:'Mockup 3D linha artesanal',   col:'done',   pri:'alta',  tg:'3D',       tc:'#FA541C', who:'Marcos R.',  due:'20/04' },
    { id:4, t:'Mockup 3D linha especial',    col:'done',   pri:'alta',  tg:'3D',       tc:'#FA541C', who:'Marcos R.',  due:'28/04' },
    { id:5, t:'Ajustes pós-feedback',        col:'doing',  pri:'alta',  tg:'DESIGN',   tc:'#36CFC9', who:'Ana S.',     due:'08/05' },
    { id:6, t:'Aprovação arte final',        col:'review', pri:'alta',  tg:'CLIENTE',  tc:'#1890FF', who:'Cliente',    due:'09/05' },
    { id:7, t:'Arquivo para produção',       col:'todo',   pri:'alta',  tg:'ENTREGA',  tc:'#FADB14', who:'Marcos R.',  due:'12/05' },
    { id:8, t:'Prova impressa',              col:'todo',   pri:'média', tg:'PRODUÇÃO', tc:'#1890FF', who:'Lucas V.',   due:'15/05' },
  ],
};

// ── Modal: Emitir NF ──────────────────────────────────────────────────────────
function EmitirNFModal({ onClose, onEmitido, project }) {
  const [emitido, setEmitido] = useState(false);

  const now    = new Date();
  const mes    = now.toLocaleString('pt-BR', { month: 'long' });
  const ano    = now.getFullYear();
  const comp   = mes.charAt(0).toUpperCase() + mes.slice(1) + ' / ' + ano;
  const tomador = (project?.client || '—');
  const servico = project?.name || '—';

  function confirmar() {
    setEmitido(true);
    window.__toast?.('NFS-e emitida com sucesso', { tone: 'success' });
    setTimeout(onEmitido, 800);
  }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(540px,100%)', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>

        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>Financeiro · Projeto</div>
            <h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Emitir nota fiscal</h2>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>

        <div style={{ padding:24, display:'flex', flexDirection:'column', gap:16 }}>
          <div style={{ background:'var(--bg-elevated)', borderRadius:12, padding:18, display:'flex', flexDirection:'column', gap:12 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
              <span style={{ fontFamily:'var(--font-display)', fontSize:9, fontWeight:700, color:'#fff', background:'#1890FF', padding:'4px 8px', borderRadius:4 }}>NFS-e</span>
            </div>
            {[
              ['Tomador',     tomador],
              ['Serviço',     servico],
              ['Competência', comp],
            ].map(([k, v]) => (
              <div key={k} style={{ display:'flex', justifyContent:'space-between', fontSize:13, borderBottom:'1px solid var(--border-subtle)', paddingBottom:8 }}>
                <span style={{ color:'var(--fg-muted)' }}>{k}</span>
                <span style={{ fontWeight:600 }}>{v}</span>
              </div>
            ))}
          </div>

          <div style={{ background:'rgba(34,197,94,0.08)', border:'1px solid rgba(34,197,94,0.25)', borderRadius:10, padding:'12px 16px', fontSize:12, color:'var(--fg-secondary)' }}>
            A NFS-e será gerada automaticamente e enviada para o e-mail do cliente cadastrado.
          </div>
        </div>

        <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)' }}>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button icon="check" onClick={confirmar} style={{ opacity: emitido ? 0.6 : 1, pointerEvents: emitido ? 'none' : 'auto' }}>
            {emitido ? 'Emitindo…' : 'Confirmar emissão'}
          </Button>
        </div>
      </div>
    </div>
  );
}

// ── Modal: Resposta do cliente ────────────────────────────────────────────────
function RespostaClienteModal({ onClose }) {
  const campos = [
    { q: 'Em 3 palavras, como você descreveria sua marca?',       a: 'Natural, premium, acessível' },
    { q: 'Qual problema seu produto resolve para o cliente?',     a: 'Produtos veganos de alta qualidade que não custam uma fortuna. Beleza consciente sem abrir mão do resultado.' },
    { q: 'Quem é seu público-alvo?',                             a: 'Mulheres de 25 a 40 anos, urbanas, que se preocupam com ingredientes e impacto ambiental. Classe B/C, renda média.' },
    { q: 'Quais são seus principais concorrentes?',              a: 'Lush, Quem disse, Berenice? e marcas indie como Granado linha vegana.' },
    { q: 'O que te diferencia deles?',                           a: 'Fórmulas 100% veganas e cruelty-free com certificação PETA. Preço mais acessível que Lush com qualidade similar.' },
    { q: 'Como você descreveria o tom de comunicação ideal?',    a: 'Próximo e humano, mas com sofisticação. Sem ser "hipster" demais — queremos ser acessíveis.' },
    { q: 'Existem elementos visuais que DEVEM ser mantidos?',    a: 'O símbolo da folha no logotipo atual tem muito valor de marca. Não pode ser removido.' },
    { q: 'Existem cores ou estilos que devem ser EVITADOS?',     a: 'Nada muito colorido ou juvenil. Queremos distância de marcas como O Boticário linha jovem.' },
    { q: 'Qual é o prazo ideal para entrega final?',             a: 'Precisamos do manual até 22 de maio para apresentar aos distribuidores.' },
    { q: 'Observações adicionais',                               a: 'As embalagens precisam funcionar tanto em prateleira de farmácia quanto em loja própria. Versatilidade é essencial.' },
  ];

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(680px,100%)', maxHeight:'82vh', display:'flex', flexDirection:'column', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>

        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between', flexShrink:0 }}>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>Briefing · BRF-0012</div>
            <h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Resposta do cliente</h2>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <div style={{ fontSize:11, color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>Respondido em 16/03/2026</div>
            <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4 }}>
              <Icon d={ICONS.x} size={18}/>
            </button>
          </div>
        </div>

        <div style={{ flex:1, overflow:'auto', padding:'8px 0' }}>
          {campos.map((c, i) => (
            <div key={i} style={{ padding:'16px 24px', borderBottom: i < campos.length-1 ? '1px solid var(--border-subtle)' : 'none' }}>
              <div style={{ fontSize:11, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:8 }}>{c.q}</div>
              <div style={{ fontSize:14, color:'var(--fg-primary)', lineHeight:1.65, background:'var(--bg-elevated)', borderRadius:8, padding:'10px 14px' }}>{c.a}</div>
            </div>
          ))}
        </div>

        <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)', flexShrink:0 }}>
          <Button variant="secondary" onClick={() => window.__toast?.('PDF exportado', { tone: 'success' })}>Exportar PDF</Button>
          <Button variant="ghost" onClick={onClose}>Fechar</Button>
        </div>
      </div>
    </div>
  );
}

// ── Tab: Briefing (editável, persistido por projeto) ──────────────────────────
function BriefingTab({ project }) {
  const projKey = project?.id || project?.name || 'default';
  const LS_KEY  = 'inbrivvo_brief_' + projKey;

  const EMPTY = { descricao: '', objetivos: [] };

  function loadFromLS() {
    try { return JSON.parse(localStorage.getItem(LS_KEY) || 'null') || EMPTY; } catch(e) { return EMPTY; }
  }

  const [editMode, setEditMode]   = useState(false);
  const [data, setData]           = useState(loadFromLS);
  const [draft, setDraft]         = useState(EMPTY);

  const isEmpty = !data.descricao && data.objetivos.length === 0;

  function startEdit()  { setDraft({ ...data, objetivos: [...data.objetivos] }); setEditMode(true); }
  function saveEdit()   {
    const saved = { ...draft, objetivos: draft.objetivos.filter(o => o.trim()) };
    setData(saved);
    try { localStorage.setItem(LS_KEY, JSON.stringify(saved)); } catch(e) {}
    setEditMode(false);
    window.__toast?.('Briefing salvo', { tone: 'success' });
  }
  function cancelEdit() { setEditMode(false); }

  function updateObj(i, val) { setDraft(d => { const o = [...d.objetivos]; o[i] = val; return { ...d, objetivos: o }; }); }
  function removeObj(i)      { setDraft(d => ({ ...d, objetivos: d.objetivos.filter((_,j) => j !== i) })); }
  function addObj()          { setDraft(d => ({ ...d, objetivos: [...d.objetivos, ''] })); }

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

  // ── Empty state ──────────────────────────────────────────────────────────────
  if (isEmpty && !editMode) {
    return (
      <Card padding={0}>
        <div style={{ padding:'48px 32px', display:'flex', flexDirection:'column', alignItems:'center', textAlign:'center', gap:16 }}>
          <div style={{ fontSize:40, opacity:0.35 }}>📋</div>
          <div>
            <div style={{ fontSize:16, fontWeight:700, color:'var(--fg-primary)', marginBottom:6 }}>Nenhum briefing registrado</div>
            <div style={{ fontSize:13, color:'var(--fg-muted)', maxWidth:380, lineHeight:1.6 }}>
              Adicione uma descrição do projeto e os principais objetivos para manter tudo documentado e alinhado com o cliente.
            </div>
          </div>
          <Button icon="plus" onClick={() => { setDraft({ descricao:'', objetivos:[''] }); setEditMode(true); }}>
            Preencher briefing
          </Button>
        </div>
      </Card>
    );
  }

  const projectLabel = project?.name || 'Projeto';
  const clientLabel  = project?.client || '';

  return (
    <Card padding={0}>
      {/* Cabeçalho */}
      <div style={{ padding:'18px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:12, flexWrap:'wrap' }}>
        <div style={{ flex:1, minWidth:200 }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, flexWrap:'wrap' }}>
            <span style={{ fontSize:15, fontWeight:700 }}>Briefing · {clientLabel || projectLabel}</span>
            {!isEmpty && !editMode && (
              <div style={{ display:'inline-flex', alignItems:'center', gap:5, background:'rgba(34,197,94,0.1)', border:'1px solid rgba(34,197,94,0.3)', borderRadius:20, padding:'3px 10px' }}>
                <span style={{ width:6, height:6, borderRadius:'50%', background:'#22C55E' }}/>
                <span style={{ fontSize:11, fontWeight:700, color:'#22C55E' }}>Preenchido</span>
              </div>
            )}
          </div>
          {clientLabel && <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:4 }}>{projectLabel}</div>}
        </div>
        <div style={{ display:'flex', gap:8, alignItems:'center', flexShrink:0 }}>
          {!editMode ? (
            <Button variant="ghost" onClick={startEdit}>Editar briefing</Button>
          ) : (
            <>
              <Button variant="ghost" onClick={cancelEdit}>Cancelar</Button>
              <Button icon="check" onClick={saveEdit}>Salvar</Button>
            </>
          )}
        </div>
      </div>

      <div style={{ padding:28, display:'flex', flexDirection:'column', gap:28 }}>
        {/* Descrição */}
        <div>
          <span style={lStyle}>Descrição / contexto</span>
          {editMode
            ? <textarea value={draft.descricao} onChange={e => setDraft(d => ({ ...d, descricao: e.target.value }))} rows={4} placeholder="Contexto do projeto, problema que resolve, público-alvo…" style={{ ...inputStyle, resize:'vertical', lineHeight:1.65 }}/>
            : <p style={{ color:'var(--fg-secondary)', fontSize:14, lineHeight:1.65, margin:0 }}>{data.descricao || <span style={{ color:'var(--fg-muted)', fontStyle:'italic' }}>Sem descrição.</span>}</p>
          }
        </div>

        {/* Objetivos */}
        <div>
          <span style={lStyle}>Objetivos</span>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {(editMode ? draft.objetivos : data.objetivos).map((obj, i) => (
              editMode ? (
                <div key={i} style={{ display:'flex', gap:8, alignItems:'center' }}>
                  <input value={obj} onChange={e => updateObj(i, e.target.value)} placeholder={`Objetivo ${i+1}…`} style={{ ...inputStyle, flex:1 }}/>
                  <button onClick={() => removeObj(i)} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4, flexShrink:0 }}>
                    <Icon d={ICONS.x} size={14}/>
                  </button>
                </div>
              ) : (
                <div key={i} style={{ display:'flex', alignItems:'flex-start', gap:10, fontSize:13, color:'var(--fg-secondary)', lineHeight:1.6, padding:'6px 0' }}>
                  <span style={{ width:5, height:5, borderRadius:'50%', background:'var(--primary)', marginTop:6, flexShrink:0 }}/>
                  {obj}
                </div>
              )
            ))}
            {editMode && (
              <button onClick={addObj} style={{ alignSelf:'flex-start', background:'transparent', border:'1px dashed var(--border-strong)', borderRadius:7, padding:'6px 16px', color:'var(--fg-muted)', cursor:'pointer', fontSize:12, fontFamily:'inherit', marginTop:4 }}>
                + Adicionar objetivo
              </button>
            )}
            {!editMode && data.objetivos.length === 0 && (
              <span style={{ fontSize:13, color:'var(--fg-muted)', fontStyle:'italic' }}>Nenhum objetivo registrado.</span>
            )}
          </div>
        </div>
      </div>
    </Card>
  );
}

// ── Task detail completo (igual ao módulo de Tarefas) ────────────────────────
function ProjTaskDetail({ task, project, onClose, onMove, onUpdate }) {
  const [editingTitle, setEditingTitle] = useState(false);
  const [titleDraft, setTitleDraft]     = useState(task.t);
  const [newSub, setNewSub]             = useState('');

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

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

  function saveTitle() {
    if (titleDraft.trim()) onUpdate(task.id, { t: titleDraft.trim() });
    setEditingTitle(false);
  }

  function addSub() {
    if (!newSub.trim()) return;
    onUpdate(task.id, { subtasks: [...subtasks, { id: Date.now(), text: newSub.trim(), done: false }] });
    setNewSub('');
  }

  function toggleSub(sid) { onUpdate(task.id, { subtasks: subtasks.map(s => s.id===sid ? {...s,done:!s.done} : s) }); }
  function deleteSub(sid) { onUpdate(task.id, { subtasks: subtasks.filter(s => s.id!==sid) }); }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.55)', backdropFilter:'blur(4px)', zIndex:200, display:'flex', alignItems:'stretch', justifyContent:'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width:440, display:'flex', flexDirection:'column', background:'var(--bg-surface)', borderLeft:'1px solid var(--border-subtle)', boxShadow:'-20px 0 60px rgba(0,0,0,0.4)' }}>

        {/* Header com título editável */}
        <div style={{ padding:'18px 22px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:12 }}>
          <div style={{ flex:1 }}>
            <span style={{ display:'inline-block', fontFamily:'var(--font-display)', fontSize:9, fontWeight:700, letterSpacing:'0.06em', padding:'2px 8px', borderRadius:4, background:task.tc+'24', color:task.tc }}>{task.tg}</span>
            {editingTitle ? (
              <input autoFocus value={titleDraft} onChange={e => setTitleDraft(e.target.value)} onBlur={saveTitle} onKeyDown={e => { if (e.key==='Enter') saveTitle(); if (e.key==='Escape') { setTitleDraft(task.t); setEditingTitle(false); } }} style={{ ...iStyle, marginTop:8, fontSize:16, fontWeight:700, padding:'6px 8px' }}/>
            ) : (
              <h2 onClick={() => setEditingTitle(true)} title="Clique para editar"
                style={{ margin:'8px 0 0', fontSize:16, fontWeight:700, lineHeight:1.3, cursor:'text', borderRadius:6, padding:'2px 4px', marginLeft:-4 }}
                onMouseEnter={e => e.currentTarget.style.background='var(--bg-elevated)'}
                onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                {task.t}
              </h2>
            )}
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4, marginTop:2 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>

        <div style={{ flex:1, overflow:'auto', padding:'20px 22px', display:'flex', flexDirection:'column', gap:22 }}>

          {/* Metadados */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            <div>
              <span style={lStyle}>Projeto</span>
              <div style={{ fontSize:13, color:'var(--fg-secondary)' }}>{project?.name || '—'}</div>
            </div>
            <div>
              <span style={lStyle}>Responsável</span>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <Avatar name={task.who} size={22} idx={task.id}/>
                <input defaultValue={task.who} onBlur={e => onUpdate(task.id, { who: e.target.value })} style={{ ...iStyle, padding:'3px 6px', fontSize:12 }}/>
              </div>
            </div>
            <div>
              <span style={lStyle}>Prioridade</span>
              <div style={{ display:'flex', gap:6 }}>
                {[['alta','#EF4444'],['média','#FADB14'],['baixa','#7A859A']].map(([p,c]) => (
                  <button key={p} onClick={() => onUpdate(task.id, { pri:p })} style={{ padding:'5px 10px', borderRadius:6, fontSize:11, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background: task.pri===p ? c+'22' : 'var(--bg-elevated)', color: task.pri===p ? c : 'var(--fg-muted)', border:`1px solid ${task.pri===p ? c+'66' : 'var(--border-subtle)'}` }}>{p.charAt(0).toUpperCase()+p.slice(1)}</button>
                ))}
              </div>
            </div>
            <div>
              <span style={lStyle}>Vencimento</span>
              <input defaultValue={task.due} placeholder="dd/mm" onBlur={e => onUpdate(task.id, { due: e.target.value })} style={{ ...iStyle, padding:'5px 8px', fontSize:12, fontFamily:'var(--font-mono)', width:90 }}/>
            </div>
          </div>

          {/* Status */}
          <div>
            <span style={lStyle}>Status</span>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {PROJ_COLS.map(c => (
                <button key={c.id} onClick={() => onMove(task.id, c.id)} style={{ padding:'6px 12px', borderRadius:8, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background: task.col===c.id ? c.tone+'22' : 'var(--bg-elevated)', color: task.col===c.id ? c.tone : 'var(--fg-secondary)', border:`1px solid ${task.col===c.id ? c.tone+'66' : 'var(--border-subtle)'}` }}>{c.lab}</button>
              ))}
            </div>
          </div>

          {/* Subtarefas */}
          <div>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:10 }}>
              <span style={{ ...lStyle, marginBottom:0 }}>Subtarefas</span>
              {subtasks.length > 0 && <span style={{ fontSize:11, color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>{doneSubs}/{subtasks.length}</span>}
            </div>
            {subtasks.length > 0 && (
              <div style={{ height:4, background:'var(--bg-elevated)', borderRadius:999, overflow:'hidden', marginBottom:12 }}>
                <div style={{ width:pct+'%', height:'100%', background: pct===100 ? '#22C55E' : 'var(--primary)', borderRadius:999, transition:'width 200ms' }}/>
              </div>
            )}
            <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
              {subtasks.map(s => (
                <div key={s.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'7px 10px', borderRadius:8, background:'var(--bg-elevated)' }}
                  onMouseEnter={e => e.currentTarget.querySelector('.sdel').style.opacity='1'}
                  onMouseLeave={e => e.currentTarget.querySelector('.sdel').style.opacity='0'}>
                  <button onClick={() => toggleSub(s.id)} style={{ width:18, height:18, borderRadius:5, flexShrink:0, cursor:'pointer', padding:0, background: s.done?'#22C55E':'transparent', border:`1.5px solid ${s.done?'#22C55E':'var(--border-strong)'}`, display:'grid', placeItems:'center' }}>
                    {s.done && <svg width="10" height="10" viewBox="0 0 10 10" fill="none"><path d="M2 5l2.5 2.5 4-4" stroke="#fff" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                  </button>
                  <span style={{ flex:1, fontSize:13, color: s.done?'var(--fg-muted)':'var(--fg-primary)', textDecoration: s.done?'line-through':'none' }}>{s.text}</span>
                  <button className="sdel" onClick={() => deleteSub(s.id)} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:2, opacity:0, transition:'opacity 120ms', lineHeight:1 }}>
                    <Icon d={ICONS.x} size={13}/>
                  </button>
                </div>
              ))}
            </div>
            <div style={{ display:'flex', gap:8, marginTop: subtasks.length ? 8 : 0 }}>
              <input value={newSub} onChange={e => setNewSub(e.target.value)} onKeyDown={e => e.key==='Enter' && addSub()} placeholder="Nova subtarefa…" style={{ ...iStyle, flex:1 }}/>
              <button onClick={addSub} style={{ background:'var(--primary)', border:'none', borderRadius:8, padding:'0 14px', color:'#fff', cursor:'pointer', fontFamily:'inherit', fontSize:13, fontWeight:600, flexShrink:0 }}>Adicionar</button>
            </div>
          </div>

          {/* Descrição */}
          <div>
            <span style={lStyle}>Descrição</span>
            <textarea defaultValue={task.desc||''} onBlur={e => onUpdate(task.id, { desc: e.target.value })} placeholder="Adicione uma descrição…" rows={3} style={{ ...iStyle, resize:'vertical', lineHeight:1.5 }}/>
          </div>
        </div>

        <div style={{ padding:'12px 22px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end' }}>
          <Button variant="secondary" onClick={onClose}>Fechar</Button>
        </div>
      </div>
    </div>
  );
}

// ── Modal: Nova tarefa do projeto ─────────────────────────────────────────────
function NovaTarefaProjModal({ project, onClose, onSave }) {
  const [form, setForm] = useState({ t:'', col:'todo', pri:'média', who:'Ana S.', due:'', tg:'DESIGN', tc:'#36CFC9' });

  const TAGS = [
    { v:'DESIGN',  c:'#36CFC9' }, { v:'FRONT',   c:'#22C55E' },
    { v:'DOC',     c:'#FA541C' }, { v:'UX',       c:'#7C3AED' },
    { v:'CLIENTE', c:'#1890FF' }, { v:'QA',       c:'#FA541C' },
    { v:'COPY',    c:'#FADB14' }, { v:'VÍDEO',   c:'#1890FF' },
  ];

  function handleSave() {
    if (!form.t.trim()) { window.__toast?.('Informe um título para a tarefa', { tone: 'danger' }); return; }
    onSave({ ...form, t: form.t.trim() });
  }

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

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(520px,100%)', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>

        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>{project?.name || 'Projeto'}</div>
            <h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Nova tarefa</h2>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>

        <div style={{ padding:24, display:'flex', flexDirection:'column', gap:18 }}>
          <div>
            <span style={LS}>Título *</span>
            <input autoFocus value={form.t} onChange={e => setForm(f => ({...f, t:e.target.value}))} onKeyDown={e => e.key==='Enter' && handleSave()} placeholder="Ex: Aprovar paleta de cores…" style={IS}/>
          </div>

          <div>
            <span style={LS}>Área / Tipo</span>
            <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
              {TAGS.map(tg => (
                <button key={tg.v} onClick={() => setForm(f => ({...f, tg:tg.v, tc:tg.c}))} style={{ padding:'5px 10px', borderRadius:6, fontSize:11, fontWeight:700, cursor:'pointer', fontFamily:'inherit', background: form.tg===tg.v ? tg.c+'22' : 'var(--bg-elevated)', color: form.tg===tg.v ? tg.c : 'var(--fg-muted)', border:`1px solid ${form.tg===tg.v ? tg.c+'66' : 'var(--border-subtle)'}` }}>{tg.v}</button>
              ))}
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            <div>
              <span style={LS}>Prioridade</span>
              <div style={{ display:'flex', gap:6 }}>
                {[['alta','#EF4444'],['média','#FADB14'],['baixa','#7A859A']].map(([p,c]) => (
                  <button key={p} onClick={() => setForm(f => ({...f, pri:p}))} style={{ flex:1, padding:'6px 6px', borderRadius:6, fontSize:11, fontWeight:700, cursor:'pointer', fontFamily:'inherit', background: form.pri===p ? c+'22' : 'var(--bg-elevated)', color: form.pri===p ? c : 'var(--fg-muted)', border:`1px solid ${form.pri===p ? c+'66' : 'var(--border-subtle)'}` }}>{p.charAt(0).toUpperCase()+p.slice(1)}</button>
                ))}
              </div>
            </div>
            <div>
              <span style={LS}>Coluna inicial</span>
              <select value={form.col} onChange={e => setForm(f => ({...f, col:e.target.value}))} style={{ ...IS, cursor:'pointer' }}>
                {PROJ_COLS.map(c => <option key={c.id} value={c.id}>{c.lab}</option>)}
              </select>
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            <div>
              <span style={LS}>Responsável</span>
              <input value={form.who} onChange={e => setForm(f => ({...f, who:e.target.value}))} placeholder="Nome do responsável" style={IS}/>
            </div>
            <div>
              <span style={LS}>Vencimento</span>
              <input value={form.due} onChange={e => setForm(f => ({...f, due:e.target.value}))} placeholder="dd/mm" style={IS}/>
            </div>
          </div>
        </div>

        <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)' }}>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button icon="plus" onClick={handleSave}>Criar tarefa</Button>
        </div>
      </div>
    </div>
  );
}

// ── Kanban do projeto ─────────────────────────────────────────────────────────
function ProjKanban({ project }) {
  const seed = PROJ_TASKS_BY_PROJECT[project?.name] || [];
  const [tasks, setTasks]           = useState(seed);
  const [draggingId, setDraggingId] = useState(null);
  const [dragOverCol, setDragOverCol] = useState(null);
  const [selected, setSelected]     = useState(null);
  const [novaTarefaOpen, setNovaTarefaOpen] = useState(false);

  React.useEffect(() => {
    window.__openProjNewTask = () => setNovaTarefaOpen(true);
    return () => { window.__openProjNewTask = null; };
  }, []);

  function moveTask(id, toCol) { setTasks(prev => prev.map(t => t.id===id ? {...t, col:toCol} : t)); }
  function updateTask(id, ch)  { setTasks(prev => prev.map(t => t.id===id ? {...t,...ch} : t)); }

  function addTask(data) {
    const newTask = { ...data, id: Date.now(), proj: project?.name || 'Projeto' };
    setTasks(prev => [...prev, newTask]);
    // Sincroniza com o módulo global de Tarefas se estiver montado
    window.__addExternalTask?.({ ...newTask, proj: project?.name || 'Projeto' });
    window.__toast?.('Tarefa criada com sucesso', { tone: 'success' });
    setNovaTarefaOpen(false);
  }

  if (tasks.length === 0) {
    return (
      <>
        <div style={{ padding:'48px 24px', textAlign:'center', color:'var(--fg-muted)' }}>
          <div style={{ fontSize:32, marginBottom:12, opacity:0.35 }}>📋</div>
          <div style={{ fontSize:15, fontWeight:600, color:'var(--fg-secondary)', marginBottom:6 }}>Nenhuma tarefa criada ainda</div>
          <div style={{ fontSize:13 }}>Adicione a primeira tarefa para este projeto usando o botão acima.</div>
        </div>
        {novaTarefaOpen && (
          <NovaTarefaProjModal
            project={project}
            onClose={() => setNovaTarefaOpen(false)}
            onSave={addTask}
          />
        )}
      </>
    );
  }

  return (
    <>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14 }}>
        <span style={{ fontSize:12, color:'var(--fg-muted)' }}>Arraste para mover · clique para detalhar</span>
        <Button icon="plus" onClick={() => setNovaTarefaOpen(true)}>Nova tarefa</Button>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }}>
        {PROJ_COLS.map(col => {
          const items = tasks.filter(t => t.col === col.id);
          const isOver = dragOverCol === col.id;
          return (
            <div key={col.id}
              onDragEnter={e => { e.preventDefault(); setDragOverCol(col.id); }}
              onDragOver={e => e.preventDefault()}
              onDragLeave={e => { if (!e.currentTarget.contains(e.relatedTarget)) setDragOverCol(null); }}
              onDrop={e => { e.preventDefault(); const id = parseInt(e.dataTransfer.getData('text/plain'),10); if (!isNaN(id)) moveTask(id, col.id); setDraggingId(null); setDragOverCol(null); }}
              style={{ background: isOver ? col.tone+'14' : 'var(--bg-elevated)', border:`${isOver?2:1}px solid ${isOver?col.tone:'var(--border-subtle)'}`, borderRadius:10, padding:12, minHeight:200, display:'flex', flexDirection:'column', gap:8, transition:'background 100ms, border-color 100ms' }}
            >
              <div style={{ display:'flex', alignItems:'center', gap:7, fontWeight:700, fontSize:12, padding:'0 2px 4px' }}>
                <span style={{ width:8, height:8, borderRadius:'50%', background:col.tone }}/>
                {col.lab}
                <span style={{ fontSize:10, color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>{items.length}</span>
              </div>
              {items.map(t => (
                <div key={t.id}
                  draggable={true}
                  onDragStart={e => { e.dataTransfer.setData('text/plain', String(t.id)); e.dataTransfer.effectAllowed='move'; requestAnimationFrame(() => setDraggingId(t.id)); }}
                  onDragEnd={() => { setDraggingId(null); setDragOverCol(null); }}
                  onClick={() => setSelected(t)}
                  style={{ background:'var(--bg-surface)', border:'1px solid var(--border-subtle)', borderRadius:8, padding:10, cursor:'grab', opacity: draggingId===t.id ? 0.35 : 1, userSelect:'none', WebkitUserSelect:'none', transition:'opacity 100ms' }}
                >
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                    <span style={{ fontFamily:'var(--font-display)', fontSize:8, fontWeight:700, letterSpacing:'0.05em', padding:'2px 6px', borderRadius:3, background:t.tc+'24', color:t.tc }}>{t.tg}</span>
                    <span style={{ width:5, height:5, borderRadius:'50%', background: t.pri==='alta'?'#EF4444':t.pri==='média'?'#FADB14':'#7A859A' }}/>
                  </div>
                  <div style={{ fontSize:12, fontWeight:600, marginTop:6, lineHeight:1.3 }}>{t.t}</div>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:8 }}>
                    <Avatar name={t.who} size={20} idx={t.id}/>
                    <span style={{ fontSize:10, color:'var(--fg-muted)', fontFamily:'var(--font-mono)' }}>{t.due}</span>
                  </div>
                </div>
              ))}
            </div>
          );
        })}
      </div>

      {selected && (
        <ProjTaskDetail
          task={tasks.find(t => t.id===selected.id) || selected}
          project={project}
          onClose={() => setSelected(null)}
          onMove={moveTask}
          onUpdate={updateTask}
        />
      )}

      {novaTarefaOpen && (
        <NovaTarefaProjModal
          project={project}
          onClose={() => setNovaTarefaOpen(false)}
          onSave={addTask}
        />
      )}
    </>
  );
}

// ── Modal: Editar despesa ─────────────────────────────────────────────────────
const PATH_PENCIL_PROJ = 'M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z';
const PATH_TRASH_PROJ  = 'M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6';

function EditDespesaModal({ despesa, onClose, onSave }) {
  const [form, setForm] = useState({ ...despesa });
  const cats = ['Recursos', 'Subcontrato', 'Software', 'Produção', 'Marketing', 'Viagem', 'Outros'];

  function handleSave() {
    onSave({ ...form, tone: form.s === 'pago' ? 'success' : 'warning' });
  }

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

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(480px,100%)', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>

        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>Financeiro · Projeto</div>
            <h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Editar despesa</h2>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>

        <div style={{ padding:24, display:'flex', flexDirection:'column', gap:16 }}>
          <div>
            <span style={lStyle}>Descrição</span>
            <input value={form.t} onChange={e => setForm(f => ({ ...f, t: e.target.value }))} style={inputStyle} placeholder="Ex: Banco de imagens"/>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:14 }}>
            <div>
              <span style={lStyle}>Categoria</span>
              <select value={form.c} onChange={e => setForm(f => ({ ...f, c: e.target.value }))} style={{ ...inputStyle, cursor:'pointer' }}>
                {cats.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <span style={lStyle}>Data</span>
              <input value={form.d} onChange={e => setForm(f => ({ ...f, d: e.target.value }))} style={inputStyle} placeholder="DD/MM/AAAA"/>
            </div>
          </div>
          <div>
            <span style={lStyle}>Valor</span>
            <input value={form.v} onChange={e => setForm(f => ({ ...f, v: e.target.value }))} style={inputStyle} placeholder="Ex: R$ 480"/>
          </div>
          <div>
            <span style={lStyle}>Status</span>
            <div style={{ display:'flex', gap:8 }}>
              {[['pago','Pago','#22C55E'],['a pagar','A pagar','#FADB14']].map(([val, label, color]) => (
                <button key={val} onClick={() => setForm(f => ({ ...f, s: val }))} style={{ flex:1, padding:'8px 12px', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', border:`1.5px solid ${form.s===val ? color+'88' : 'var(--border-subtle)'}`, background: form.s===val ? color+'18' : 'var(--bg-elevated)', color: form.s===val ? color : 'var(--fg-muted)' }}>{label}</button>
              ))}
            </div>
          </div>
        </div>

        <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)' }}>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button icon="check" onClick={handleSave}>Salvar alterações</Button>
        </div>
      </div>
    </div>
  );
}

// ── Card de despesas (com editar / apagar) ────────────────────────────────────
function ProjDespesasCard({ despesas, onDelete, onUpdate, onLancar }) {
  const [editando, setEditando] = useState(null);
  const [hovered, setHovered]   = useState(null);

  function deletar(id) {
    onDelete(id);
    window.__toast?.('Despesa removida', { tone: 'info' });
  }

  function salvar(updated) {
    onUpdate(updated);
    setEditando(null);
    window.__toast?.('Despesa atualizada', { tone: 'success' });
  }

  const btnStyle = (color) => ({
    width:28, height:28, borderRadius:7, background:'transparent',
    border:`1px solid ${color === 'danger' ? 'rgba(239,68,68,0.35)' : 'var(--border-subtle)'}`,
    color: color === 'danger' ? '#EF4444' : 'var(--fg-muted)',
    cursor:'pointer', display:'grid', placeItems:'center', flexShrink:0,
  });

  return (
    <>
      <Card padding={0}>
        <div style={{ padding:'14px 18px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:10 }}>
          <h3 style={{ margin:0, fontSize:14, fontWeight:700, flex:1 }}>Despesas do projeto</h3>
          <Button variant="ghost" size="sm" icon="plus" onClick={onLancar}>Lançar despesa</Button>
        </div>
        <table style={{ width:'100%', borderCollapse:'collapse' }}>
          <thead>
            <tr style={{ background:'var(--bg-elevated)' }}>
              {['Descrição','Categoria','Data','Valor','Status',''].map(h => (
                <th key={h} style={{ textAlign:'left', padding:'10px 18px', fontSize:11, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.06em' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {despesas.map(r => (
              <tr key={r.id}
                onMouseEnter={() => setHovered(r.id)}
                onMouseLeave={() => setHovered(null)}
                style={{ borderTop:'1px solid var(--border-subtle)', background: hovered===r.id ? 'var(--bg-elevated)' : 'transparent', transition:'background 100ms' }}
              >
                <td style={{ padding:'14px 18px', fontSize:13, fontWeight:600 }}>{r.t}</td>
                <td style={{ padding:'14px 18px' }}><Badge tone="neutral" dot={false}>{r.c}</Badge></td>
                <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)', color:'var(--fg-muted)' }}>{r.d}</td>
                <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)', fontWeight:600, color:'var(--accent-danger)' }}>− {r.v}</td>
                <td style={{ padding:'14px 18px' }}><Badge tone={r.tone} dot={false}>{r.s}</Badge></td>
                <td style={{ padding:'14px 18px' }}>
                  <div style={{ display:'flex', gap:5, justifyContent:'flex-end', opacity: hovered===r.id ? 1 : 0, transition:'opacity 120ms' }}>
                    <button title="Editar" style={btnStyle('neutral')} onClick={() => setEditando(r)}>
                      <svg viewBox="0 0 24 24" width={13} height={13} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"><path d={PATH_PENCIL_PROJ}/></svg>
                    </button>
                    <button title="Apagar" style={btnStyle('danger')} onClick={() => deletar(r.id)}>
                      <svg viewBox="0 0 24 24" width={13} height={13} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"><path d={PATH_TRASH_PROJ}/></svg>
                    </button>
                  </div>
                </td>
              </tr>
            ))}
            {despesas.length === 0 && (
              <tr>
                <td colSpan={6} style={{ padding:'36px 18px', textAlign:'center', fontSize:13, color:'var(--fg-muted)' }}>
                  Nenhuma despesa lançada neste projeto
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </Card>

      {editando && <EditDespesaModal despesa={editando} onClose={() => setEditando(null)} onSave={salvar}/>}
    </>
  );
}

// ── Modal: Editar projeto ─────────────────────────────────────────────────────
function EditarProjetoModal({ projData, onClose, onSave }) {
  const [form, setForm] = useState({ ...projData, equipe: [...projData.equipe] });
  const [novoMembro, setNovoMembro] = useState('');

  const STATUS_OPTS = [
    { v:'Em andamento', c:'#597EF7' },
    { v:'Em revisão',   c:'#FADB14' },
    { v:'Em pausa',     c:'#36CFC9' },
    { v:'Quase pronto', c:'#22C55E' },
    { v:'Concluído',    c:'#7A859A' },
  ];

  function addMembro() {
    const nome = novoMembro.trim();
    if (!nome || form.equipe.includes(nome)) return;
    setForm(f => ({ ...f, equipe: [...f.equipe, nome] }));
    setNovoMembro('');
  }

  function removeMembro(nome) {
    setForm(f => ({ ...f, equipe: f.equipe.filter(m => m !== nome) }));
  }

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

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(560px,100%)', maxHeight:'88vh', display:'flex', flexDirection:'column', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', overflow:'hidden' }}>

        <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', justifyContent:'space-between', flexShrink:0 }}>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>Projetos</div>
            <h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Editar projeto</h2>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4 }}>
            <Icon d={ICONS.x} size={18}/>
          </button>
        </div>

        <div style={{ flex:1, overflow:'auto', padding:24, display:'flex', flexDirection:'column', gap:20 }}>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            <div>
              <span style={LS}>Nome do projeto</span>
              <input value={form.name} onChange={e => setForm(f => ({...f, name:e.target.value}))} style={IS}/>
            </div>
            <div>
              <span style={LS}>Cliente</span>
              <input value={form.client} onChange={e => setForm(f => ({...f, client:e.target.value}))} style={IS}/>
            </div>
          </div>

          <div>
            <span style={LS}>Status</span>
            <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
              {STATUS_OPTS.map(s => {
                const sel = form.status === s.v;
                return (
                  <button key={s.v} onClick={() => setForm(f => ({...f, status:s.v}))} style={{ padding:'6px 14px', borderRadius:20, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background: sel ? s.c+'22' : 'var(--bg-elevated)', color: sel ? s.c : 'var(--fg-muted)', border:`1.5px solid ${sel ? s.c+'66' : 'var(--border-subtle)'}` }}>{s.v}</button>
                );
              })}
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            <div>
              <span style={LS}>Data de início</span>
              <input value={form.inicio} onChange={e => setForm(f => ({...f, inicio:e.target.value}))} placeholder="dd/mm/aaaa" style={IS}/>
            </div>
            <div>
              <span style={LS}>Data de entrega</span>
              <input value={form.entrega} onChange={e => setForm(f => ({...f, entrega:e.target.value}))} placeholder="dd/mm/aaaa" style={IS}/>
            </div>
          </div>

          <div>
            <span style={LS}>Equipe</span>
            <div style={{ display:'flex', flexWrap:'wrap', gap:8, marginBottom: form.equipe.length ? 10 : 0 }}>
              {form.equipe.map((m, i) => (
                <div key={m} style={{ display:'flex', alignItems:'center', gap:6, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', borderRadius:20, padding:'4px 10px 4px 6px' }}>
                  <Avatar name={m} size={20} idx={i}/>
                  <span style={{ fontSize:12, fontWeight:500 }}>{m}</span>
                  <button onClick={() => removeMembro(m)} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:0, lineHeight:1, marginLeft:2 }}>
                    <Icon d={ICONS.x} size={11}/>
                  </button>
                </div>
              ))}
            </div>
            <div style={{ display:'flex', gap:8 }}>
              <input value={novoMembro} onChange={e => setNovoMembro(e.target.value)} onKeyDown={e => e.key==='Enter' && addMembro()} placeholder="Nome do novo membro…" style={{ ...IS, flex:1 }}/>
              <button onClick={addMembro} style={{ background:'var(--primary)', border:'none', borderRadius:8, padding:'0 14px', color:'#fff', cursor:'pointer', fontFamily:'inherit', fontSize:13, fontWeight:600, flexShrink:0 }}>+</button>
            </div>
          </div>
        </div>

        <div style={{ padding:'14px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)', flexShrink:0 }}>
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button icon="check" onClick={() => onSave(form)}>Salvar alterações</Button>
        </div>
      </div>
    </div>
  );
}

// ── ProjectView principal ─────────────────────────────────────────────────────
function ProjectView({ project, onBack }) {
  const projKey = project?.id || project?.name || 'default';
  const PARC_LS = 'inbrivvo_parc_' + projKey;
  const DESP_LS = 'inbrivvo_desp_' + projKey;

  const [tab, setTab]           = useState('overview');
  const [finModal, setFinModal] = useState(null);
  const [nfModal, setNfModal]   = useState(false);
  const [nfEmitida, setNfEmitida] = useState(false);
  const [editProjetoOpen, setEditProjetoOpen] = useState(false);

  const [parcelas, setParcelas] = useState(() => {
    try { return JSON.parse(localStorage.getItem(PARC_LS) || '[]'); } catch(e) { return []; }
  });
  const [despesas, setDespesas] = useState(() => {
    try { return JSON.parse(localStorage.getItem(DESP_LS) || '[]'); } catch(e) { return []; }
  });

  // ── Financeiro real do projeto (tabela finances no Supabase) ──
  const [finResumo, setFinResumo] = useState({ receita: 0, custo: 0, loaded: false });
  useEffect(() => {
    if (!project?.id) return;
    sb.from('finances')
      .select('amount,type')
      .eq('project_id', project.id)
      .then(({ data }) => {
        if (!data) return;
        let receita = 0, custo = 0;
        data.forEach(f => {
          const val = parseFloat(f.amount) || 0;
          if (f.type === 'receita') receita += val;
          else custo += val;
        });
        setFinResumo({ receita, custo, loaded: true });
      });
  }, [project?.id]);

  function persistParcelas(arr) { setParcelas(arr); try { localStorage.setItem(PARC_LS, JSON.stringify(arr)); } catch(e) {} }
  function persistDespesas(arr) { setDespesas(arr); try { localStorage.setItem(DESP_LS, JSON.stringify(arr)); } catch(e) {} }

  // Map DB status key → label used in EditarProjetoModal
  const STATUS_DB_TO_LABEL = {
    andamento: 'Em andamento', ativo: 'Em andamento',
    revisao:   'Em revisão',   pausa: 'Em pausa',
    quase:     'Quase pronto', concluido: 'Concluído',
  };
  // Map label → DB key for saving
  const STATUS_LABEL_TO_DB = {
    'Em andamento': 'andamento', 'Em revisão': 'revisao',
    'Em pausa':     'pausa',     'Quase pronto': 'quase',
    'Concluído':    'concluido',
  };

  const [projData, setProjData] = useState({
    name:    project?.name   || '',
    client:  project?.client || '',
    status:  STATUS_DB_TO_LABEL[project?.dbStatus] || 'Em andamento',
    inicio:  '',
    entrega: project?.deadline || '',
    equipe:  [],
  });

  function statusTone(s) {
    return { 'Em andamento':'brand', 'Em revisão':'warning', 'Em pausa':'cyan', 'Quase pronto':'success', 'Concluído':'neutral' }[s] || 'brand';
  }

  function diasRestantes(dataStr) {
    if (!dataStr) return '—';
    try {
      // Suporta ISO (YYYY-MM-DD) e DD/MM/YYYY
      let d;
      if (/^\d{4}-\d{2}-\d{2}/.test(dataStr)) {
        d = new Date(dataStr + 'T00:00:00');
      } else {
        const p = dataStr.split('/');
        d = new Date(parseInt(p[2]), parseInt(p[1]) - 1, parseInt(p[0]));
      }
      if (isNaN(d.getTime())) return '—';
      const diff = Math.ceil((d - new Date()) / 86400000);
      return diff > 0 ? diff + ' dias' : diff === 0 ? 'hoje' : Math.abs(diff) + ' d atr.';
    } catch(e) { return '—'; }
  }

  const tabs = [
    { id: 'overview', lab: 'Visão geral' },
    { id: 'tasks',    lab: 'Tarefas' },
    { id: 'briefing', lab: 'Briefing' },
    { id: 'finance',  lab: 'Financeiro' },
    { id: 'files',    lab: 'Arquivos' },
    { id: 'grid',     lab: 'Grid 📱' },
  ];


  return (
    <div style={{ padding: '24px 28px', display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--fg-muted)', fontSize: 13 }}>
        <a onClick={onBack} style={{ cursor: 'pointer', color: 'var(--fg-secondary)' }}>Projetos</a>
        <Icon d={ICONS.arrowR} size={12} />
        <span style={{ color: 'var(--fg-primary)' }}>{projData.name}</span>
      </div>

      <Card padding={0} style={{ overflow: 'hidden' }}>
        <div style={{ height: 140, background: 'linear-gradient(135deg,#1D39C4 0%,#36CFC9 100%)', padding: '20px 24px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <Badge tone={statusTone(projData.status)}>{projData.status}</Badge>
            <button onClick={() => setEditProjetoOpen(true)} title="Editar projeto"
              style={{ display:'flex', alignItems:'center', gap:6, background:'rgba(255,255,255,0.12)', border:'1px solid rgba(255,255,255,0.2)', borderRadius:8, padding:'5px 12px', color:'rgba(255,255,255,0.9)', fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit' }}
              onMouseEnter={e => e.currentTarget.style.background='rgba(255,255,255,0.2)'}
              onMouseLeave={e => e.currentTarget.style.background='rgba(255,255,255,0.12)'}>
              <svg viewBox="0 0 24 24" width={13} height={13} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
              </svg>
              Editar projeto
            </button>
          </div>
          <div>
            <h1 style={{ margin: 0, fontSize: 28, fontWeight: 700, color: '#fff', letterSpacing: '-0.01em' }}>{projData.name}</h1>
            <div style={{ marginTop: 4, color: 'rgba(255,255,255,0.85)', fontSize: 13 }}>Cliente: {projData.client} · Iniciado em {projData.inicio} · Entrega {projData.entrega}</div>
          </div>
        </div>
        <div style={{ padding: '14px 24px', display: 'flex', alignItems: 'center', gap: 24, borderBottom: '1px solid var(--border-subtle)' }}>
          <div style={{ display: 'flex' }}>
            {projData.equipe.map((n, i) => <Avatar key={n} name={n} size={30} idx={i}/>)}
          </div>
          <div style={{ height: 24, width: 1, background: 'var(--border-subtle)' }}/>
          <div style={{ display: 'flex', gap: 24, fontSize: 12, color: 'var(--fg-muted)' }}>
            <span><strong style={{ color: 'var(--fg-primary)', fontFamily: 'var(--font-display)', fontSize: 16 }}>{project?.pct || 0}%</strong> concluído</span>
            <span><strong style={{ color: 'var(--fg-primary)', fontFamily: 'var(--font-display)', fontSize: 16 }}>{diasRestantes(projData.entrega)}</strong> restantes</span>
            <span><strong style={{ color: 'var(--fg-primary)', fontFamily: 'var(--font-display)', fontSize: 16 }}>{fmtPV(finResumo.receita)}</strong> faturado</span>
          </div>
          <div style={{ flex: 1 }}/>
          <Button variant="secondary" icon="msg" onClick={() => window.__toast?.('Comentário adicionado', { tone: 'success' })}>Comentar</Button>
          <Button icon="plus" onClick={() => { setTab('tasks'); setTimeout(() => window.__openProjNewTask?.(), 80); }}>Adicionar tarefa</Button>
        </div>
        <div style={{ padding: '0 24px', display: 'flex', gap: 4, borderBottom: '1px solid var(--border-subtle)' }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              background: 'transparent', border: 'none', padding: '14px 16px',
              color: tab === t.id ? 'var(--fg-primary)' : 'var(--fg-muted)',
              fontFamily: 'inherit', fontSize: 13, fontWeight: 600, cursor: 'pointer',
              borderBottom: `2px solid ${tab === t.id ? 'var(--primary)' : 'transparent'}`,
              marginBottom: -1,
            }}>{t.lab}</button>
          ))}
        </div>
      </Card>

      {/* ── Visão geral ── */}
      {tab === 'overview' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>

          {/* Acesso rápido às tarefas */}
          <Card padding={20}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:16 }}>
              <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Tarefas do projeto</h3>
              <Button size="sm" icon="plus" onClick={() => { setTab('tasks'); setTimeout(() => window.__openProjNewTask?.(), 80); }}>Nova tarefa</Button>
            </div>
            <div style={{ padding:'36px 24px', textAlign:'center', background:'var(--bg-elevated)', borderRadius:10, border:'1px dashed var(--border-strong)' }}>
              <div style={{ fontSize:28, marginBottom:10, opacity:0.5 }}>📋</div>
              <div style={{ fontSize:14, fontWeight:600, color:'var(--fg-secondary)', marginBottom:6 }}>Gerencie as tarefas na aba Tarefas</div>
              <div style={{ fontSize:12, color:'var(--fg-muted)', marginBottom:16, lineHeight:1.6 }}>
                Crie, organize e acompanhe o progresso de cada entrega deste projeto no quadro Kanban.
              </div>
              <button onClick={() => setTab('tasks')} style={{ padding:'8px 20px', borderRadius:8, background:'var(--primary)', color:'#fff', border:'none', fontSize:13, fontWeight:600, fontFamily:'inherit', cursor:'pointer' }}>
                Ver tarefas →
              </button>
            </div>
          </Card>

          {/* Resumo financeiro */}
          <Card padding={20}>
            <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700 }}>Resumo financeiro</h3>
            {(() => {
              const orcamento  = project?.budget ?? project?.rawValue ?? 0;
              const faturado   = finResumo.receita;
              const custo      = finResumo.custo;
              const aFaturar   = Math.max(0, orcamento - faturado);
              const margem     = orcamento > 0 ? Math.round(((orcamento - custo) / orcamento) * 100) : null;
              const linhas = [
                { k: 'Orçamento',      v: fmtPV(orcamento),                              c: 'var(--fg-primary)' },
                { k: 'Faturado',       v: faturado > 0 ? fmtPV(faturado) : '—',          c: 'var(--accent-success)' },
                { k: 'A faturar',      v: aFaturar > 0 ? fmtPV(aFaturar) : '—',          c: 'var(--fg-muted)' },
                { k: 'Custos',         v: custo > 0 ? fmtPV(custo) : '—',                c: 'var(--accent-danger)' },
                { k: 'Margem prevista',v: margem !== null ? margem + '%' : '—',           c: 'var(--geek-blue-300)' },
              ];
              return (
                <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
                  {linhas.map((it, i) => (
                    <div key={i} style={{ display:'flex', justifyContent:'space-between', borderBottom: i===linhas.length-1?'none':'1px solid var(--border-subtle)', paddingBottom:10 }}>
                      <span style={{ color:'var(--fg-secondary)', fontSize:13 }}>{it.k}</span>
                      <span style={{ color:it.c, fontWeight:700, fontFamily:'var(--font-display)', fontSize:14 }}>{it.v}</span>
                    </div>
                  ))}
                </div>
              );
            })()}

            {nfEmitida ? (
              <div style={{ marginTop:16, padding:'10px 14px', borderRadius:8, background:'rgba(34,197,94,0.1)', border:'1px solid rgba(34,197,94,0.3)', fontSize:13, fontWeight:600, color:'#22C55E', textAlign:'center' }}>
                NFS-e 0061 emitida
              </div>
            ) : (
              <Button variant="secondary" style={{ width:'100%', justifyContent:'center', marginTop:16 }} onClick={() => setNfModal(true)}>
                Emitir nota fiscal
              </Button>
            )}
          </Card>
        </div>
      )}

      {/* ── Tarefas ── */}
      {tab === 'tasks' && (
        <Card padding={20}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16 }}>
            <h3 style={{ margin:0, fontSize:16, fontWeight:700 }}>Quadro de tarefas</h3>
            <span style={{ fontSize:12, color:'var(--fg-muted)' }}>Arraste para mover · clique para detalhar</span>
          </div>
          <ProjKanban key={project?.name || 'novo'} project={project}/>
        </Card>
      )}

      {/* ── Briefing ── */}
      {tab === 'briefing' && <BriefingTab project={project}/>}

      {/* ── Financeiro ── */}
      {tab === 'finance' && (() => {
        const totalContratado = parcelas.reduce((s, p) => s + (p.numValue || 0), 0);
        const totalRecebido   = parcelas.filter(p => p.s === 'pago').reduce((s, p) => s + (p.numValue || 0), 0);
        const totalAReceber   = totalContratado - totalRecebido;
        const totalDespesas   = despesas.reduce((s, d) => s + (d.numValue || 0), 0);
        const pagas = parcelas.filter(p => p.s === 'pago').length;
        const aReceber = parcelas.filter(p => p.s !== 'pago').length;
        const pctPago = totalContratado > 0 ? Math.round((totalRecebido / totalContratado) * 100) : 0;
        const pctDesp = totalContratado > 0 ? Math.round((totalDespesas  / totalContratado) * 100) : 0;
        return (
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
              {[
                { l:'Contratado', v: fmtPV(totalContratado), d: parcelas.length > 0 ? pagas + '/' + parcelas.length + ' pagas' : 'Sem parcelas', tone:'neutral' },
                { l:'Recebido',   v: fmtPV(totalRecebido),   d: totalContratado > 0 ? pctPago + '% pago' : '—',     tone:'success' },
                { l:'A receber',  v: fmtPV(totalAReceber),   d: aReceber + (aReceber === 1 ? ' parcela' : ' parcelas'), tone:'brand' },
                { l:'Despesas',   v: fmtPV(totalDespesas),   d: totalContratado > 0 ? pctDesp + '% do total' : '—', tone:'warning' },
              ].map((k,i) => (
                <Card key={i} padding={16}>
                  <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)' }}>{k.l}</div>
                  <div style={{ fontFamily:'var(--font-display)', fontSize:24, fontWeight:700, letterSpacing:'-0.02em', marginTop:6 }}>{k.v}</div>
                  <div style={{ marginTop:10 }}><Badge tone={k.tone} dot={false}>{k.d}</Badge></div>
                </Card>
              ))}
            </div>

            <Card padding={0}>
              <div style={{ padding:'14px 18px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:10 }}>
                <h3 style={{ margin:0, fontSize:14, fontWeight:700, flex:1 }}>Recebíveis</h3>
                <Button variant="ghost" size="sm" icon="plus" onClick={() => setFinModal('receivable')}>Nova parcela</Button>
              </div>
              <table style={{ width:'100%', borderCollapse:'collapse' }}>
                <thead><tr style={{ background:'var(--bg-elevated)' }}>{['Parcela','Vencimento','Valor','NF','Status',''].map(h => <th key={h} style={{ textAlign:'left', padding:'10px 18px', fontSize:11, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.06em' }}>{h}</th>)}</tr></thead>
                <tbody>
                  {parcelas.length === 0 && (
                    <tr><td colSpan={6} style={{ padding:'32px 18px', textAlign:'center', fontSize:13, color:'var(--fg-muted)' }}>Nenhuma parcela cadastrada — clique em "Nova parcela" para começar</td></tr>
                  )}
                  {parcelas.map((r) => (
                    <tr key={r.id} style={{ borderTop:'1px solid var(--border-subtle)' }}>
                      <td style={{ padding:'14px 18px', fontSize:13, fontWeight:600 }}>{r.p}</td>
                      <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)', color:'var(--fg-muted)' }}>{r.d}</td>
                      <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)', fontWeight:600 }}>{r.v}</td>
                      <td style={{ padding:'14px 18px', fontSize:13, fontFamily:'var(--font-mono)', color:'var(--fg-muted)' }}>—</td>
                      <td style={{ padding:'14px 18px' }}><Badge tone={r.tone} dot={false}>{r.s}</Badge></td>
                      <td style={{ padding:'14px 18px' }}>
                        <button onClick={() => persistParcelas(parcelas.filter(p => p.id !== r.id))} title="Remover" style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4, borderRadius:6 }}>
                          <svg viewBox="0 0 24 24" width={13} height={13} fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round"><path d={PATH_TRASH_PROJ}/></svg>
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </Card>

            <ProjDespesasCard
              despesas={despesas}
              onDelete={(id) => persistDespesas(despesas.filter(d => d.id !== id))}
              onUpdate={(upd) => persistDespesas(despesas.map(d => d.id === upd.id ? upd : d))}
              onLancar={() => setFinModal('expense')}
            />
          </div>
        );
      })()}

      {tab === 'files' && <FilesTab projectName={projData.name} />}

      {/* ── Grid de Preview ── */}
      {tab === 'grid' && (
        <ProjGridPreview
          clientName={projData.client}
          onNavToGrid={() => window.__navigateToGrid && window.__navigateToGrid()}
        />
      )}

      {finModal && <FinanceModal kind={finModal} onClose={() => setFinModal(null)} onSave={(data) => {
        const val = parsePV(data.value);
        const fmtVal = 'R$ ' + val.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        if (finModal === 'receivable') {
          const nova = { id: pvUuid(), p: data.desc, d: data.date, v: fmtVal, nf: '—', s: data.paid ? 'pago' : 'a vencer', tone: data.paid ? 'success' : 'warning', numValue: val };
          persistParcelas([...parcelas, nova]);
          window.__toast?.('Parcela adicionada', { tone: 'success' });
        } else {
          const nova = { id: pvUuid(), t: data.desc, c: data.category, d: data.date, v: fmtVal, s: data.paid ? 'pago' : 'a pagar', tone: data.paid ? 'success' : 'warning', numValue: val };
          persistDespesas([...despesas, nova]);
          window.__toast?.('Despesa lançada', { tone: 'success' });
        }
      }}/>}
      {nfModal  && <EmitirNFModal project={project} onClose={() => setNfModal(false)} onEmitido={() => { setNfModal(false); setNfEmitida(true); }}/>}

      {editProjetoOpen && (
        <EditarProjetoModal
          projData={projData}
          onClose={() => setEditProjetoOpen(false)}
          onSave={async (data) => {
            if (project?.id) {
              const dbStatus = STATUS_LABEL_TO_DB[data.status] || 'andamento';
              const { error } = await sb.from('projects').update({
                name:   data.name.trim() || project.name,
                client: data.client.trim(),
                status: dbStatus,
              }).eq('id', project.id);
              if (error) { window.__toast?.(error.message, { tone:'danger' }); return; }
            }
            setProjData(data);
            setEditProjetoOpen(false);
            window.__toast?.('Projeto atualizado com sucesso', { tone: 'success' });
          }}
        />
      )}
    </div>
  );
}
window.ProjectView = ProjectView;
