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

// ─── Blocks ───────────────────────────────────────────────────────────────────
const AVAILABLE_BLOCKS = [
  'Menu / Logo','Header','Hero','Texto','Imagem','Vídeo','Carrossel',
  'Serviços','Portfólio','Sobre','Estatísticas','Timeline','Depoimentos',
  'CTA','CTA Final','Rodapé',
];

const BLOCK_DEFAULTS = {
  'Menu / Logo':  { brand:'Estúdio Norte' },
  'Header':       { brand:'Estúdio Norte' },
  'Hero':         { headline:'Design que transforma marcas', sub:'Criamos identidades visuais únicas que conectam e convertem.', cta:'Ver portfólio' },
  'Texto':        { heading:'', body:'Escreva seu conteúdo aqui...' },
  'Imagem':       { src:'', caption:'' },
  'Vídeo':        { url:'', title:'Assista nosso vídeo' },
  'Carrossel':    { items:'Imagem 1, Imagem 2, Imagem 3' },
  'Serviços':     { heading:'Nossos serviços', items:'Branding, Web Design, Motion, UI/UX' },
  'Portfólio':    { heading:'Trabalhos recentes', items:'Projeto A, Projeto B, Projeto C, Projeto D' },
  'Sobre':        { heading:'Sobre nós', body:'Somos um estúdio criativo especializado em design de marca e experiências digitais.' },
  'Estatísticas': { items:'120+ Projetos, 85 Clientes, 7 Anos' },
  'Timeline':     { heading:'Nossa jornada', items:'2018 Fundação, 2020 Expansão, 2024 Novos mercados' },
  'Depoimentos':  { heading:'O que dizem nossos clientes' },
  'CTA':          { heading:'Vamos conversar?', cta:'Entrar em contato' },
  'CTA Final':    { heading:'Pronto para começar?', sub:'Fale com a gente e comece seu projeto hoje.', cta:'Solicitar orçamento' },
  'Rodapé':       { brand:'Estúdio Norte', copy:'© 2026 Todos os direitos reservados.' },
};

const BLOCK_FIELDS = {
  'Menu / Logo':  [{ key:'brand', label:'Nome da marca', type:'text' }],
  'Header':       [{ key:'brand', label:'Nome da marca', type:'text' }],
  'Hero':         [{ key:'headline', label:'Título principal', type:'text' }, { key:'sub', label:'Subtítulo', type:'textarea' }, { key:'cta', label:'Texto do botão CTA', type:'text' }],
  'Texto':        [{ key:'heading', label:'Título (opcional)', type:'text' }, { key:'body', label:'Texto', type:'textarea' }],
  'Imagem':       [{ key:'src', label:'URL da imagem', type:'text' }, { key:'caption', label:'Legenda', type:'text' }],
  'Vídeo':        [{ key:'url', label:'URL do vídeo (YouTube, Vimeo…)', type:'text' }, { key:'title', label:'Título', type:'text' }],
  'Carrossel':    [{ key:'items', label:'Itens (separados por vírgula)', type:'text' }],
  'Serviços':     [{ key:'heading', label:'Título da seção', type:'text' }, { key:'items', label:'Serviços (separados por vírgula)', type:'text' }],
  'Portfólio':    [{ key:'heading', label:'Título da seção', type:'text' }, { key:'items', label:'Projetos (separados por vírgula)', type:'text' }],
  'Sobre':        [{ key:'heading', label:'Título', type:'text' }, { key:'body', label:'Texto', type:'textarea' }],
  'Estatísticas': [{ key:'items', label:'Estatísticas (ex: 120+ Projetos, 85 Clientes)', type:'text' }],
  'Timeline':     [{ key:'heading', label:'Título', type:'text' }, { key:'items', label:'Marcos (separados por vírgula)', type:'text' }],
  'Depoimentos':  [{ key:'heading', label:'Título da seção', type:'text' }],
  'CTA':          [{ key:'heading', label:'Título', type:'text' }, { key:'cta', label:'Texto do botão', type:'text' }],
  'CTA Final':    [{ key:'heading', label:'Título', type:'text' }, { key:'sub', label:'Subtítulo', type:'text' }, { key:'cta', label:'Texto do botão', type:'text' }],
  'Rodapé':       [{ key:'brand', label:'Nome da marca', type:'text' }, { key:'copy', label:'Copyright', type:'text' }],
};

function defaultBlocks(kind) {
  const sets = {
    'Portfolio':  ['Header','Hero','Estatísticas','Serviços','Portfólio','Sobre','Depoimentos','CTA Final','Rodapé'],
    'Bio Link':   ['Header','Hero','Rodapé'],
    'Aprovação':  ['Header','Hero','CTA','Rodapé'],
    'Briefing':   ['Header','Texto','CTA Final','Rodapé'],
    'Agenda':     ['Header','Hero','Serviços','Rodapé'],
    'Formulário': ['Header','Hero','Serviços','Rodapé'],
  };
  return (sets[kind] || ['Header','Hero','Rodapé']).map((type, i) => ({
    id: type.toLowerCase().replace(/[\s\/]+/g, '-') + '-' + i,
    type,
    data: { ...(BLOCK_DEFAULTS[type] || {}) },
  }));
}

// ─── Seed data ───────────────────────────────────────────────────────────────
const PAGES_SEED = [
  { t:'Portfolio · Estúdio Norte', url:'inbrivvo.com/p/estudio-norte',  kind:'Portfolio',  views:2400, leads:18, status:'publicado', tone:'success', c:'linear-gradient(135deg,#1D39C4,#36CFC9)', estilo:'moderno',     blocks:defaultBlocks('Portfolio')  },
  { t:'Bio link · Ana Silva',      url:'inbrivvo.bio/anasilva',          kind:'Bio Link',   views:1100, leads:34, status:'publicado', tone:'success', c:'linear-gradient(135deg,#FA541C,#FADB14)', estilo:'criativo',    blocks:defaultBlocks('Bio Link')   },
  { t:'Aprovação · Astra',         url:'inbrivvo.com/a/astra-2026',      kind:'Aprovação',  views:14,   leads:1,  status:'privado',   tone:'brand',   c:'linear-gradient(135deg,#7C3AED,#1D39C4)', estilo:'minimalista', blocks:defaultBlocks('Aprovação')  },
  { t:'Briefing · Norte Foods',    url:'inbrivvo.com/b/norte-foods',     kind:'Briefing',   views:3,    leads:2,  status:'rascunho',  tone:'neutral', c:'linear-gradient(135deg,#13C2C2,#1890FF)', estilo:'minimalista', blocks:defaultBlocks('Briefing')   },
  { t:'Agenda pública · Ana',      url:'inbrivvo.com/agenda/ana',        kind:'Agenda',     views:420,  leads:27, status:'publicado', tone:'success', c:'linear-gradient(135deg,#22C55E,#36CFC9)', estilo:'moderno',     blocks:defaultBlocks('Agenda')     },
  { t:'Form de contato',           url:'inbrivvo.com/f/estudio-norte',   kind:'Formulário', views:186,  leads:7,  status:'publicado', tone:'success', c:'linear-gradient(135deg,#1890FF,#34E0A1)', estilo:'criativo',    blocks:defaultBlocks('Formulário') },
];

function rowToPage(row) {
  const STATUS_TONES = { publicado:'success', privado:'brand', rascunho:'neutral' };
  return {
    id:     row.id,
    t:      row.title,
    url:    row.url || '',
    kind:   row.kind || 'Portfolio',
    estilo: row.estilo || 'moderno',
    status: row.status || 'rascunho',
    tone:   row.tone || STATUS_TONES[row.status] || 'neutral',
    blocks: Array.isArray(row.blocks) ? row.blocks : [],
    views:  row.views || 0,
    leads:  row.leads || 0,
    c:      row.gradient || 'linear-gradient(135deg,#1D39C4,#36CFC9)',
  };
}

const PAGE_TYPES = [
  { id:'portfolio', label:'Portfolio',  desc:'Mostre seus trabalhos com link personalizado',       icon:'folder', c:'linear-gradient(135deg,#1D39C4,#36CFC9)', kind:'Portfolio',  base:'inbrivvo.com/p/'      },
  { id:'biolink',   label:'Bio Link',   desc:'Um link único com todos seus canais e contatos',     icon:'link',   c:'linear-gradient(135deg,#FA541C,#FADB14)', kind:'Bio Link',   base:'inbrivvo.bio/'        },
  { id:'aprovacao', label:'Aprovação',  desc:'Página privada para cliente aprovar seus materiais', icon:'check',  c:'linear-gradient(135deg,#7C3AED,#1D39C4)', kind:'Aprovação',  base:'inbrivvo.com/a/'      },
  { id:'briefing',  label:'Briefing',   desc:'Levantamento de necessidades do cliente',            icon:'page',   c:'linear-gradient(135deg,#13C2C2,#1890FF)', kind:'Briefing',   base:'inbrivvo.com/b/'      },
  { id:'agenda',    label:'Agenda',     desc:'Calendário público para agendamentos de reuniões',   icon:'cal',    c:'linear-gradient(135deg,#22C55E,#36CFC9)', kind:'Agenda',     base:'inbrivvo.com/agenda/' },
  { id:'form',      label:'Formulário', desc:'Formulário customizável para coleta de dados',       icon:'list',   c:'linear-gradient(135deg,#1890FF,#34E0A1)', kind:'Formulário', base:'inbrivvo.com/f/'      },
];

const PAGE_STYLES = [
  {
    id:'moderno', label:'Moderno', sub:'Autoridade · Premium',
    desc:'Tipografia bold, espaços ricos e paleta de autoridade. Ideal para transmitir presença e credibilidade profissional.',
    bg:'#080D1C', accent:'#1D39C4', textC:'#E8EDFF',
    lineC:['#1D39C4','#1D39C460','#FFFFFF18'],
    btnBg:'linear-gradient(135deg,#1D39C4,#36CFC9)',
  },
  {
    id:'minimalista', label:'Minimalista', sub:'Editorial · Clean',
    desc:'Espaço em branco, hierarquia clara e foco total no conteúdo. Comunicação precisa com elegância atemporal.',
    bg:'#F8F8F6', accent:'#111111', textC:'#111111',
    lineC:['#11111120','#11111114','#1111110C'],
    btnBg:'#111111',
  },
  {
    id:'criativo', label:'Criativo', sub:'Impacto Visual · Ousado',
    desc:'Cores vibrantes, blocos expressivos e alta energia visual. Para marcas que querem causar impacto e ser inesquecíveis.',
    bg:'#0D0D0D', accent:'#FA541C', textC:'#FFFFFF',
    lineC:['#FA541C','#FADB14','#36CFC9'],
    btnBg:'linear-gradient(135deg,#FA541C,#FADB14)',
  },
];

function slugify(s) {
  return s.toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g,'').replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'');
}

function fmtNum(n) {
  const num = Number(n) || 0;
  if (num >= 1000) return (num / 1000).toFixed(1) + 'k';
  return String(num);
}

// ─── Mini preview de estilo ──────────────────────────────────────────────────
function StyleMiniPreview({ st }) {
  return (
    <div style={{ width:'100%', height:92, background:st.bg, borderRadius:8, overflow:'hidden', padding:'10px 12px', display:'flex', flexDirection:'column', gap:5, position:'relative', border:`1px solid ${st.accent}44` }}>
      <div style={{ height:7, width:'55%', background:st.accent, borderRadius:3 }}/>
      <div style={{ height:4, width:'38%', background:st.textC+'50', borderRadius:3, marginBottom:2 }}/>
      {st.lineC.map((c,i) => (
        <div key={i} style={{ height:4, width:[88,72,58][i]+'%', background:c, borderRadius:2 }}/>
      ))}
      <div style={{ position:'absolute', bottom:10, right:10, background:st.btnBg, borderRadius:5, padding:'5px 10px' }}>
        <div style={{ height:4, width:20, background:'#ffffff90', borderRadius:2 }}/>
      </div>
    </div>
  );
}

// ─── Toggle ──────────────────────────────────────────────────────────────────
function Toggle({ value, onChange }) {
  return (
    <div onClick={() => onChange(!value)} style={{ width:40, height:22, borderRadius:999, cursor:'pointer', background:value?'var(--primary)':'var(--bg-elevated)', border:`1px solid ${value?'var(--primary)':'var(--border-subtle)'}`, position:'relative', flexShrink:0, transition:'background 200ms' }}>
      <div style={{ position:'absolute', top:2, left:value?20:2, width:16, height:16, borderRadius:'50%', background:'#fff', transition:'left 200ms', boxShadow:'0 1px 3px rgba(0,0,0,0.3)' }}/>
    </div>
  );
}

// ─── Conteúdo por tipo de página (para prévia) ───────────────────────────────
function PortfolioContent({ st }) {
  const [openFaq, setOpenFaq] = React.useState(null);

  // Design tokens — dark agency style (Kobi/Fetech inspired)
  const BG0 = '#07091A';   // deepest bg
  const BG1 = '#0D1020';   // section alternate
  const BRD = 'rgba(255,255,255,0.08)';
  const FG  = '#FFFFFF';
  const FG2 = 'rgba(255,255,255,0.58)';
  const FG3 = 'rgba(255,255,255,0.32)';
  const ACC = st.accent || '#1D39C4';
  const ACC2 = '#36CFC9';

  const WORK = [
    { n:'Rebranding Astra Cosméticos', cat:'Branding',  year:'2026', c:'linear-gradient(135deg,#1D39C4,#36CFC9)', featured:true  },
    { n:'Site Café Norte',             cat:'Web Design', year:'2025', c:'linear-gradient(135deg,#FA541C,#FF7A45)', featured:false },
    { n:'App Bemvindo',                cat:'UI/UX',      year:'2025', c:'linear-gradient(135deg,#7C3AED,#FA541C)', featured:false },
    { n:'Campanha Norte Foods',        cat:'Motion',     year:'2024', c:'linear-gradient(135deg,#22C55E,#1890FF)', featured:false },
  ];

  const TESTIMONIALS = [
    { name:'Carla Mendes',  role:'CEO · Astra Cosméticos',      txt:'O rebranding superou todas as expectativas. Nossa marca ganhou um posicionamento que conecta com o público premium que buscamos.', stars:5, init:'CM', c:'#1D39C4' },
    { name:'Rafael Torres', role:'Fundador · Café Norte',        txt:'Site entregue no prazo com qualidade excepcional. Em 30 dias a taxa de conversão dobrou — ROI imediato e mensurável.',          stars:5, init:'RT', c:'#FA541C' },
    { name:'Julia Soares',  role:'Head of Product · Bemvindo',   txt:'Time extremamente profissional. Transformaram nossa visão em produto visual que encantou tanto investidores quanto usuários.',   stars:5, init:'JS', c:'#7C3AED' },
  ];

  const PLANS = [
    { name:'Starter', price:'R$ 2.800', note:'pagamento único',   highlight:false, items:['Logo + variações','Paleta & tipografia','Manual de uso básico','2 rodadas de revisão','Entrega em 15 dias'] },
    { name:'Pro',     price:'R$ 6.500', note:'pagamento único',   highlight:true,  items:['Tudo do Starter','Brandbook completo','Aplicações & mockups','Site 1 página incluso','Suporte 60 dias','Arquivos organizados'] },
    { name:'Studio',  price:'Sob consulta', note:'projetos complexos', highlight:false, items:['Escopo personalizado','Equipe dedicada','Estratégia completa','Identity + Motion','Suporte contínuo'] },
  ];

  const FAQS = [
    { q:'Qual o prazo médio de entrega?',       a:'Projetos Starter: 15 dias úteis. Pro: 25–35 dias. Studio: prazo definido no briefing conforme escopo.' },
    { q:'Como funciona o processo de criação?', a:'Briefing aprofundado → pesquisa e estratégia → 3 conceitos → refinamentos → entrega com todos os arquivos.' },
    { q:'O que é incluso nos arquivos finais?', a:'AI, EPS, PDF, PNG e SVG organizados por aplicação. Para projetos web, assets em @1x, @2x e @3x.' },
    { q:'Vocês atendem fora do Brasil?',        a:'Sim — América Latina, Portugal e EUA. Reuniões em PT, EN e ES conforme preferência.' },
  ];

  const lbl = { fontSize:10, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.10em', color:FG3 };
  const sec = (extra) => ({ padding:'44px 28px', background:BG0, ...extra });

  return (
    <div style={{ background:BG0, color:FG, fontFamily:'inherit', overflow:'hidden' }}>

      {/* ── NAV ──────────────────────────────────────────────────────────── */}
      <nav style={{ padding:'14px 28px', display:'flex', alignItems:'center', justifyContent:'space-between', borderBottom:`1px solid ${BRD}`, background:'rgba(7,9,26,0.92)', position:'sticky', top:0, zIndex:10 }}>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <div style={{ width:26, height:26, borderRadius:7, background:`linear-gradient(135deg,${ACC},${ACC2})` }}/>
          <span style={{ fontSize:14, fontWeight:800, color:FG, letterSpacing:'-0.01em' }}>Estúdio Norte</span>
        </div>
        <div style={{ display:'flex', gap:18 }}>
          {['Sobre','Serviços','Portfólio'].map(l => (
            <span key={l} style={{ fontSize:12, color:FG3, cursor:'pointer', fontWeight:500 }}>{l}</span>
          ))}
        </div>
        <div style={{ padding:'7px 16px', borderRadius:8, background:`linear-gradient(135deg,${ACC},${ACC2})`, cursor:'pointer' }}>
          <span style={{ fontSize:12, fontWeight:700, color:'#fff' }}>Contato</span>
        </div>
      </nav>

      {/* ── HERO ─────────────────────────────────────────────────────────── */}
      <div style={{ ...sec(), background:`radial-gradient(ellipse at 65% 40%, ${ACC}1A 0%, transparent 65%), ${BG0}`, display:'grid', gridTemplateColumns:'1fr 1fr', gap:28, alignItems:'center', paddingTop:52, paddingBottom:52 }}>
        <div>
          <div style={{ display:'inline-flex', alignItems:'center', gap:6, padding:'4px 12px', borderRadius:999, background:'rgba(255,255,255,0.06)', border:`1px solid ${BRD}`, marginBottom:18 }}>
            <div style={{ width:5, height:5, borderRadius:'50%', background:'#22C55E', boxShadow:'0 0 6px #22C55E' }}/>
            <span style={{ ...lbl, color:'rgba(255,255,255,0.45)' }}>Disponível para projetos</span>
          </div>
          <h1 style={{ margin:'0 0 6px', fontSize:34, fontWeight:900, color:FG, lineHeight:1.08, letterSpacing:'-0.03em' }}>
            Design que<br/>
            <span style={{ fontStyle:'italic', background:`linear-gradient(90deg,${ACC2},${ACC})`, WebkitBackgroundClip:'text', WebkitTextFillColor:'transparent', backgroundClip:'text' }}>transforma marcas/</span><br/>
            em resultados.
          </h1>
          <p style={{ margin:'14px 0 24px', fontSize:13, color:FG2, lineHeight:1.7, maxWidth:340 }}>
            Estúdio criativo especializado em branding, web design e UI/UX — identidades que conectam marcas ao público certo.
          </p>
          <div style={{ display:'flex', gap:10 }}>
            <div style={{ padding:'11px 22px', borderRadius:10, background:`linear-gradient(135deg,${ACC},${ACC2})`, cursor:'pointer', display:'inline-flex', alignItems:'center', gap:7 }}>
              <span style={{ fontSize:13, fontWeight:700, color:'#fff' }}>Ver portfólio →</span>
            </div>
            <div style={{ padding:'11px 22px', borderRadius:10, background:'transparent', border:`1px solid ${BRD}`, cursor:'pointer' }}>
              <span style={{ fontSize:13, fontWeight:600, color:FG2 }}>Orçamento</span>
            </div>
          </div>
        </div>

        {/* Hero visual — mock project card */}
        <div style={{ position:'relative' }}>
          <div style={{ borderRadius:14, border:`1px solid ${BRD}`, overflow:'hidden', background:BG1 }}>
            <div style={{ height:140, background:'linear-gradient(135deg,#1D39C4,#36CFC9)', position:'relative', display:'flex', flexDirection:'column', justifyContent:'flex-end', padding:'16px' }}>
              <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg,rgba(0,0,0,0) 40%,rgba(13,16,32,0.7) 100%)' }}/>
              <div style={{ position:'relative' }}>
                <span style={{ fontSize:9, fontWeight:700, letterSpacing:'0.12em', color:'rgba(255,255,255,0.65)', textTransform:'uppercase' }}>★ Case destaque</span>
                <div style={{ fontSize:16, fontWeight:900, color:'#fff', marginTop:4 }}>Rebranding Astra</div>
              </div>
            </div>
            <div style={{ padding:'14px 16px', display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:6 }}>
              {['#1D39C4','#36CFC9','#FADB14','#FF6A00','#7C3AED','#EC4899'].map((c,i) => (
                <div key={i} style={{ height:22, borderRadius:5, background:c, opacity:0.85 }}/>
              ))}
            </div>
          </div>
          <div style={{ position:'absolute', bottom:-10, left:-10, padding:'8px 14px', borderRadius:10, background:BG1, border:`1px solid ${BRD}`, boxShadow:'0 8px 32px rgba(0,0,0,0.5)' }}>
            <div style={{ fontSize:11, fontWeight:700, color:FG }}>120+ Projetos</div>
            <div style={{ fontSize:9, color:FG3 }}>entregues com sucesso</div>
          </div>
        </div>
      </div>

      {/* ── LOGOS BAR ────────────────────────────────────────────────────── */}
      <div style={{ padding:'20px 28px', borderTop:`1px solid ${BRD}`, borderBottom:`1px solid ${BRD}`, background:BG1 }}>
        <div style={{ ...lbl, textAlign:'center', marginBottom:14 }}>Trabalhamos com</div>
        <div style={{ display:'flex', justifyContent:'space-around', alignItems:'center', gap:8 }}>
          {['Astra Co.','Norte Foods','Bemvindo','Kaffa Studio','Vistro'].map((l,i) => (
            <span key={i} style={{ fontSize:12, fontWeight:800, color:FG3, letterSpacing:'-0.01em' }}>{l}</span>
          ))}
        </div>
      </div>

      {/* ── BENTO FEATURES ───────────────────────────────────────────────── */}
      <div style={{ ...sec(), paddingTop:44 }}>
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <div style={lbl}>Por que a gente</div>
          <h2 style={{ margin:'8px 0 10px', fontSize:24, fontWeight:900, color:FG, letterSpacing:'-0.02em' }}>Criamos mais do que design</h2>
          <p style={{ fontSize:13, color:FG2, maxWidth:400, margin:'0 auto', lineHeight:1.6 }}>Cada projeto é tratado como se fosse o nosso próprio negócio.</p>
        </div>

        {/* Top row — 2 cards */}
        <div style={{ display:'grid', gridTemplateColumns:'1.3fr 1fr', gap:12, marginBottom:12 }}>
          {/* Branding card */}
          <div style={{ borderRadius:14, border:`1px solid ${BRD}`, background:BG1, padding:'22px 20px 16px', overflow:'hidden' }}>
            <div style={{ display:'inline-flex', padding:'3px 10px', borderRadius:999, background:`${ACC}22`, border:`1px solid ${ACC}44`, marginBottom:12 }}>
              <span style={{ fontSize:9, fontWeight:700, color:ACC, letterSpacing:'0.08em' }}>BRANDING</span>
            </div>
            <div style={{ fontSize:15, fontWeight:800, color:FG, marginBottom:5 }}>Identidades que ficam na memória</div>
            <p style={{ fontSize:12, color:FG2, lineHeight:1.55, margin:'0 0 14px' }}>Sistemas visuais completos — logo, tipografia, paleta e brandbook.</p>
            {/* Mock brand visual */}
            <div style={{ padding:'12px', borderRadius:10, background:'rgba(0,0,0,0.3)', border:`1px solid ${BRD}` }}>
              <div style={{ display:'flex', gap:6, marginBottom:10 }}>
                {['#1D39C4','#36CFC9','#FADB14','#FF6A00','#7C3AED'].map((c,i) => (
                  <div key={i} style={{ width:22, height:22, borderRadius:'50%', background:c, boxShadow:`0 0 8px ${c}66` }}/>
                ))}
              </div>
              <div style={{ display:'flex', gap:8, alignItems:'center' }}>
                <div style={{ width:30, height:30, borderRadius:7, background:`linear-gradient(135deg,${ACC},${ACC2})` }}/>
                <div>
                  <div style={{ fontSize:11, fontWeight:900, color:FG, letterSpacing:'-0.01em' }}>BRAND</div>
                  <div style={{ fontSize:8, color:FG3, letterSpacing:'0.15em' }}>ESTÚDIO NORTE</div>
                </div>
              </div>
            </div>
          </div>
          {/* Web card */}
          <div style={{ borderRadius:14, border:`1px solid ${BRD}`, background:BG1, padding:'22px 20px 16px', overflow:'hidden' }}>
            <div style={{ display:'inline-flex', padding:'3px 10px', borderRadius:999, background:'rgba(250,84,28,0.15)', border:'1px solid rgba(250,84,28,0.3)', marginBottom:12 }}>
              <span style={{ fontSize:9, fontWeight:700, color:'#FA541C', letterSpacing:'0.08em' }}>WEB DESIGN</span>
            </div>
            <div style={{ fontSize:15, fontWeight:800, color:FG, marginBottom:5 }}>Sites que convertem</div>
            <p style={{ fontSize:12, color:FG2, lineHeight:1.55, margin:'0 0 14px' }}>Landing pages que transformam visitantes em clientes.</p>
            {/* Mock browser visual */}
            <div style={{ borderRadius:8, overflow:'hidden', border:`1px solid ${BRD}`, background:'#0A0E1A' }}>
              <div style={{ padding:'6px 10px', background:'rgba(255,255,255,0.04)', display:'flex', gap:4, alignItems:'center' }}>
                {['#FF5F56','#FEBC2E','#28C840'].map((c,i) => <div key={i} style={{ width:6, height:6, borderRadius:'50%', background:c }}/>)}
                <div style={{ flex:1, marginLeft:6, height:10, borderRadius:3, background:'rgba(255,255,255,0.07)', display:'flex', alignItems:'center', paddingLeft:6 }}>
                  <span style={{ fontSize:7, color:FG3 }}>estudio.norte.com</span>
                </div>
              </div>
              <div style={{ padding:'8px' }}>
                <div style={{ height:36, borderRadius:5, background:`linear-gradient(135deg,${ACC},${ACC2})`, marginBottom:5, display:'flex', alignItems:'center', justifyContent:'center' }}>
                  <span style={{ fontSize:9, fontWeight:800, color:'#fff' }}>ESTÚDIO NORTE</span>
                </div>
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:4 }}>
                  {[`${ACC}33`,'rgba(250,84,28,0.25)','rgba(124,58,237,0.25)','rgba(34,197,94,0.2)'].map((c,i) => (
                    <div key={i} style={{ height:20, borderRadius:4, background:c, border:`1px solid ${BRD}` }}/>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Bottom row — 3 cards */}
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
          {/* UI/UX */}
          <div style={{ borderRadius:14, border:`1px solid ${BRD}`, background:BG1, padding:'18px 16px' }}>
            <div style={{ display:'inline-flex', padding:'3px 10px', borderRadius:999, background:'rgba(124,58,237,0.15)', border:'1px solid rgba(124,58,237,0.3)', marginBottom:10 }}>
              <span style={{ fontSize:9, fontWeight:700, color:'#7C3AED', letterSpacing:'0.08em' }}>UI/UX</span>
            </div>
            <div style={{ fontSize:13, fontWeight:800, color:FG, marginBottom:5 }}>Centrado em dados</div>
            <p style={{ fontSize:11, color:FG2, lineHeight:1.5, margin:'0 0 12px' }}>Interfaces que elevam conversão.</p>
            {/* Mock analytics */}
            <div style={{ padding:'10px', background:'rgba(0,0,0,0.3)', borderRadius:8, border:`1px solid ${BRD}` }}>
              <div style={{ fontSize:8, color:FG3, marginBottom:3, letterSpacing:'0.06em' }}>CONVERSÃO</div>
              <div style={{ fontSize:16, fontWeight:900, color:FG }}>94.3% <span style={{ fontSize:9, color:'#22C55E' }}>↑12%</span></div>
              <div style={{ display:'flex', alignItems:'flex-end', gap:3, height:28, marginTop:8 }}>
                {[40,65,45,80,55,90,70].map((h,i) => (
                  <div key={i} style={{ flex:1, borderRadius:'2px 2px 0 0', background:`linear-gradient(180deg,${ACC},${ACC}66)`, height:`${h}%` }}/>
                ))}
              </div>
            </div>
          </div>
          {/* Motion */}
          <div style={{ borderRadius:14, border:`1px solid ${BRD}`, background:BG1, padding:'18px 16px' }}>
            <div style={{ display:'inline-flex', padding:'3px 10px', borderRadius:999, background:'rgba(34,197,94,0.12)', border:'1px solid rgba(34,197,94,0.28)', marginBottom:10 }}>
              <span style={{ fontSize:9, fontWeight:700, color:'#22C55E', letterSpacing:'0.08em' }}>MOTION</span>
            </div>
            <div style={{ fontSize:13, fontWeight:800, color:FG, marginBottom:5 }}>Animação & Vídeo</div>
            <p style={{ fontSize:11, color:FG2, lineHeight:1.5, margin:'0 0 12px' }}>Conteúdo que engaja e converte.</p>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'center', height:52, position:'relative' }}>
              {[0,1,2].map(i => (
                <div key={i} style={{ position:'absolute', width:52+i*30, height:52+i*30, borderRadius:'50%', border:`1px solid ${ACC}${40-i*10}`, opacity:0.7-i*0.15 }}/>
              ))}
              <div style={{ width:16, height:16, borderRadius:'50%', background:`linear-gradient(135deg,${ACC},${ACC2})`, position:'relative', zIndex:2, boxShadow:`0 0 16px ${ACC}88` }}/>
            </div>
          </div>
          {/* Estratégia */}
          <div style={{ borderRadius:14, border:`1px solid ${BRD}`, background:BG1, padding:'18px 16px' }}>
            <div style={{ display:'inline-flex', padding:'3px 10px', borderRadius:999, background:'rgba(250,219,20,0.1)', border:'1px solid rgba(250,219,20,0.22)', marginBottom:10 }}>
              <span style={{ fontSize:9, fontWeight:700, color:'#FADB14', letterSpacing:'0.08em' }}>ESTRATÉGIA</span>
            </div>
            <div style={{ fontSize:13, fontWeight:800, color:FG, marginBottom:5 }}>Estratégia Digital</div>
            <p style={{ fontSize:11, color:FG2, lineHeight:1.5, margin:'0 0 12px' }}>Presença digital completa.</p>
            <div style={{ display:'flex', gap:6 }}>
              {[['CAC','R$42'],['LTV','R$890'],['ROI','21x']].map(([l,v],i) => (
                <div key={i} style={{ flex:1, padding:'7px 4px', borderRadius:7, background:'rgba(255,255,255,0.05)', border:`1px solid ${BRD}`, textAlign:'center' }}>
                  <div style={{ fontSize:11, fontWeight:900, color:ACC }}>{v}</div>
                  <div style={{ fontSize:8, color:FG3, marginTop:2, letterSpacing:'0.07em' }}>{l}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* ── STATS ────────────────────────────────────────────────────────── */}
      <div style={{ padding:'0 28px 44px', background:BG0 }}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', borderRadius:14, overflow:'hidden', border:`1px solid ${BRD}` }}>
          {[['120+','Projetos entregues'],['85','Clientes satisfeitos'],['7+','Anos de mercado'],['98%','Taxa de aprovação']].map(([v,l],i) => (
            <div key={i} style={{ padding:'20px 0', textAlign:'center', background:BG1, borderLeft:i>0?`1px solid ${BRD}`:'none' }}>
              <div style={{ fontSize:26, fontWeight:900, color:ACC, letterSpacing:'-0.03em', lineHeight:1 }}>{v}</div>
              <div style={{ ...lbl, marginTop:5 }}>{l}</div>
            </div>
          ))}
        </div>
      </div>

      {/* ── PORTFOLIO GRID ───────────────────────────────────────────────── */}
      <div style={{ ...sec(), paddingTop:0, background:BG0 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:18 }}>
          <div>
            <div style={lbl}>Portfólio</div>
            <h2 style={{ margin:'8px 0 0', fontSize:24, fontWeight:900, color:FG, letterSpacing:'-0.02em' }}>Trabalhos recentes</h2>
          </div>
          <span style={{ fontSize:12, fontWeight:600, color:ACC, cursor:'pointer' }}>Ver todos →</span>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1.6fr 1fr', gap:12, marginBottom:12 }}>
          {/* Featured */}
          <div style={{ borderRadius:14, overflow:'hidden', border:`1px solid ${BRD}`, cursor:'pointer' }}>
            <div style={{ height:180, background:WORK[0].c, position:'relative', display:'flex', flexDirection:'column', justifyContent:'flex-end', padding:'18px' }}>
              <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg,transparent 30%,rgba(0,0,0,0.6) 100%)' }}/>
              <div style={{ position:'relative' }}>
                <div style={{ display:'inline-flex', padding:'3px 9px', borderRadius:999, background:'rgba(255,255,255,0.18)', backdropFilter:'blur(8px)', marginBottom:6 }}>
                  <span style={{ fontSize:8, fontWeight:700, color:'#fff', letterSpacing:'0.09em' }}>★ CASE DESTAQUE</span>
                </div>
                <div style={{ fontSize:15, fontWeight:800, color:'#fff' }}>{WORK[0].n}</div>
                <div style={{ fontSize:11, color:'rgba(255,255,255,0.55)', marginTop:3 }}>{WORK[0].cat} · {WORK[0].year}</div>
              </div>
            </div>
          </div>
          {/* Right column */}
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {WORK.slice(1,3).map((p,i) => (
              <div key={i} style={{ borderRadius:12, overflow:'hidden', border:`1px solid ${BRD}`, cursor:'pointer', flex:1 }}>
                <div style={{ height:80, background:p.c, position:'relative', display:'flex', alignItems:'flex-end', padding:'8px 12px' }}>
                  <div style={{ display:'inline-flex', padding:'2px 7px', borderRadius:999, background:'rgba(0,0,0,0.4)', backdropFilter:'blur(6px)' }}>
                    <span style={{ fontSize:8, fontWeight:700, color:'#fff', letterSpacing:'0.06em' }}>{p.cat.toUpperCase()}</span>
                  </div>
                  <div style={{ position:'absolute', top:8, right:10, fontSize:9, color:'rgba(255,255,255,0.5)' }}>{p.year}</div>
                </div>
                <div style={{ padding:'9px 12px', background:BG1, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                  <div style={{ fontSize:12, fontWeight:700, color:FG }}>{p.n}</div>
                  <span style={{ color:ACC, fontSize:13 }}>→</span>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ textAlign:'center', marginTop:6 }}>
          <div style={{ display:'inline-flex', padding:'10px 24px', borderRadius:10, border:`1px solid ${BRD}`, cursor:'pointer' }}>
            <span style={{ fontSize:12, fontWeight:600, color:FG2 }}>Ver todos os projetos</span>
          </div>
        </div>
      </div>

      {/* ── PROCESS ──────────────────────────────────────────────────────── */}
      <div style={{ padding:'44px 28px', background:BG1, borderTop:`1px solid ${BRD}`, borderBottom:`1px solid ${BRD}` }}>
        <div style={{ textAlign:'center', marginBottom:28 }}>
          <div style={lbl}>Processo</div>
          <h2 style={{ margin:'8px 0 0', fontSize:22, fontWeight:900, color:FG, letterSpacing:'-0.02em' }}>Como trabalhamos</h2>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:20 }}>
          {[
            { n:'01', title:'Briefing & Estratégia', sub:'Pesquisa de mercado, análise de concorrência e definição de objetivos.' },
            { n:'02', title:'Conceito & Criação',    sub:'3 direções criativas. Você escolhe e refinamos juntos até aprovar.' },
            { n:'03', title:'Entrega & Suporte',     sub:'Arquivos organizados, manual de uso e suporte de 60 dias.' },
          ].map((p,i) => (
            <div key={i}>
              <div style={{ width:38, height:38, borderRadius:11, background:`${ACC}22`, border:`1px solid ${ACC}44`, display:'flex', alignItems:'center', justifyContent:'center', marginBottom:14 }}>
                <span style={{ fontSize:14, fontWeight:900, color:ACC }}>{p.n}</span>
              </div>
              <div style={{ fontSize:14, fontWeight:800, color:FG, marginBottom:7 }}>{p.title}</div>
              <p style={{ fontSize:12, color:FG2, lineHeight:1.65, margin:0 }}>{p.sub}</p>
            </div>
          ))}
        </div>
      </div>

      {/* ── TESTIMONIALS ─────────────────────────────────────────────────── */}
      <div style={{ ...sec(), paddingTop:44, paddingBottom:44 }}>
        <div style={{ textAlign:'center', marginBottom:24 }}>
          <div style={lbl}>Depoimentos</div>
          <h2 style={{ margin:'8px 0 0', fontSize:22, fontWeight:900, color:FG, letterSpacing:'-0.02em' }}>O que dizem nossos clientes</h2>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
          {TESTIMONIALS.map((t,i) => (
            <div key={i} style={{ borderRadius:14, border:`1px solid ${BRD}`, background:BG1, padding:'20px 18px', display:'flex', flexDirection:'column' }}>
              <div style={{ display:'flex', gap:2, marginBottom:12 }}>
                {[...Array(t.stars)].map((_,si) => <span key={si} style={{ color:'#FADB14', fontSize:11 }}>★</span>)}
              </div>
              <p style={{ margin:'0 0 auto', fontSize:12, color:FG2, lineHeight:1.7, fontStyle:'italic', paddingBottom:14 }}>"{t.txt}"</p>
              <div style={{ display:'flex', alignItems:'center', gap:10, paddingTop:14, borderTop:`1px solid ${BRD}` }}>
                <div style={{ width:32, height:32, borderRadius:'50%', background:`${t.c}33`, border:`2px solid ${t.c}55`, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  <span style={{ fontSize:11, fontWeight:800, color:t.c }}>{t.init}</span>
                </div>
                <div>
                  <div style={{ fontSize:12, fontWeight:700, color:FG }}>{t.name}</div>
                  <div style={{ fontSize:10, color:FG3 }}>{t.role}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── PRICING ──────────────────────────────────────────────────────── */}
      <div style={{ padding:'44px 28px', background:BG1, borderTop:`1px solid ${BRD}` }}>
        <div style={{ textAlign:'center', marginBottom:24 }}>
          <div style={lbl}>Planos</div>
          <h2 style={{ margin:'8px 0 8px', fontSize:22, fontWeight:900, color:FG, letterSpacing:'-0.02em' }}>Investimento</h2>
          <p style={{ fontSize:13, color:FG2, margin:0 }}>Sem surpresas — você sabe exatamente o que está contratando.</p>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
          {PLANS.map((p,i) => (
            <div key={i} style={{ borderRadius:14, border:p.highlight?`2px solid ${ACC}`:`1px solid ${BRD}`, background:p.highlight?`${ACC}0C`:BG0, padding:'22px 18px', position:'relative', display:'flex', flexDirection:'column' }}>
              {p.highlight && (
                <div style={{ position:'absolute', top:-1, left:'50%', transform:'translateX(-50%)', padding:'3px 12px', borderRadius:'0 0 9px 9px', background:`linear-gradient(90deg,${ACC},${ACC2})` }}>
                  <span style={{ fontSize:9, fontWeight:800, color:'#fff', letterSpacing:'0.08em' }}>POPULAR</span>
                </div>
              )}
              <div style={{ fontSize:11, fontWeight:700, color:FG3, marginBottom:4, marginTop:p.highlight?12:0 }}>{p.name}</div>
              <div style={{ fontSize:22, fontWeight:900, color:FG, letterSpacing:'-0.02em', marginBottom:2 }}>{p.price}</div>
              <div style={{ fontSize:11, color:FG3, marginBottom:18 }}>{p.note}</div>
              <div style={{ display:'flex', flexDirection:'column', gap:7, flex:1, marginBottom:18 }}>
                {p.items.map((it,ii) => (
                  <div key={ii} style={{ display:'flex', alignItems:'center', gap:7 }}>
                    <div style={{ width:13, height:13, borderRadius:'50%', background:p.highlight?`${ACC}33`:'rgba(255,255,255,0.07)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                      <span style={{ fontSize:7, color:p.highlight?ACC:FG3 }}>✓</span>
                    </div>
                    <span style={{ fontSize:11, color:p.highlight?FG2:FG3 }}>{it}</span>
                  </div>
                ))}
              </div>
              <div style={{ padding:'10px 0', borderRadius:10, background:p.highlight?`linear-gradient(135deg,${ACC},${ACC2})`:'transparent', border:p.highlight?'none':`1px solid ${BRD}`, textAlign:'center', cursor:'pointer' }}>
                <span style={{ fontSize:12, fontWeight:700, color:p.highlight?'#fff':FG2 }}>Solicitar orçamento</span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── FAQ ──────────────────────────────────────────────────────────── */}
      <div style={{ ...sec(), paddingTop:44, paddingBottom:44, borderTop:`1px solid ${BRD}` }}>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1.4fr', gap:40, alignItems:'start' }}>
          <div>
            <div style={lbl}>FAQ</div>
            <h2 style={{ margin:'8px 0 10px', fontSize:22, fontWeight:900, color:FG, letterSpacing:'-0.02em' }}>Perguntas frequentes</h2>
            <p style={{ fontSize:13, color:FG2, lineHeight:1.65, margin:'0 0 20px' }}>Não encontrou o que procura? Entre em contato diretamente.</p>
            <div style={{ padding:'14px 16px', borderRadius:12, border:`1px solid ${BRD}`, background:BG1, display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:30, height:30, borderRadius:8, background:`${ACC}22`, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <span style={{ fontSize:13 }}>💬</span>
              </div>
              <div>
                <div style={{ fontSize:12, fontWeight:700, color:FG }}>Fale conosco</div>
                <div style={{ fontSize:10, color:FG3 }}>Resposta em até 24h</div>
              </div>
            </div>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {FAQS.map((f,i) => (
              <div key={i} style={{ borderRadius:12, border:`1px solid ${openFaq===i?ACC+'55':BRD}`, background:BG1, overflow:'hidden' }}>
                <div onClick={()=>setOpenFaq(openFaq===i?null:i)} style={{ padding:'13px 16px', display:'flex', justifyContent:'space-between', alignItems:'center', cursor:'pointer', gap:12 }}>
                  <span style={{ fontSize:13, fontWeight:700, color:FG }}>{f.q}</span>
                  <span style={{ fontSize:15, color:ACC, flexShrink:0, transform:openFaq===i?'rotate(45deg)':'none', transition:'transform 200ms', display:'inline-block' }}>+</span>
                </div>
                {openFaq===i && (
                  <div style={{ padding:'0 16px 14px' }}>
                    <p style={{ margin:0, fontSize:12, color:FG2, lineHeight:1.7 }}>{f.a}</p>
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── CTA FINAL ────────────────────────────────────────────────────── */}
      <div style={{ padding:'52px 28px', background:BG1, borderTop:`1px solid ${BRD}`, textAlign:'center', position:'relative', overflow:'hidden' }}>
        <div style={{ position:'absolute', top:'50%', left:'50%', transform:'translate(-50%,-50%)', width:360, height:180, background:`radial-gradient(ellipse,${ACC}28 0%,transparent 70%)`, pointerEvents:'none' }}/>
        <div style={{ position:'relative' }}>
          <div style={{ ...lbl, textAlign:'center', marginBottom:10 }}>Interessado em trabalhar juntos?</div>
          <h2 style={{ margin:'0 0 10px', fontSize:28, fontWeight:900, color:FG, letterSpacing:'-0.02em', lineHeight:1.15 }}>
            Vamos criar algo<br/>
            <span style={{ fontStyle:'italic', background:`linear-gradient(90deg,${ACC2},${ACC})`, WebkitBackgroundClip:'text', WebkitTextFillColor:'transparent', backgroundClip:'text' }}>incrível juntos.</span>
          </h2>
          <p style={{ fontSize:13, color:FG2, maxWidth:380, margin:'0 auto 24px', lineHeight:1.65 }}>
            Conte sobre seu projeto e receba uma proposta personalizada em até 24 horas.
          </p>
          <div style={{ display:'inline-flex', padding:'13px 32px', borderRadius:12, background:`linear-gradient(135deg,${ACC},${ACC2})`, cursor:'pointer' }}>
            <span style={{ fontSize:14, fontWeight:800, color:'#fff' }}>Agendar conversa →</span>
          </div>
        </div>
      </div>

      {/* ── FOOTER ───────────────────────────────────────────────────────── */}
      <div style={{ padding:'36px 28px 20px', background:'#050810', borderTop:`1px solid ${BRD}` }}>
        <div style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr 1fr 1fr', gap:20, marginBottom:28 }}>
          <div>
            <div style={{ display:'flex', alignItems:'center', gap:7, marginBottom:10 }}>
              <div style={{ width:24, height:24, borderRadius:6, background:`linear-gradient(135deg,${ACC},${ACC2})` }}/>
              <span style={{ fontSize:13, fontWeight:800, color:FG }}>Estúdio Norte</span>
            </div>
            <p style={{ fontSize:11, color:FG3, lineHeight:1.65, margin:'0 0 14px', maxWidth:180 }}>Design estratégico para marcas que querem crescer com identidade.</p>
            <div style={{ display:'flex', gap:8 }}>
              {['in','ig','be','yt'].map((s,i) => (
                <div key={i} style={{ width:26, height:26, borderRadius:6, background:'rgba(255,255,255,0.05)', border:`1px solid ${BRD}`, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
                  <span style={{ fontSize:8, fontWeight:700, color:FG3 }}>{s}</span>
                </div>
              ))}
            </div>
          </div>
          {[
            { h:'Empresa',   links:['Sobre nós','Portfólio','Blog','Carreiras'] },
            { h:'Serviços',  links:['Branding','Web Design','UI/UX','Motion'] },
            { h:'Contato',   links:['Orçamento','WhatsApp','E-mail','Instagram'] },
          ].map((col,i) => (
            <div key={i}>
              <div style={{ fontSize:10, fontWeight:700, color:FG, marginBottom:12, textTransform:'uppercase', letterSpacing:'0.09em' }}>{col.h}</div>
              {col.links.map((l,li) => (
                <div key={li} style={{ fontSize:11, color:FG3, marginBottom:7, cursor:'pointer' }}>{l}</div>
              ))}
            </div>
          ))}
        </div>
        <div style={{ borderTop:`1px solid ${BRD}`, paddingTop:16, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <span style={{ fontSize:10, color:FG3 }}>© 2026 Estúdio Norte. Todos os direitos reservados.</span>
          <div style={{ display:'flex', gap:14 }}>
            {['Privacidade','Termos','Cookies'].map(l => (
              <span key={l} style={{ fontSize:10, color:FG3, cursor:'pointer' }}>{l}</span>
            ))}
          </div>
        </div>
      </div>

    </div>
  );
}

function BioLinkContent({ st }) {
  const LINKS = [
    { l:'Portfolio',  sub:'Veja meus trabalhos',    icon:'◈', c:'#1D39C4' },
    { l:'Instagram',  sub:'@anasilvadesign',         icon:'◎', c:'#FA541C' },
    { l:'LinkedIn',   sub:'Conecte-se comigo',       icon:'◻', c:'#0A66C2' },
    { l:'WhatsApp',   sub:'Fale diretamente',        icon:'◉', c:'#22C55E' },
    { l:'Newsletter', sub:'Receba novidades mensais',icon:'◈', c:'#7C3AED' },
  ];
  const STATS = [{ v:'4.2k', l:'Seguidores' }, { v:'120+', l:'Projetos' }, { v:'7 anos', l:'Experiência' }];
  return (
    <div style={{ maxWidth:420, margin:'0 auto', display:'flex', flexDirection:'column', alignItems:'center' }}>
      {/* Avatar + Identity */}
      <div style={{ position:'relative', marginBottom:16 }}>
        <div style={{ width:84, height:84, borderRadius:'50%', background:'linear-gradient(135deg,#FA541C,#FADB14)', display:'flex', alignItems:'center', justifyContent:'center', boxShadow:`0 0 0 3px ${st.cardBorder}, 0 0 0 5px ${st.accent}` }}>
          <span style={{ fontSize:26, fontWeight:800, color:'#fff' }}>AS</span>
        </div>
        <div style={{ position:'absolute', bottom:2, right:2, width:20, height:20, borderRadius:'50%', background:'#22C55E', border:`2px solid ${st.cardBg||'#fff'}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <span style={{ fontSize:9, color:'#fff' }}>✓</span>
        </div>
      </div>
      <div style={{ fontSize:20, fontWeight:800, color:st.fg, marginBottom:4 }}>Ana Silva</div>
      <div style={{ fontSize:13, color:st.accent, fontWeight:600, marginBottom:8 }}>Designer Gráfica & Estrategista de Marca</div>
      <div style={{ fontSize:12, color:st.mutedFg, marginBottom:20, textAlign:'center', lineHeight:1.65, maxWidth:320 }}>Criando identidades visuais que conectam marcas às pessoas certas. São Paulo, Brasil 🇧🇷</div>

      {/* Stats */}
      <div style={{ display:'flex', gap:0, width:'100%', marginBottom:24, borderRadius:12, overflow:'hidden', border:`1px solid ${st.cardBorder}` }}>
        {STATS.map((s,i) => (
          <div key={i} style={{ flex:1, padding:'14px 0', textAlign:'center', background:st.cardBg, borderLeft:i>0?`1px solid ${st.cardBorder}`:'none' }}>
            <div style={{ fontSize:17, fontWeight:800, color:st.accent }}>{s.v}</div>
            <div style={{ fontSize:10, color:st.mutedFg, marginTop:3, textTransform:'uppercase', letterSpacing:'0.07em' }}>{s.l}</div>
          </div>
        ))}
      </div>

      {/* Links */}
      <div style={{ display:'flex', flexDirection:'column', gap:10, width:'100%' }}>
        {LINKS.map((l,i) => (
          <div key={i} style={{ padding:'14px 20px', borderRadius:13, border:`1px solid ${st.cardBorder}`, background:st.cardBg, display:'flex', alignItems:'center', gap:14, cursor:'pointer' }}>
            <div style={{ width:36, height:36, borderRadius:10, background:l.c+'22', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              <span style={{ color:l.c, fontSize:16 }}>{l.icon}</span>
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:14, fontWeight:700, color:st.fg }}>{l.l}</div>
              <div style={{ fontSize:11, color:st.mutedFg, marginTop:2 }}>{l.sub}</div>
            </div>
            <span style={{ color:st.mutedFg, fontSize:14 }}>→</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function AprovacaoContent({ st }) {
  const ROWS = [
    { l:'Cliente',  v:'Astra Cosméticos'        },
    { l:'Projeto',  v:'Rebranding Completo 2026' },
    { l:'Valor',    v:'R$ 8.500,00'             },
    { l:'Prazo',    v:'45 dias úteis'            },
    { l:'Validade', v:'Até 20/05/2026'           },
  ];
  const STEPS = [
    { n:'Enviado',    done:true  },
    { n:'Em análise', done:true  },
    { n:'Aguardando', done:false, active:true },
    { n:'Aprovado',   done:false },
  ];
  const DELIVERABLES = ['Diagnóstico de marca', 'Logo principal + variações', 'Paleta de cores & tipografia', 'Manual de marca (brandbook)', 'Aplicações (mockups)'];
  return (
    <div style={{ maxWidth:580, margin:'0 auto' }}>

      {/* Progress tracker */}
      <div style={{ display:'flex', alignItems:'center', marginBottom:28, padding:'16px 20px', borderRadius:12, border:`1px solid ${st.cardBorder}`, background:st.cardBg }}>
        {STEPS.map((s,i) => (
          <React.Fragment key={i}>
            <div style={{ display:'flex', flexDirection:'column', alignItems:'center', gap:6 }}>
              <div style={{ width:28, height:28, borderRadius:'50%', background:s.done?st.accent:s.active?st.accent+'30':'transparent', border:`2px solid ${s.done||s.active?st.accent:st.cardBorder}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
                {s.done ? <span style={{ fontSize:11, color:'#fff' }}>✓</span> : s.active ? <div style={{ width:8, height:8, borderRadius:'50%', background:st.accent }}/> : null}
              </div>
              <span style={{ fontSize:10, fontWeight:s.active?700:500, color:s.done||s.active?st.accent:st.mutedFg, whiteSpace:'nowrap' }}>{s.n}</span>
            </div>
            {i < STEPS.length-1 && (
              <div style={{ flex:1, height:2, background:STEPS[i+1].done||s.done?st.accent:st.cardBorder, margin:'0 8px', marginBottom:18, opacity:s.done?1:0.35 }}/>
            )}
          </React.Fragment>
        ))}
      </div>

      {/* Summary */}
      <div style={{ padding:'20px 24px', borderRadius:12, border:`1px solid ${st.cardBorder}`, background:st.cardBg, marginBottom:16 }}>
        <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:st.mutedFg, marginBottom:16 }}>Resumo da proposta</div>
        {ROWS.map((r,i) => (
          <div key={i} style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 0', borderBottom:i<ROWS.length-1?`1px solid ${st.cardBorder}`:'none' }}>
            <span style={{ fontSize:13, color:st.mutedFg }}>{r.l}</span>
            <span style={{ fontSize:13, fontWeight:700, color:st.fg }}>{r.v}</span>
          </div>
        ))}
      </div>

      {/* Deliverables */}
      <div style={{ padding:'16px 20px', borderRadius:12, border:`1px solid ${st.cardBorder}`, background:st.cardBg, marginBottom:16 }}>
        <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.08em', textTransform:'uppercase', color:st.mutedFg, marginBottom:12 }}>Entregáveis incluídos</div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {DELIVERABLES.map((d,i) => (
            <div key={i} style={{ display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:16, height:16, borderRadius:4, background:st.accent+'22', border:`1px solid ${st.accent}44`, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                <span style={{ fontSize:9, color:st.accent }}>✓</span>
              </div>
              <span style={{ fontSize:13, color:st.fg }}>{d}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Signature */}
      <div style={{ padding:'14px 18px', borderRadius:12, border:`1px solid ${st.cardBorder}`, background:st.cardBg, marginBottom:16 }}>
        <div style={{ fontSize:11, fontWeight:700, color:st.mutedFg, marginBottom:10, textTransform:'uppercase', letterSpacing:'0.06em' }}>Assinatura digital</div>
        <div style={{ height:52, borderRadius:8, border:`2px dashed ${st.accent}44`, background:st.accent+'08', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
          <span style={{ fontSize:16, color:st.mutedFg }}>✎</span>
          <span style={{ fontSize:12, color:st.mutedFg }}>Assine aqui para confirmar</span>
        </div>
      </div>

      {/* CTAs */}
      <div style={{ display:'flex', gap:12 }}>
        <div style={{ flex:2, padding:'15px 0', borderRadius:11, background:st.btnBg, textAlign:'center', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
          <span style={{ fontSize:14, fontWeight:700, color:'#fff' }}>✓ Aprovar proposta</span>
        </div>
        <div style={{ flex:1, padding:'15px 0', borderRadius:11, border:`1px solid ${st.cardBorder}`, background:st.cardBg, textAlign:'center', cursor:'pointer' }}>
          <span style={{ fontSize:13, fontWeight:600, color:st.mutedFg }}>Solicitar ajustes</span>
        </div>
      </div>
    </div>
  );
}

function FormContent({ page, st }) {
  const isBriefing = page.kind === 'Briefing';
  const FIELDS = isBriefing
    ? [
        { l:'Nome da empresa',      sub:'Como sua empresa se chama?',       tall:false },
        { l:'Segmento de atuação',  sub:'Ex: alimentação, tecnologia, saúde', tall:false },
        { l:'Descreva o projeto',   sub:'O que você precisa e qual o objetivo?', tall:true },
        { l:'Prazo desejado',       sub:'Quando você precisa que esteja pronto?', tall:false },
        { l:'Orçamento aproximado', sub:'Ter uma referência nos ajuda a planejar melhor', tall:false },
      ]
    : [
        { l:'Seu nome',  sub:'Como devo te chamar?',    tall:false },
        { l:'Email',     sub:'Para onde enviamos a resposta', tall:false },
        { l:'Assunto',   sub:'Resumo do que precisa',   tall:false },
        { l:'Mensagem',  sub:'Conta mais detalhes aqui', tall:true  },
      ];
  return (
    <div style={{ maxWidth:540, margin:'0 auto' }}>
      {/* Intro */}
      <div style={{ marginBottom:24, padding:'16px 20px', borderRadius:12, border:`1px solid ${st.cardBorder}`, background:st.accent+'10', borderLeftColor:st.accent, borderLeftWidth:3 }}>
        <div style={{ fontSize:13, fontWeight:700, color:st.accent, marginBottom:4 }}>
          {isBriefing ? '📋 Briefing de projeto' : '✉️ Formulário de contato'}
        </div>
        <div style={{ fontSize:12, color:st.mutedFg, lineHeight:1.55 }}>
          {isBriefing
            ? 'Preencha com o máximo de detalhes — quanto mais soubermos, melhor a proposta que enviamos.'
            : 'Preencha o formulário e retornamos em até 24 horas úteis.'}
        </div>
      </div>

      {/* Fields */}
      <div style={{ display:'flex', flexDirection:'column', gap:18 }}>
        {FIELDS.map((f,i) => (
          <div key={i}>
            <div style={{ fontSize:12, fontWeight:700, color:st.fg, marginBottom:3 }}>{f.l}</div>
            <div style={{ fontSize:11, color:st.mutedFg, marginBottom:7 }}>{f.sub}</div>
            <div style={{ height:f.tall?96:42, borderRadius:9, border:`1px solid ${st.cardBorder}`, background:st.cardBg }}/>
          </div>
        ))}
      </div>

      {/* Privacy note */}
      <div style={{ marginTop:14, marginBottom:16, display:'flex', alignItems:'center', gap:8 }}>
        <div style={{ width:14, height:14, borderRadius:3, border:`1px solid ${st.cardBorder}`, background:st.accent+'22', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
          <span style={{ fontSize:9, color:st.accent }}>✓</span>
        </div>
        <span style={{ fontSize:11, color:st.mutedFg }}>Seus dados são protegidos e não serão compartilhados com terceiros.</span>
      </div>

      <div style={{ padding:'15px 0', borderRadius:11, background:st.btnBg, textAlign:'center', cursor:'pointer' }}>
        <span style={{ fontSize:14, fontWeight:700, color:'#fff' }}>{isBriefing ? '📋 Enviar briefing' : '✉️ Enviar mensagem'}</span>
      </div>
    </div>
  );
}

function AgendaContent({ st }) {
  const SERVICES = [
    { l:'Consultoria de Branding',    dur:'60 min', price:'Gratuito' },
    { l:'Revisão de Identidade Visual', dur:'45 min', price:'R$ 150' },
    { l:'Mentoria de Carreira',        dur:'90 min', price:'R$ 280' },
  ];
  const DAYS = [
    { label:'Seg', date:'11', slots:[{ time:'09:00', avail:true },{ time:'11:00', avail:false },{ time:'14:00', avail:true }] },
    { label:'Ter', date:'12', slots:[{ time:'09:00', avail:true },{ time:'10:00', avail:true  },{ time:'15:00', avail:false}] },
    { label:'Qua', date:'13', slots:[{ time:'09:00', avail:false},{ time:'13:00', avail:true  },{ time:'16:00', avail:true }] },
    { label:'Qui', date:'14', slots:[{ time:'10:00', avail:true },{ time:'14:00', avail:true  },{ time:'16:00', avail:true }] },
    { label:'Sex', date:'15', slots:[{ time:'09:00', avail:false},{ time:'11:00', avail:true  }] },
  ];
  const [selectedSvc, setSelectedSvc] = React.useState(0);
  return (
    <div style={{ maxWidth:520, margin:'0 auto' }}>
      {/* Service selector */}
      <div style={{ marginBottom:24 }}>
        <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.09em', color:st.mutedFg, marginBottom:12 }}>Tipo de reunião</div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {SERVICES.map((s,i) => (
            <div key={i} onClick={() => setSelectedSvc(i)} style={{ padding:'14px 18px', borderRadius:12, border:`1px solid ${selectedSvc===i?st.accent:st.cardBorder}`, background:selectedSvc===i?st.accent+'12':st.cardBg, cursor:'pointer', display:'flex', justifyContent:'space-between', alignItems:'center', transition:'all 150ms' }}>
              <div>
                <div style={{ fontSize:13, fontWeight:700, color:st.fg }}>{s.l}</div>
                <div style={{ fontSize:11, color:st.mutedFg, marginTop:3 }}>⏱ {s.dur}</div>
              </div>
              <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                <span style={{ fontSize:13, fontWeight:700, color:selectedSvc===i?st.accent:st.mutedFg }}>{s.price}</span>
                {selectedSvc===i && <div style={{ width:18, height:18, borderRadius:'50%', background:st.accent, display:'flex', alignItems:'center', justifyContent:'center' }}><span style={{ fontSize:10, color:'#fff' }}>✓</span></div>}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Calendar grid */}
      <div style={{ marginBottom:20 }}>
        <div style={{ fontSize:11, fontWeight:700, textTransform:'uppercase', letterSpacing:'0.09em', color:st.mutedFg, marginBottom:12 }}>Escolha data e horário — Maio 2026</div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:8 }}>
          {DAYS.map((d,di) => (
            <div key={di}>
              <div style={{ textAlign:'center', marginBottom:8 }}>
                <div style={{ fontSize:10, fontWeight:600, color:st.mutedFg, textTransform:'uppercase', letterSpacing:'0.05em' }}>{d.label}</div>
                <div style={{ fontSize:18, fontWeight:800, color:st.fg, lineHeight:1.2 }}>{d.date}</div>
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
                {d.slots.map((s,si) => (
                  <div key={si} style={{ padding:'6px 4px', borderRadius:7, border:`1px solid ${s.avail?st.accent+'55':st.cardBorder}`, background:s.avail?st.accent+'14':st.cardBg, textAlign:'center', cursor:s.avail?'pointer':'default', opacity:s.avail?1:0.4 }}>
                    <span style={{ fontSize:11, fontWeight:s.avail?700:400, color:s.avail?st.accent:st.mutedFg }}>{s.time}</span>
                  </div>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ padding:'15px 0', borderRadius:11, background:st.btnBg, textAlign:'center', cursor:'pointer' }}>
        <span style={{ fontSize:14, fontWeight:700, color:'#fff' }}>Confirmar agendamento</span>
      </div>
    </div>
  );
}

function PageContent({ page, st }) {
  if (page.kind === 'Portfolio') return <PortfolioContent st={st}/>;
  if (page.kind === 'Bio Link')  return <BioLinkContent st={st}/>;
  if (page.kind === 'Aprovação') return <AprovacaoContent st={st}/>;
  if (page.kind === 'Agenda')    return <AgendaContent st={st}/>;
  return <FormContent page={page} st={st}/>;
}

// ─── Block renderers (editor preview) ────────────────────────────────────────
const BLOCK_ACCENTS = ['#1D39C4','#FA541C','#22C55E','#7C3AED','#36CFC9','#FADB14'];

function NavBlock({ data, st }) {
  return (
    <div style={{ padding:'14px 32px', display:'flex', justifyContent:'space-between', alignItems:'center', borderBottom:`1px solid ${st.cardBorder}` }}>
      <span style={{ fontSize:15, fontWeight:800, color:st.accent }}>{data.brand||'Minha marca'}</span>
      <div style={{ display:'flex', gap:20 }}>
        {['Home','Sobre','Portfólio','Contato'].map(l => (
          <span key={l} style={{ fontSize:12, color:st.mutedFg, cursor:'pointer' }}>{l}</span>
        ))}
      </div>
    </div>
  );
}

function HeroBlock({ data, page, st }) {
  return (
    <div style={{ background:page.c, padding:'52px 48px 44px', position:'relative', overflow:'hidden' }}>
      <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg,rgba(0,0,0,0) 0%,rgba(0,0,0,0.22) 100%)' }}/>
      <div style={{ position:'relative' }}>
        <h1 style={{ margin:'0 0 14px', fontSize:38, fontWeight:800, color:'#fff', lineHeight:1.15 }}>{data.headline||'Título principal aqui'}</h1>
        <p style={{ margin:'0 0 24px', fontSize:15, color:'rgba(255,255,255,0.82)', lineHeight:1.65, maxWidth:540 }}>{data.sub||'Subtítulo descritivo da sua página'}</p>
        {data.cta && (
          <div style={{ display:'inline-flex', padding:'13px 28px', borderRadius:10, background:'rgba(255,255,255,0.18)', backdropFilter:'blur(8px)', cursor:'pointer' }}>
            <span style={{ fontSize:14, fontWeight:700, color:'#fff' }}>{data.cta}</span>
          </div>
        )}
      </div>
    </div>
  );
}

function TextoBlock({ data, st }) {
  return (
    <div style={{ padding:'32px 48px' }}>
      {data.heading && <h2 style={{ margin:'0 0 14px', fontSize:24, fontWeight:800, color:st.fg }}>{data.heading}</h2>}
      <p style={{ margin:0, fontSize:15, color:st.mutedFg, lineHeight:1.75, maxWidth:640 }}>{data.body||'Texto aqui...'}</p>
    </div>
  );
}

function ImagemBlock({ data, st }) {
  return (
    <div style={{ padding:'20px 48px 28px' }}>
      {data.src
        ? <img src={data.src} alt={data.caption||''} style={{ width:'100%', borderRadius:12, display:'block' }}/>
        : <div style={{ width:'100%', height:200, borderRadius:12, border:`2px dashed ${st.cardBorder}`, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:8 }}>
            <div style={{ fontSize:28 }}>🖼</div>
            <span style={{ fontSize:12, color:st.mutedFg }}>Cole a URL da imagem nas opções do bloco</span>
          </div>
      }
      {data.caption && <div style={{ marginTop:10, fontSize:12, color:st.mutedFg, textAlign:'center' }}>{data.caption}</div>}
    </div>
  );
}

function VideoBlock({ data, st }) {
  return (
    <div style={{ padding:'20px 48px 28px' }}>
      <div style={{ width:'100%', paddingBottom:'56.25%', position:'relative', borderRadius:12, overflow:'hidden', background:st.cardBg, border:`1px solid ${st.cardBorder}` }}>
        <div style={{ position:'absolute', inset:0, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:10 }}>
          <div style={{ width:52, height:52, borderRadius:'50%', background:st.accent+'22', display:'flex', alignItems:'center', justifyContent:'center' }}>
            <div style={{ width:0, height:0, borderStyle:'solid', borderWidth:'9px 0 9px 18px', borderColor:`transparent transparent transparent ${st.accent}`, marginLeft:5 }}/>
          </div>
          <span style={{ fontSize:12, color:st.mutedFg }}>{data.title||'Adicione a URL do vídeo'}</span>
        </div>
      </div>
    </div>
  );
}

function ServicosBlock({ data, st }) {
  const items = (data.items||'Branding, Web Design, Motion, UI/UX').split(',').map(s=>s.trim()).filter(Boolean);
  return (
    <div style={{ padding:'32px 48px' }}>
      {data.heading && <h2 style={{ margin:'0 0 20px', fontSize:22, fontWeight:800, color:st.fg }}>{data.heading}</h2>}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill,minmax(160px,1fr))', gap:14 }}>
        {items.map((item, i) => (
          <div key={i} style={{ padding:'18px 16px', borderRadius:12, border:`1px solid ${st.cardBorder}`, background:st.cardBg }}>
            <div style={{ width:36, height:36, borderRadius:8, background:BLOCK_ACCENTS[i%BLOCK_ACCENTS.length]+'22', marginBottom:12, display:'flex', alignItems:'center', justifyContent:'center' }}>
              <div style={{ width:16, height:16, borderRadius:4, background:BLOCK_ACCENTS[i%BLOCK_ACCENTS.length] }}/>
            </div>
            <div style={{ fontSize:13, fontWeight:700, color:st.fg }}>{item}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function PortfolioBlock({ data, st }) {
  const items = (data.items||'Projeto A, Projeto B, Projeto C, Projeto D').split(',').map(s=>s.trim()).filter(Boolean);
  const COLORS = ['linear-gradient(135deg,#1D39C4,#36CFC9)','linear-gradient(135deg,#FA541C,#FADB14)','linear-gradient(135deg,#7C3AED,#FA541C)','linear-gradient(135deg,#22C55E,#1890FF)'];
  return (
    <div style={{ padding:'32px 48px' }}>
      {data.heading && <h2 style={{ margin:'0 0 20px', fontSize:22, fontWeight:800, color:st.fg }}>{data.heading}</h2>}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:16 }}>
        {items.slice(0,4).map((item, i) => (
          <div key={i} style={{ borderRadius:12, overflow:'hidden', border:`1px solid ${st.cardBorder}`, cursor:'pointer' }}>
            <div style={{ height:110, background:COLORS[i%COLORS.length] }}/>
            <div style={{ padding:'12px 14px', background:st.cardBg }}>
              <div style={{ fontSize:13, fontWeight:700, color:st.fg }}>{item}</div>
              <div style={{ fontSize:11, color:st.mutedFg, marginTop:3 }}>Ver projeto →</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function SobreBlock({ data, st }) {
  return (
    <div style={{ padding:'32px 48px', display:'grid', gridTemplateColumns:'1fr 1fr', gap:32, alignItems:'center' }}>
      <div>
        {data.heading && <h2 style={{ margin:'0 0 14px', fontSize:24, fontWeight:800, color:st.fg }}>{data.heading}</h2>}
        <p style={{ margin:0, fontSize:14, color:st.mutedFg, lineHeight:1.75 }}>{data.body||'Conte sobre você ou sua empresa...'}</p>
      </div>
      <div style={{ height:180, borderRadius:12, background:`linear-gradient(135deg,${st.accent}22,${st.accent}44)`, border:`1px solid ${st.cardBorder}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <div style={{ width:64, height:64, borderRadius:'50%', background:st.accent, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <span style={{ fontSize:24, fontWeight:800, color:'#fff' }}>✦</span>
        </div>
      </div>
    </div>
  );
}

function EstatisticasBlock({ data, st }) {
  const items = (data.items||'120+ Projetos, 85 Clientes, 7 Anos').split(',').map(s => {
    const parts = s.trim().split(' ');
    return { value: parts[0], label: parts.slice(1).join(' ') };
  });
  return (
    <div style={{ display:'flex', gap:0, borderTop:`1px solid ${st.cardBorder}`, borderBottom:`1px solid ${st.cardBorder}` }}>
      {items.map((item, i) => (
        <div key={i} style={{ flex:1, textAlign:'center', borderLeft:i>0?`1px solid ${st.cardBorder}`:'none', padding:'24px 0' }}>
          <div style={{ fontSize:32, fontWeight:900, color:st.accent, fontFamily:'var(--font-display)' }}>{item.value}</div>
          <div style={{ fontSize:12, color:st.mutedFg, marginTop:4, textTransform:'uppercase', letterSpacing:'0.07em' }}>{item.label}</div>
        </div>
      ))}
    </div>
  );
}

function TimelineBlock({ data, st }) {
  const items = (data.items||'2018 Fundação, 2020 Expansão, 2024 Novos mercados').split(',').map(s=>s.trim());
  return (
    <div style={{ padding:'32px 48px' }}>
      {data.heading && <h2 style={{ margin:'0 0 24px', fontSize:22, fontWeight:800, color:st.fg }}>{data.heading}</h2>}
      <div style={{ position:'relative', paddingLeft:28 }}>
        <div style={{ position:'absolute', left:10, top:8, bottom:8, width:2, background:st.cardBorder }}/>
        {items.map((item, i) => (
          <div key={i} style={{ position:'relative', marginBottom:i<items.length-1?18:0 }}>
            <div style={{ position:'absolute', left:-22, top:4, width:10, height:10, borderRadius:'50%', background:st.accent }}/>
            <div style={{ fontSize:14, fontWeight:600, color:st.fg }}>{item}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function DepoimentosBlock({ data, st }) {
  const ITEMS = [
    { name:'Ana Lima',      txt:'Excelente trabalho! Superou todas as expectativas.' },
    { name:'Carlos Mendes', txt:'Profissionalismo e criatividade incríveis.' },
  ];
  return (
    <div style={{ padding:'32px 48px' }}>
      {data.heading && <h2 style={{ margin:'0 0 20px', fontSize:22, fontWeight:800, color:st.fg }}>{data.heading}</h2>}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
        {ITEMS.map((d, i) => (
          <div key={i} style={{ padding:'20px', borderRadius:12, border:`1px solid ${st.cardBorder}`, background:st.cardBg }}>
            <p style={{ margin:'0 0 14px', fontSize:14, color:st.fg, lineHeight:1.65, fontStyle:'italic' }}>"{d.txt}"</p>
            <div style={{ fontSize:12, fontWeight:700, color:st.accent }}>— {d.name}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function CTABlock({ data, st }) {
  return (
    <div style={{ padding:'40px 48px', textAlign:'center', background:`${st.accent}08` }}>
      <h2 style={{ margin:'0 0 10px', fontSize:28, fontWeight:800, color:st.fg }}>{data.heading||'Vamos conversar?'}</h2>
      {data.sub && <p style={{ margin:'0 0 22px', fontSize:14, color:st.mutedFg }}>{data.sub}</p>}
      <div style={{ display:'inline-flex', padding:'14px 32px', borderRadius:10, background:st.btnBg, cursor:'pointer' }}>
        <span style={{ fontSize:14, fontWeight:700, color:'#fff' }}>{data.cta||'Entrar em contato'}</span>
      </div>
    </div>
  );
}

function RodapeBlock({ data, page, st }) {
  return (
    <div style={{ borderTop:`1px solid ${st.cardBorder}`, padding:'24px 48px', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
      <span style={{ fontSize:14, fontWeight:800, color:st.accent }}>{data.brand||page.t.split('·')[0].trim()}</span>
      <span style={{ fontSize:11, color:st.mutedFg }}>{data.copy||'© 2026 Todos os direitos reservados.'}</span>
    </div>
  );
}

function BlockPreview({ block, page, st, ps }) {
  const data = block.data || {};
  if (block.type === 'Menu / Logo' || block.type === 'Header') return <NavBlock data={data} st={st}/>;
  if (block.type === 'Hero')         return <HeroBlock data={data} page={page} st={st}/>;
  if (block.type === 'Texto')        return <TextoBlock data={data} st={st}/>;
  if (block.type === 'Imagem')       return <ImagemBlock data={data} st={st}/>;
  if (block.type === 'Vídeo')        return <VideoBlock data={data} st={st}/>;
  if (block.type === 'Carrossel' || block.type === 'Serviços') return <ServicosBlock data={data} st={st}/>;
  if (block.type === 'Portfólio')    return <PortfolioBlock data={data} st={st}/>;
  if (block.type === 'Sobre')        return <SobreBlock data={data} st={st}/>;
  if (block.type === 'Estatísticas') return <EstatisticasBlock data={data} st={st}/>;
  if (block.type === 'Timeline')     return <TimelineBlock data={data} st={st}/>;
  if (block.type === 'Depoimentos')  return <DepoimentosBlock data={data} st={st}/>;
  if (block.type === 'CTA' || block.type === 'CTA Final') return <CTABlock data={data} st={st}/>;
  if (block.type === 'Rodapé')       return <RodapeBlock data={data} page={page} st={st}/>;
  return (
    <div style={{ padding:'20px 48px', display:'flex', alignItems:'center', justifyContent:'center', borderTop:`1px dashed ${st.cardBorder}` }}>
      <span style={{ fontSize:12, color:st.mutedFg, fontStyle:'italic' }}>{block.type} · bloco</span>
    </div>
  );
}

// ─── Visualizar Página Modal ──────────────────────────────────────────────────
function VisualizarPaginaModal({ page, onClose, onEdit, onStatusChange }) {
  const ps     = PAGE_STYLES.find(s => s.id === (page.estilo||'moderno')) || PAGE_STYLES[0];
  const isDark = page.estilo !== 'minimalista';
  const st = {
    fg:         ps.textC,
    accent:     ps.accent,
    btnBg:      ps.btnBg,
    cardBg:     isDark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.04)',
    cardBorder: isDark ? 'rgba(255,255,255,0.09)' : 'rgba(0,0,0,0.10)',
    mutedFg:    isDark ? 'rgba(255,255,255,0.48)' : 'rgba(0,0,0,0.42)',
  };
  const [copied,      setCopied]      = useState(false);
  const [viewDevice,  setViewDevice]  = useState('desktop');
  const DEVICES = [{ id:'desktop', icon:'▣', w:null }, { id:'tablet', icon:'▭', w:768 }, { id:'mobile', icon:'▯', w:390 }];

  const STATUS_CFG = {
    publicado: { label:'Publicado', dot:'#22C55E', nextStatus:'privado',   nextLabel:'Tornar privado' },
    privado:   { label:'Privado',   dot:'#1D39C4', nextStatus:'publicado', nextLabel:'Publicar'       },
    rascunho:  { label:'Rascunho',  dot:'#8B8B9B', nextStatus:'publicado', nextLabel:'Publicar'       },
  };
  const sc = STATUS_CFG[page.status] || STATUS_CFG.rascunho;

  function copyLink() {
    window.__toast?.('Link copiado!', { tone:'success' });
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  function toggleStatus() {
    const tone = sc.nextStatus === 'publicado' ? 'success' : sc.nextStatus === 'privado' ? 'brand' : 'neutral';
    onStatusChange?.({ ...page, status: sc.nextStatus, tone });
    window.__toast?.(`Página ${sc.nextStatus === 'publicado' ? 'publicada' : 'tornada privada'}!`, { tone: sc.nextStatus === 'publicado' ? 'success' : 'brand' });
  }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.82)', backdropFilter:'blur(8px)', zIndex:200, overflowY:'auto', display:'flex', flexDirection:'column', alignItems:'center', padding:'20px 24px' }}>

      {/* Browser bar */}
      <div onClick={e=>e.stopPropagation()} style={{ width:'min(860px,100%)', marginBottom:12, display:'flex', alignItems:'center', gap:10, background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:12, padding:'10px 16px', flexShrink:0 }}>
        <div style={{ display:'flex', gap:5, flexShrink:0 }}>
          <div style={{ width:10, height:10, borderRadius:'50%', background:'#FF5F56' }}/>
          <div style={{ width:10, height:10, borderRadius:'50%', background:'#FEBC2E' }}/>
          <div style={{ width:10, height:10, borderRadius:'50%', background:'#28C840' }}/>
        </div>
        <div style={{ flex:1, height:26, borderRadius:6, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', padding:'0 10px', gap:6, minWidth:0 }}>
          <div style={{ width:8, height:8, borderRadius:'50%', background:sc.dot, flexShrink:0 }}/>
          <span style={{ fontSize:11, fontFamily:'var(--font-mono)', color:'var(--fg-muted)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{page.url}</span>
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:7, flexShrink:0 }}>
          {/* Device toggle */}
          <div style={{ display:'flex', gap:2, background:'var(--bg-elevated)', borderRadius:7, padding:3, border:'1px solid var(--border-subtle)' }}>
            {DEVICES.map(d => (
              <button key={d.id} onClick={() => setViewDevice(d.id)} title={d.id}
                style={{ padding:'3px 7px', borderRadius:4, border:'none', background:viewDevice===d.id?'var(--primary)':'transparent', color:viewDevice===d.id?'#fff':'var(--fg-muted)', cursor:'pointer', fontSize:12, lineHeight:1, transition:'all 100ms' }}>
                {d.icon}
              </button>
            ))}
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:5, padding:'4px 10px', borderRadius:7, background:sc.dot+'18', border:`1px solid ${sc.dot}44` }}>
            <div style={{ width:6, height:6, borderRadius:'50%', background:sc.dot }}/>
            <span style={{ fontSize:11, fontWeight:700, color:sc.dot }}>{sc.label}</span>
          </div>
          <button onClick={toggleStatus} style={{ padding:'5px 12px', borderRadius:7, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-secondary)', cursor:'pointer', fontSize:12, fontWeight:600, fontFamily:'inherit' }}>
            {sc.nextLabel}
          </button>
          <button onClick={copyLink} style={{ padding:'5px 12px', borderRadius:7, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-secondary)', cursor:'pointer', fontSize:12, fontWeight:600, fontFamily:'inherit', display:'flex', alignItems:'center', gap:5 }}>
            <Icon d={ICONS.copy} size={12}/> {copied?'Copiado!':'Copiar link'}
          </button>
          <button onClick={onEdit} style={{ padding:'5px 12px', borderRadius:7, border:'1px solid var(--border-subtle)', background:'var(--primary)', color:'#fff', cursor:'pointer', fontSize:12, fontWeight:700, fontFamily:'inherit', display:'flex', alignItems:'center', gap:5 }}>
            <Icon d={ICONS.pencil} size={12}/> Editar
          </button>
          <button onClick={onClose} style={{ width:30, height:30, borderRadius:7, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-muted)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
            <Icon d={ICONS.x} size={14}/>
          </button>
        </div>
      </div>

      {/* Page frame */}
      <div onClick={e=>e.stopPropagation()} style={{ width: DEVICES.find(d=>d.id===viewDevice)?.w ? DEVICES.find(d=>d.id===viewDevice).w : 'min(860px,100%)', background:ps.bg, borderRadius:16, border:'1px solid rgba(255,255,255,0.07)', overflow:'hidden', boxShadow:'0 32px 80px rgba(0,0,0,0.65)', marginBottom:24, transition:'width 300ms ease', flexShrink:0 }}>

        {/* Header */}
        <div style={{ background:page.c, padding:'48px 48px 40px', position:'relative', overflow:'hidden' }}>
          <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg,rgba(0,0,0,0) 0%,rgba(0,0,0,0.22) 100%)' }}/>
          <div style={{ position:'relative' }}>
            <div style={{ display:'inline-flex', alignItems:'center', gap:6, background:'rgba(255,255,255,0.16)', borderRadius:20, padding:'4px 12px', marginBottom:16, backdropFilter:'blur(8px)' }}>
              <div style={{ width:6, height:6, borderRadius:'50%', background:'#fff' }}/>
              <span style={{ fontSize:11, fontWeight:700, color:'rgba(255,255,255,0.9)', letterSpacing:'0.1em', textTransform:'uppercase' }}>{page.kind}</span>
            </div>
            <h1 style={{ margin:'0 0 12px', fontSize:36, fontWeight:page.estilo==='minimalista'?300:800, color:'#fff', lineHeight:1.15 }}>{page.t}</h1>
            <div style={{ fontSize:13, color:'rgba(255,255,255,0.7)', fontFamily:'var(--font-mono)', display:'flex', alignItems:'center', gap:6 }}>
              <div style={{ width:8, height:8, borderRadius:'50%', background:'#22C55E' }}/>
              {page.url}
            </div>
          </div>
        </div>

        {/* Body */}
        <div style={{ padding:'36px 48px 48px' }}>
          <PageContent page={page} st={st}/>
        </div>

        {/* Footer */}
        <div style={{ borderTop:`1px solid ${st.cardBorder}`, padding:'20px 48px', display:'flex', justifyContent:'center' }}>
          <div style={{ fontSize:12, color:st.mutedFg }}>
            Página criada com <span style={{ color:st.accent, fontWeight:700 }}>inBrivvo</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Visual Editor (full-screen) ─────────────────────────────────────────────
function VisualEditorView({ page, onBack, onSave }) {
  const pt  = PAGE_TYPES.find(p => p.kind === page.kind) || PAGE_TYPES[0];
  const [blocks,      setBlocks]      = useState(() => (page.blocks?.length ? page.blocks : defaultBlocks(page.kind)).map(b => ({ ...b, data: b.data || { ...(BLOCK_DEFAULTS[b.type]||{}) } })));
  const [selectedId,  setSelectedId]  = useState(null);
  const [estilo,      setEstilo]      = useState(page.estilo || 'moderno');
  const [layout,      setLayout]      = useState('Empilhado');
  const [title,       setTitle]       = useState(page.t);
  const [visibility,  setVisibility]  = useState(page.status);
  const [jsonInput,   setJsonInput]   = useState('');
  const [slug,        setSlug]        = useState(page.url.replace(pt.base, ''));
  const [showContact, setShowContact] = useState(true);
  const [emailNotif,  setEmailNotif]  = useState(true);
  const [duration,    setDuration]    = useState('60');
  const [instagram,   setInstagram]   = useState('');
  const [site,        setSite]        = useState('');
  const [settingsTab, setSettingsTab] = useState('blocos');
  const [previewDevice, setPreviewDevice] = useState('desktop');

  const ps = PAGE_STYLES.find(s => s.id === estilo) || PAGE_STYLES[0];
  const isDark = estilo !== 'minimalista';
  const st = {
    fg:         ps.textC,
    accent:     ps.accent,
    btnBg:      ps.btnBg,
    cardBg:     isDark ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.04)',
    cardBorder: isDark ? 'rgba(255,255,255,0.09)' : 'rgba(0,0,0,0.10)',
    mutedFg:    isDark ? 'rgba(255,255,255,0.48)' : 'rgba(0,0,0,0.42)',
  };

  const IS = { width:'100%', padding:'7px 10px', borderRadius:7, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-primary)', fontFamily:'inherit', fontSize:12, outline:'none', boxSizing:'border-box' };
  const LS = { fontSize:11, color:'var(--fg-muted)', display:'block', marginBottom:5 };
  const visOpts = [
    { v:'publicado', l:'Público'  },
    { v:'privado',   l:'Privado'  },
    { v:'rascunho',  l:'Rascunho' },
  ];

  function addBlock(type) {
    const nb = { id: type.toLowerCase().replace(/[\s\/]+/g, '-') + '-' + Date.now(), type, data: { ...(BLOCK_DEFAULTS[type]||{}) } };
    setBlocks(prev => [...prev, nb]);
    setSelectedId(nb.id);
  }

  function removeBlock(id) {
    setBlocks(prev => {
      const next = prev.filter(b => b.id !== id);
      if (selectedId === id) setSelectedId(null);
      return next;
    });
  }

  function updateBlockData(blockId, key, value) {
    setBlocks(prev => prev.map(b => b.id === blockId ? { ...b, data: { ...(b.data||{}), [key]: value } } : b));
  }

  function loadTemplate() {
    try {
      const parsed = JSON.parse(jsonInput);
      if (Array.isArray(parsed)) {
        setBlocks(parsed.map((b, i) => ({ id:(b.id||b.type||'block')+'-'+i, type:b.type||b.id||'Hero', data:b.data||{ ...(BLOCK_DEFAULTS[b.type]||{}) } })));
        window.__toast?.('Template carregado!', { tone:'success' });
      }
    } catch { window.__toast?.('JSON inválido', { tone:'danger' }); }
  }

  function handleSave(publish) {
    const finalStatus = publish ? 'publicado' : visibility;
    const tone = finalStatus==='publicado'?'success':finalStatus==='privado'?'brand':'neutral';
    const finalSlug = slug.trim() || slugify(title || page.t);
    onSave({ ...page, t:title.trim()||page.t, url:`${pt.base}${finalSlug}`, estilo, status:finalStatus, tone, blocks });
  }

  const [dragIdx, setDragIdx] = useState(null);
  const [overIdx, setOverIdx] = useState(null);

  function reorderBlocks(fromIdx, toIdx) {
    if (fromIdx === toIdx) return;
    setBlocks(prev => {
      const next = [...prev];
      const [moved] = next.splice(fromIdx, 1);
      next.splice(toIdx, 0, moved);
      return next;
    });
  }

  const DEVICE_CFG = [{ id:'desktop', icon:'▣', w:null }, { id:'tablet', icon:'▭', w:768 }, { id:'mobile', icon:'▯', w:390 }];
  const selBlock   = blocks.find(b => b.id === selectedId);
  const blockFields = selBlock ? (BLOCK_FIELDS[selBlock.type] || []) : [];

  const SIDEBAR_BTN = (active, label, onClick) => (
    <button onClick={onClick} style={{ flex:1, padding:'7px 0', borderRadius:7, border:`1px solid ${active?'var(--primary)':'var(--border-subtle)'}`, background:active?'var(--primary-soft)':'transparent', color:active?'var(--geek-blue-200)':'var(--fg-muted)', cursor:'pointer', fontFamily:'inherit', fontSize:12, fontWeight:600, transition:'all 100ms' }}>{label}</button>
  );

  return (
    <div style={{ position:'fixed', inset:0, zIndex:200, display:'flex', flexDirection:'column', background:'var(--bg-app)', fontFamily:'var(--font-sans)' }}>

      {/* ── Top bar ── */}
      <div style={{ height:52, display:'flex', alignItems:'center', padding:'0 16px', background:'var(--bg-surface)', borderBottom:'1px solid var(--border-subtle)', gap:10, flexShrink:0 }}>
        <button onClick={onBack} style={{ display:'flex', alignItems:'center', gap:6, padding:'6px 12px', borderRadius:8, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-secondary)', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit' }}>
          <Icon d={ICONS.arrowR} size={12} style={{ transform:'rotate(180deg)' }}/> Voltar
        </button>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:14, fontWeight:700, color:'var(--fg-primary)' }}>Editor Visual</div>
          <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:1 }}>{title||page.t} — {pt.label}</div>
        </div>
        <button onClick={onBack} style={{ padding:'6px 16px', borderRadius:8, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-secondary)', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit' }}>Cancelar</button>
        <button onClick={() => handleSave(false)} style={{ padding:'6px 16px', borderRadius:8, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-primary)', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit', display:'flex', alignItems:'center', gap:6 }}>
          <Icon d={ICONS.check} size={13}/> Salvar
        </button>
        <button onClick={() => handleSave(true)} style={{ padding:'6px 20px', borderRadius:8, border:'none', background:'var(--primary)', color:'#fff', cursor:'pointer', fontSize:13, fontWeight:700, fontFamily:'inherit' }}>
          Publicar
        </button>
      </div>

      {/* ── Main ── */}
      <div style={{ flex:1, display:'flex', minHeight:0 }}>

        {/* Left panel */}
        <div style={{ width:236, flexShrink:0, display:'flex', flexDirection:'column', background:'var(--bg-surface)', borderRight:'1px solid var(--border-subtle)', overflow:'hidden' }}>

          {/* Tab switcher */}
          <div style={{ padding:'10px 12px', display:'flex', gap:6, borderBottom:'1px solid var(--border-subtle)', flexShrink:0 }}>
            {SIDEBAR_BTN(settingsTab==='blocos', 'Blocos',        () => { setSettingsTab('blocos'); if(settingsTab!=='blocos') setSelectedId(null); })}
            {SIDEBAR_BTN(settingsTab==='config', 'Configurações', () => setSettingsTab('config'))}
          </div>

          <div style={{ flex:1, overflow:'auto', padding:'12px 12px 20px' }}>

            {/* ── Block editor panel (when a block is selected) ── */}
            {settingsTab === 'blocos' && selBlock && (
              <div>
                <button onClick={() => setSelectedId(null)} style={{ display:'flex', alignItems:'center', gap:5, padding:0, background:'none', border:'none', color:'var(--fg-muted)', cursor:'pointer', fontSize:12, fontFamily:'inherit', marginBottom:12 }}>
                  ← Blocos
                </button>
                <div style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 12px', borderRadius:8, background:`${ps.accent}14`, border:`1px solid ${ps.accent}33`, marginBottom:14 }}>
                  <div style={{ width:28, height:28, borderRadius:6, background:ps.btnBg, flexShrink:0 }}/>
                  <div>
                    <div style={{ fontSize:13, fontWeight:700, color:'var(--fg-primary)' }}>{selBlock.type}</div>
                    <div style={{ fontSize:10, color:'var(--fg-muted)', marginTop:1 }}>Editando bloco</div>
                  </div>
                </div>
                {blockFields.length > 0
                  ? blockFields.map(f => (
                      <div key={f.key} style={{ marginBottom:12 }}>
                        <label style={LS}>{f.label}</label>
                        {f.type === 'textarea'
                          ? <textarea
                              value={selBlock.data?.[f.key] ?? (BLOCK_DEFAULTS[selBlock.type]?.[f.key] || '')}
                              onChange={e => updateBlockData(selBlock.id, f.key, e.target.value)}
                              style={{ ...IS, height:80, resize:'vertical', lineHeight:1.5 }}
                            />
                          : <input
                              value={selBlock.data?.[f.key] ?? (BLOCK_DEFAULTS[selBlock.type]?.[f.key] || '')}
                              onChange={e => updateBlockData(selBlock.id, f.key, e.target.value)}
                              style={IS}
                            />
                        }
                      </div>
                    ))
                  : <div style={{ fontSize:12, color:'var(--fg-muted)', textAlign:'center', padding:'24px 0' }}>Este bloco não tem opções editáveis.</div>
                }
                <button onClick={() => removeBlock(selBlock.id)}
                  style={{ width:'100%', marginTop:6, padding:'8px 0', borderRadius:7, background:'transparent', border:'1px solid rgba(255,77,79,0.3)', color:'#FF4D4F', cursor:'pointer', fontSize:12, fontWeight:600, fontFamily:'inherit' }}>
                  Remover bloco
                </button>
              </div>
            )}

            {/* ── Blocks list panel ── */}
            {settingsTab === 'blocos' && !selBlock && (<>
              {/* Template de estilo */}
              <div style={{ marginBottom:10 }}>
                <label style={LS}>Template de estilo</label>
                <select value={estilo} onChange={e => setEstilo(e.target.value)} style={IS}>
                  {PAGE_STYLES.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
                </select>
              </div>

              {/* Modelo de layout */}
              <div style={{ marginBottom:10 }}>
                <label style={LS}>Modelo de layout</label>
                <div style={{ position:'relative' }}>
                  <select value={layout} onChange={e => setLayout(e.target.value)} style={{ ...IS, paddingRight:28, appearance:'none' }}>
                    {['Empilhado','Grade 2 colunas','Grade 3 colunas','Alternado'].map(l => <option key={l}>{l}</option>)}
                  </select>
                  <div style={{ position:'absolute', right:9, top:'50%', transform:'translateY(-50%)', pointerEvents:'none', color:'var(--fg-muted)', fontSize:10 }}>▾</div>
                </div>
              </div>

              {/* JSON template */}
              <div style={{ marginBottom:14 }}>
                <label style={LS}>Carregar template (JSON)</label>
                <textarea value={jsonInput} onChange={e => setJsonInput(e.target.value)}
                  placeholder={'[{"id":"hero-1","type":"hero","order":1,"visible":true,"data":{...}}]'}
                  style={{ ...IS, height:62, resize:'none', fontFamily:'var(--font-mono)', fontSize:10, lineHeight:1.45, color:'var(--fg-secondary)' }}/>
                <button onClick={loadTemplate} style={{ width:'100%', marginTop:5, padding:'7px 0', borderRadius:7, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-secondary)', cursor:'pointer', fontSize:12, fontWeight:600, fontFamily:'inherit' }}>
                  Carregar template
                </button>
              </div>

              {/* Available blocks */}
              <div style={{ fontSize:10, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.09em', marginBottom:7 }}>Adicionar bloco</div>
              <div style={{ display:'flex', flexDirection:'column', gap:3, marginBottom:16 }}>
                {AVAILABLE_BLOCKS.map(type => (
                  <div key={type} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'6px 8px', borderRadius:6, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)' }}>
                    <span style={{ fontSize:12, fontWeight:500, color:'var(--fg-secondary)' }}>{type}</span>
                    <button onClick={() => addBlock(type)} style={{ width:22, height:22, borderRadius:5, border:'1px solid var(--border-subtle)', background:'var(--bg-surface)', color:'var(--fg-muted)', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'inherit', fontSize:15, lineHeight:1, flexShrink:0 }}>+</button>
                  </div>
                ))}
              </div>

              {/* Block order */}
              <div style={{ fontSize:10, fontWeight:700, color:'var(--fg-muted)', textTransform:'uppercase', letterSpacing:'0.09em', marginBottom:7 }}>Ordem dos blocos</div>
              <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
                {blocks.map((block, idx) => {
                  const isDragging = dragIdx === idx;
                  const isOver     = overIdx === idx && dragIdx !== null && dragIdx !== idx;
                  return (
                    <div key={block.id}
                      draggable
                      onClick={() => setSelectedId(block.id)}
                      onDragStart={e => { setDragIdx(idx); e.dataTransfer.effectAllowed = 'move'; }}
                      onDragOver={e => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; setOverIdx(idx); }}
                      onDragLeave={() => setOverIdx(null)}
                      onDrop={e => { e.preventDefault(); reorderBlocks(dragIdx, idx); setDragIdx(null); setOverIdx(null); }}
                      onDragEnd={() => { setDragIdx(null); setOverIdx(null); }}
                      style={{
                        display:'flex', alignItems:'center', gap:7, padding:'8px 8px',
                        borderRadius:6,
                        border: isOver ? '1.5px dashed var(--primary)' : '1px solid var(--border-subtle)',
                        background: isDragging ? 'var(--primary-soft)' : isOver ? 'var(--primary-soft)' : 'var(--bg-elevated)',
                        cursor:'grab', opacity: isDragging ? 0.45 : 1,
                        transition:'background 80ms, border-color 80ms, opacity 80ms',
                        transform: isOver ? 'translateY(-1px)' : undefined,
                      }}>
                      <span style={{ color:'var(--fg-muted)', fontSize:13, flexShrink:0, userSelect:'none' }}>⠿</span>
                      <span style={{ flex:1, fontSize:12, fontWeight:500, color:'var(--fg-primary)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', userSelect:'none' }}>{block.type}</span>
                      <button onClick={e => { e.stopPropagation(); removeBlock(block.id); }}
                        style={{ width:20, height:20, borderRadius:4, border:'none', background:'transparent', color:'#FF4D4F', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, opacity:0.75, fontSize:14, lineHeight:1 }}>×</button>
                    </div>
                  );
                })}
                {blocks.length === 0 && (
                  <div style={{ padding:'20px 0', textAlign:'center', fontSize:12, color:'var(--fg-muted)' }}>Nenhum bloco ainda.<br/>Adicione blocos acima.</div>
                )}
              </div>
            </>)}

            {settingsTab === 'config' && (<>
              <div style={{ marginBottom:12 }}>
                <label style={LS}>Título da página</label>
                <input value={title} onChange={e => setTitle(e.target.value)} style={IS}/>
              </div>
              <div style={{ marginBottom:12 }}>
                <label style={LS}>URL pública</label>
                <div style={{ display:'flex' }}>
                  <span style={{ padding:'7px 8px', background:'var(--bg-surface)', border:'1px solid var(--border-subtle)', borderRight:'none', borderRadius:'7px 0 0 7px', fontSize:10, color:'var(--fg-muted)', whiteSpace:'nowrap', display:'flex', alignItems:'center' }}>{pt.base}</span>
                  <input value={slug} onChange={e => setSlug(e.target.value)} style={{ ...IS, borderRadius:'0 7px 7px 0', flex:1 }}/>
                </div>
              </div>
              <div style={{ marginBottom:16 }}>
                <label style={LS}>Visibilidade</label>
                <div style={{ display:'flex', gap:6 }}>
                  {visOpts.map(v => (
                    <button key={v.v} onClick={() => setVisibility(v.v)} style={{ flex:1, padding:'7px 0', borderRadius:7, cursor:'pointer', fontFamily:'inherit', fontSize:11, fontWeight:600, border:`1.5px solid ${visibility===v.v?'var(--primary)':'var(--border-subtle)'}`, background:visibility===v.v?'var(--primary-soft)':'var(--bg-elevated)', color:visibility===v.v?'var(--geek-blue-200)':'var(--fg-secondary)', transition:'all 120ms' }}>
                      {v.l}
                    </button>
                  ))}
                </div>
              </div>

              {page.kind==='Portfolio' && (
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 12px', borderRadius:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', marginBottom:10 }}>
                  <div>
                    <div style={{ fontSize:12, fontWeight:600 }}>Exibir formulário de contato</div>
                    <div style={{ fontSize:10, color:'var(--fg-muted)', marginTop:1 }}>Visitantes podem enviar mensagens</div>
                  </div>
                  <Toggle value={showContact} onChange={setShowContact}/>
                </div>
              )}
              {page.kind==='Bio Link' && (<>
                <div style={{ marginBottom:10 }}><label style={LS}>Instagram (opcional)</label><input value={instagram} onChange={e=>setInstagram(e.target.value)} placeholder="@seuusuario" style={IS}/></div>
                <div style={{ marginBottom:10 }}><label style={LS}>Site externo (opcional)</label><input value={site} onChange={e=>setSite(e.target.value)} placeholder="https://seusite.com.br" style={IS}/></div>
              </>)}
              {page.kind==='Agenda' && (
                <div style={{ marginBottom:10 }}>
                  <label style={LS}>Duração padrão</label>
                  <select value={duration} onChange={e=>setDuration(e.target.value)} style={IS}>
                    {[['30','30 minutos'],['60','1 hora'],['90','1h 30min'],['120','2 horas']].map(([v,l])=><option key={v} value={v}>{l}</option>)}
                  </select>
                </div>
              )}
              {page.kind==='Formulário' && (
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'10px 12px', borderRadius:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', marginBottom:10 }}>
                  <div>
                    <div style={{ fontSize:12, fontWeight:600 }}>Receber respostas por email</div>
                    <div style={{ fontSize:10, color:'var(--fg-muted)', marginTop:1 }}>Notificação a cada novo envio</div>
                  </div>
                  <Toggle value={emailNotif} onChange={setEmailNotif}/>
                </div>
              )}

              <button onClick={() => { window.__toast?.(`"${page.t}" excluída`, {tone:'danger'}); onBack(); }}
                style={{ width:'100%', marginTop:8, padding:'9px 0', borderRadius:8, background:'transparent', border:'1px solid rgba(255,77,79,0.3)', color:'#FF4D4F', cursor:'pointer', fontSize:12, fontWeight:600, fontFamily:'inherit' }}>
                Excluir página
              </button>
            </>)}

          </div>
        </div>

        {/* Preview panel */}
        <div style={{ flex:1, display:'flex', flexDirection:'column', background:'#14172b', minWidth:0 }}>

          {/* Preview bar */}
          <div style={{ height:42, display:'flex', alignItems:'center', padding:'0 16px', gap:10, borderBottom:'1px solid rgba(255,255,255,0.06)', flexShrink:0 }}>
            <span style={{ fontSize:10, fontWeight:700, color:'rgba(255,255,255,0.35)', textTransform:'uppercase', letterSpacing:'0.1em' }}>Preview</span>
            <div style={{ flex:1 }}/>
            {/* Device toggle */}
            <div style={{ display:'flex', gap:2, background:'rgba(255,255,255,0.05)', borderRadius:8, padding:3 }}>
              {DEVICE_CFG.map(d => (
                <button key={d.id} onClick={() => setPreviewDevice(d.id)} title={d.id}
                  style={{ padding:'4px 9px', borderRadius:5, border:'none', background:previewDevice===d.id?'rgba(255,255,255,0.14)':'transparent', color:previewDevice===d.id?'#fff':'rgba(255,255,255,0.4)', cursor:'pointer', fontSize:12, lineHeight:1, transition:'all 100ms' }}>
                  {d.icon}
                </button>
              ))}
            </div>
            <div style={{ display:'flex', gap:5 }}>
              <div style={{ width:7, height:7, borderRadius:'50%', background:'#FF5F56' }}/>
              <div style={{ width:7, height:7, borderRadius:'50%', background:'#FEBC2E' }}/>
              <div style={{ width:7, height:7, borderRadius:'50%', background:'#28C840' }}/>
            </div>
            <div style={{ padding:'3px 10px', borderRadius:5, background:'rgba(255,255,255,0.06)', fontSize:10, fontFamily:'var(--font-mono)', color:'rgba(255,255,255,0.35)', maxWidth:220, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{page.url}</div>
          </div>

          {/* Page render */}
          <div style={{ flex:1, overflow:'auto', padding:'20px 24px' }}>
            <div style={{
              width: DEVICE_CFG.find(d=>d.id===previewDevice)?.w || '100%',
              maxWidth: previewDevice==='desktop' ? 860 : undefined,
              margin: '0 auto',
              background: ps.bg,
              borderRadius: 16,
              border: '1px solid rgba(255,255,255,0.07)',
              overflow: 'hidden',
              boxShadow: '0 24px 60px rgba(0,0,0,0.5)',
              transition: 'width 300ms ease',
            }}>
              {blocks.length > 0
                ? blocks.map(block => (
                    <div key={block.id}
                      onClick={() => { setSelectedId(block.id); if(settingsTab!=='blocos') setSettingsTab('blocos'); }}
                      style={{ outline: selectedId===block.id ? `2px solid ${ps.accent}` : undefined, outlineOffset:-2, cursor:'pointer', transition:'outline 100ms' }}
                      title={`Clique para editar: ${block.type}`}>
                      <BlockPreview block={block} page={{ ...page, estilo }} st={st} ps={ps}/>
                    </div>
                  ))
                : <div style={{ padding:'80px 0', textAlign:'center', color:st.mutedFg, fontSize:14 }}>Adicione blocos no painel esquerdo para visualizar a página.</div>
              }
            </div>
          </div>

        </div>

      </div>
    </div>
  );
}

// LEGACY stub to satisfy any lingering references (replaced by VisualEditorView)
function EditarPaginaModal({ page, onClose, onSave }) {
  const pt = PAGE_TYPES.find(p => p.kind === page.kind) || PAGE_TYPES[0];
  const [title, setTitle] = useState(page.t);
  const [estilo, setEstilo] = useState(page.estilo||'moderno');
  const [visibility, setVisibility] = useState(page.status);
  const [showContact, setShowContact] = useState(true);
  const [emailNotif,  setEmailNotif]  = useState(true);
  const [duration,    setDuration]    = useState('60');
  const [instagram,   setInstagram]   = useState('');
  const [site,        setSite]        = useState('');

  const IS = { width:'100%', padding:'9px 12px', borderRadius:8, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-primary)', fontFamily:'inherit', fontSize:13, outline:'none', boxSizing:'border-box' };
  const LS = { fontSize:12, fontWeight:700, color:'var(--fg-muted)', display:'block', marginBottom:7 };
  const visOpts = [
    { v:'publicado', l:'Público',  desc:'Qualquer pessoa com o link acessa' },
    { v:'privado',   l:'Privado',  desc:'Acessível só por quem tem o link'  },
    { v:'rascunho',  l:'Rascunho', desc:'Somente você pode visualizar'      },
  ];

  function handleSave() {
    if (!title.trim()) { window.__toast?.('Informe o título', { tone:'danger' }); return; }
    const tone = visibility==='publicado'?'success':visibility==='privado'?'brand':'neutral';
    onSave({ ...page, t:title.trim(), estilo, status:visibility, tone });
    window.__toast?.('Página atualizada!', { tone:'success' });
    onClose();
  }

  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(580px,100%)', maxHeight:'90vh', 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 style={{ display:'flex', alignItems:'center', gap:12 }}>
            <div style={{ width:36, height:36, borderRadius:8, background:pt.c, display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon d={ICONS[pt.icon]} size={18} style={{ color:'#fff' }}/>
            </div>
            <div>
              <h2 style={{ margin:0, fontSize:18, fontWeight:700 }}>Editar página</h2>
              <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2 }}>{pt.label} · {page.url}</div>
            </div>
          </div>
          <button onClick={onClose} style={{ background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', width:32, height:32, borderRadius:8, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
            <Icon d={ICONS.x} size={16}/>
          </button>
        </div>
        <div style={{ flex:1, overflow:'auto', padding:24, display:'flex', flexDirection:'column', gap:16 }}>
          <div>
            <label style={LS}>Título *</label>
            <input autoFocus value={title} onChange={e=>setTitle(e.target.value)} style={IS}/>
          </div>
          <div>
            <label style={LS}>Visibilidade</label>
            <div style={{ display:'flex', gap:8 }}>
              {visOpts.map(v => (
                <button key={v.v} onClick={() => setVisibility(v.v)} style={{ flex:1, padding:'9px 8px', borderRadius:8, cursor:'pointer', fontFamily:'inherit', fontSize:12, fontWeight:600, border:`1.5px solid ${visibility===v.v?'var(--primary)':'var(--border-subtle)'}`, background:visibility===v.v?'var(--primary-soft)':'var(--bg-elevated)', color:visibility===v.v?'var(--geek-blue-200)':'var(--fg-secondary)' }}>
                  {v.l}
                </button>
              ))}
            </div>
          </div>
          {page.kind==='Portfolio' && (
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'12px 14px', borderRadius:10, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)' }}>
              <div>
                <div style={{ fontSize:13, fontWeight:600 }}>Exibir formulário de contato</div>
              </div>
              <Toggle value={showContact} onChange={setShowContact}/>
            </div>
          )}
          {page.kind==='Bio Link' && (<>
            <div><label style={LS}>Instagram (opcional)</label><input value={instagram} onChange={e=>setInstagram(e.target.value)} placeholder="@seuusuario" style={IS}/></div>
            <div><label style={LS}>Site externo (opcional)</label><input value={site} onChange={e=>setSite(e.target.value)} placeholder="https://seusite.com.br" style={IS}/></div>
          </>)}
          {page.kind==='Agenda' && (
            <div>
              <label style={LS}>Duração padrão das reuniões</label>
              <select value={duration} onChange={e=>setDuration(e.target.value)} style={IS}>
                {[['30','30 minutos'],['60','1 hora'],['90','1h 30min'],['120','2 horas']].map(([v,l])=><option key={v} value={v}>{l}</option>)}
              </select>
            </div>
          )}
          {page.kind==='Formulário' && (
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'12px 14px', borderRadius:10, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)' }}>
              <div>
                <div style={{ fontSize:13, fontWeight:600 }}>Receber respostas por email</div>
                <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>Notificação a cada novo envio</div>
              </div>
              <Toggle value={emailNotif} onChange={setEmailNotif}/>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding:'16px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', gap:10, justifyContent:'space-between', flexShrink:0, background:'var(--bg-surface)' }}>
          <button onClick={() => { window.__toast?.(`"${page.t}" excluída`, {tone:'danger'}); onClose(); }} style={{ padding:'10px 16px', borderRadius:9, background:'transparent', border:'1px solid rgba(255,77,79,0.3)', color:'var(--accent-danger)', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit' }}>
            Excluir página
          </button>
          <div style={{ display:'flex', gap:10 }}>
            <button onClick={onClose} style={{ padding:'10px 20px', borderRadius:9, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-primary)', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit' }}>Cancelar</button>
            <button onClick={handleSave} style={{ padding:'10px 24px', borderRadius:9, background:'var(--primary)', border:'none', color:'#fff', cursor:'pointer', fontSize:13, fontWeight:700, fontFamily:'inherit', display:'flex', alignItems:'center', gap:8 }}>
              <Icon d={ICONS.check} size={14}/> Salvar alterações
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Criar Página Modal (3 passos) ────────────────────────────────────────────
function CriarPaginaModal({ onClose, onCreate }) {
  const [step,        setStep]        = useState(1);
  const [tipo,        setTipo]        = useState(null);
  const [estilo,      setEstilo]      = useState(null);
  const [title,       setTitle]       = useState('');
  const [slug,        setSlug]        = useState('');
  const [visibility,  setVisibility]  = useState('publicado');
  const [instagram,   setInstagram]   = useState('');
  const [site,        setSite]        = useState('');
  const [duration,    setDuration]    = useState('60');
  const [emailNotif,  setEmailNotif]  = useState(true);
  const [showContact, setShowContact] = useState(true);

  const pt = PAGE_TYPES.find(p => p.id === tipo);
  const ps = PAGE_STYLES.find(s => s.id === estilo);

  const IS = { width:'100%', padding:'9px 12px', borderRadius:8, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-primary)', fontFamily:'inherit', fontSize:13, outline:'none', boxSizing:'border-box' };
  const LS = { fontSize:12, fontWeight:700, color:'var(--fg-muted)', display:'block', marginBottom:7 };
  const visOpts = [
    { v:'publicado', l:'Público',  desc:'Qualquer pessoa com o link acessa' },
    { v:'privado',   l:'Privado',  desc:'Acessível só por quem tem o link'  },
    { v:'rascunho',  l:'Rascunho', desc:'Somente você pode visualizar'      },
  ];

  const HDRS = [null, 'Tipo de página', 'Estilo visual', pt ? `Configurar · ${pt.label}` : 'Configurar'];
  const SUBS = [null, 'Escolha o tipo de página que deseja criar', 'Defina a identidade visual da página', 'Preencha os dados e preferências'];

  function handleTitleChange(val) { setTitle(val); setSlug(slugify(val)); }

  function handleCreate() {
    if (!title.trim()) { window.__toast?.('Informe o título da página', { tone:'danger' }); return; }
    const finalSlug = slug.trim() || slugify(title);
    const tone = visibility === 'publicado' ? 'success' : visibility === 'privado' ? 'brand' : 'neutral';
    onCreate({ t:title.trim(), url:`${pt.base}${finalSlug}`, kind:pt.kind, views:0, leads:0, status:visibility, tone, c:pt.c, estilo:ps?.id||'moderno' });
    window.__toast?.(`Página "${title.trim()}" criada!`, { tone:'success' });
    onClose();
  }

  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:'90vh', 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' }}>

        {/* Header */}
        <div style={{ padding:'20px 24px 18px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'flex-start', justifyContent:'space-between', flexShrink:0 }}>
          <div>
            {step > 1 && (
              <button onClick={() => setStep(s => s-1)} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', fontSize:12, fontFamily:'inherit', padding:0, marginBottom:8, display:'flex', alignItems:'center', gap:4 }}>
                <Icon d={ICONS.arrowR} size={12} style={{ transform:'rotate(180deg)' }}/> Voltar
              </button>
            )}
            <h2 style={{ margin:0, fontSize:18, fontWeight:700 }}>{HDRS[step]}</h2>
            <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:4 }}>{SUBS[step]}</div>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
            <div style={{ display:'flex', gap:5, alignItems:'center' }}>
              {[1,2,3].map(n => (
                <div key={n} style={{ width:n===step?20:6, height:6, borderRadius:999, background:n<=step?'var(--primary)':'var(--border-strong)', opacity:n<step?0.5:1, transition:'all 200ms' }}/>
              ))}
            </div>
            <button onClick={onClose} style={{ background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-secondary)', width:32, height:32, borderRadius:8, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
              <Icon d={ICONS.x} size={16}/>
            </button>
          </div>
        </div>

        {/* Body */}
        <div style={{ flex:1, overflow:'auto', padding:24 }}>

          {/* Passo 1: Tipo */}
          {step === 1 && (
            <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12 }}>
              {PAGE_TYPES.map(p => (
                <div key={p.id}
                  onClick={() => { setTipo(p.id); setStep(2); }}
                  style={{ borderRadius:12, overflow:'hidden', border:'1px solid var(--border-subtle)', cursor:'pointer', transition:'all 150ms' }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor='var(--primary)'; e.currentTarget.style.transform='translateY(-2px)'; e.currentTarget.style.boxShadow='0 8px 24px rgba(0,0,0,0.2)'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor='var(--border-subtle)'; e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow=''; }}>
                  <div style={{ height:72, background:p.c, display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <Icon d={ICONS[p.icon]} size={28} style={{ color:'rgba(255,255,255,0.92)' }}/>
                  </div>
                  <div style={{ padding:'12px 14px', background:'var(--bg-elevated)' }}>
                    <div style={{ fontSize:14, fontWeight:700, marginBottom:4 }}>{p.label}</div>
                    <div style={{ fontSize:11, color:'var(--fg-muted)', lineHeight:1.45 }}>{p.desc}</div>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Passo 2: Estilo */}
          {step === 2 && (
            <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
              {PAGE_STYLES.map(st => {
                const sel = estilo === st.id;
                return (
                  <div key={st.id}
                    onClick={() => { setEstilo(st.id); setStep(3); }}
                    style={{ borderRadius:12, border:`1.5px solid ${sel?'var(--primary)':'var(--border-subtle)'}`, cursor:'pointer', overflow:'hidden', transition:'all 150ms', background:'var(--bg-elevated)', display:'grid', gridTemplateColumns:'1fr 192px' }}
                    onMouseEnter={e => { e.currentTarget.style.borderColor='var(--primary)'; e.currentTarget.style.transform='translateY(-1px)'; e.currentTarget.style.boxShadow='0 6px 20px rgba(0,0,0,0.15)'; }}
                    onMouseLeave={e => { e.currentTarget.style.borderColor=sel?'var(--primary)':'var(--border-subtle)'; e.currentTarget.style.transform=''; e.currentTarget.style.boxShadow=''; }}>
                    <div style={{ padding:'18px 20px' }}>
                      <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:10 }}>
                        <div style={{ width:30, height:30, borderRadius:8, background:st.btnBg, flexShrink:0 }}/>
                        <div>
                          <div style={{ fontSize:16, fontWeight:800 }}>{st.label}</div>
                          <div style={{ fontSize:11, color:'var(--fg-muted)', fontWeight:600 }}>{st.sub}</div>
                        </div>
                      </div>
                      <div style={{ fontSize:12, color:'var(--fg-secondary)', lineHeight:1.6 }}>{st.desc}</div>
                    </div>
                    <div style={{ padding:'14px 14px 14px 0', display:'flex', alignItems:'center' }}>
                      <StyleMiniPreview st={st}/>
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {/* Passo 3: Configurar */}
          {step === 3 && pt && ps && (
            <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
                {[
                  { label:'Tipo',   icon:<Icon d={ICONS[pt.icon]} size={15} style={{color:'#fff'}}/>, bg:pt.c,     name:pt.label },
                  { label:'Estilo', icon:null,                                                         bg:ps.btnBg, name:ps.label },
                ].map(r => (
                  <div key={r.label} style={{ padding:'10px 14px', borderRadius:10, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', display:'flex', alignItems:'center', gap:10 }}>
                    <div style={{ width:32, height:32, borderRadius:8, background:r.bg, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>{r.icon}</div>
                    <div>
                      <div style={{ fontSize:11, color:'var(--fg-muted)', marginBottom:1 }}>{r.label}</div>
                      <div style={{ fontSize:13, fontWeight:700 }}>{r.name}</div>
                    </div>
                  </div>
                ))}
              </div>
              <div>
                <label style={LS}>Título <span style={{ color:'var(--accent-danger)' }}>*</span></label>
                <input autoFocus value={title} onChange={e => handleTitleChange(e.target.value)} placeholder={`Ex: ${pt.label} · Studio Norte`} style={IS}/>
              </div>
              <div>
                <label style={LS}>URL pública</label>
                <div style={{ display:'flex' }}>
                  <span style={{ padding:'9px 12px', background:'var(--bg-surface)', border:'1px solid var(--border-subtle)', borderRight:'none', borderRadius:'8px 0 0 8px', fontSize:12, color:'var(--fg-muted)', whiteSpace:'nowrap', display:'flex', alignItems:'center' }}>{pt.base}</span>
                  <input value={slug} onChange={e => setSlug(e.target.value)} placeholder="meu-portfolio" style={{ ...IS, borderRadius:'0 8px 8px 0', flex:1 }}/>
                </div>
              </div>
              <div>
                <label style={LS}>Visibilidade</label>
                <div style={{ display:'flex', gap:8 }}>
                  {visOpts.map(v => (
                    <button key={v.v} onClick={() => setVisibility(v.v)} style={{ flex:1, padding:'9px 8px', borderRadius:8, cursor:'pointer', fontFamily:'inherit', fontSize:12, fontWeight:600, border:`1.5px solid ${visibility===v.v?'var(--primary)':'var(--border-subtle)'}`, background:visibility===v.v?'var(--primary-soft)':'var(--bg-elevated)', color:visibility===v.v?'var(--geek-blue-200)':'var(--fg-secondary)', transition:'all 120ms' }}>
                      {v.l}
                    </button>
                  ))}
                </div>
                <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:6 }}>{visOpts.find(v=>v.v===visibility)?.desc}</div>
              </div>
              {tipo==='portfolio' && (
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'12px 14px', borderRadius:10, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)' }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:600 }}>Exibir formulário de contato</div>
                    <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>Permite que visitantes enviem mensagens pela página</div>
                  </div>
                  <Toggle value={showContact} onChange={setShowContact}/>
                </div>
              )}
              {tipo==='biolink' && (
                <>
                  <div><label style={LS}>Instagram (opcional)</label><input value={instagram} onChange={e=>setInstagram(e.target.value)} placeholder="@seuusuario" style={IS}/></div>
                  <div><label style={LS}>Site / portfólio externo (opcional)</label><input value={site} onChange={e=>setSite(e.target.value)} placeholder="https://seusite.com.br" style={IS}/></div>
                </>
              )}
              {tipo==='agenda' && (
                <div>
                  <label style={LS}>Duração padrão das reuniões</label>
                  <select value={duration} onChange={e=>setDuration(e.target.value)} style={IS}>
                    {[['30','30 minutos'],['60','1 hora'],['90','1h 30min'],['120','2 horas']].map(([v,l])=><option key={v} value={v}>{l}</option>)}
                  </select>
                </div>
              )}
              {tipo==='form' && (
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'12px 14px', borderRadius:10, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)' }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:600 }}>Receber respostas por email</div>
                    <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>Notificação a cada novo envio</div>
                  </div>
                  <Toggle value={emailNotif} onChange={setEmailNotif}/>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        {step >= 2 && (
          <div style={{ padding:'16px 24px', borderTop:'1px solid var(--border-subtle)', display:'flex', gap:10, justifyContent:'flex-end', flexShrink:0, background:'var(--bg-surface)' }}>
            <button onClick={() => setStep(s=>s-1)} style={{ padding:'10px 20px', borderRadius:9, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', color:'var(--fg-primary)', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit' }}>Voltar</button>
            {step === 3 && (
              <button onClick={handleCreate} style={{ padding:'10px 24px', borderRadius:9, background:'var(--primary)', border:'none', color:'#fff', cursor:'pointer', fontSize:13, fontWeight:700, fontFamily:'inherit', display:'flex', alignItems:'center', gap:8 }}>
                <Icon d={ICONS.plus} size={14}/> Criar página
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Pages (Páginas públicas) ────────────────────────────────────────────────
function Pages({ onNav }) {
  const [pages,      setPages]      = useState([]);
  const [loading,    setLoading]    = useState(true);
  const [criarOpen,  setCriarOpen]  = useState(false);
  const [deletingIdx, setDeletingIdx] = useState(null);
  const [view,      setView]      = useState('list');   // 'list' | 'preview' | 'editor'
  const [activeIdx, setActiveIdx] = useState(null);

  useEffect(() => {
    (async () => {
      const { data, error } = await sb.from('pages').select('*').order('created_at', { ascending: false });
      if (error) { window.__toast?.(error.message, { tone:'danger' }); }
      setPages((data || []).map(rowToPage));
      setLoading(false);
    })();
  }, []);

  async function handleSavePage(updated) {
    if (!updated.id) { setPages(prev => prev.map((p, i) => i === activeIdx ? updated : p)); return; }
    try {
      const { error } = await sb.from('pages').update({
        title:    updated.t,
        url:      updated.url,
        estilo:   updated.estilo,
        status:   updated.status,
        tone:     updated.tone,
        blocks:   updated.blocks || [],
        gradient: updated.c,
      }).eq('id', updated.id);
      if (error) { window.__toast?.(error.message, { tone:'danger' }); return; }
    } catch { /* ignore network errors */ }
    setPages(prev => prev.map((p, i) => i === activeIdx ? updated : p));
  }

  // Full-screen editor: return it directly so it covers the whole viewport
  if (view === 'editor' && activeIdx !== null) {
    return (
      <VisualEditorView
        page={pages[activeIdx]}
        onBack={() => setView('list')}
        onSave={(updated) => { handleSavePage(updated); setView('list'); }}
      />
    );
  }

  const totalViews  = pages.reduce((s,p) => s + (Number(p.views)||0), 0);
  const totalLeads  = pages.reduce((s,p) => s + (Number(p.leads)||0), 0);
  const activePages = pages.filter(p => p.status === 'publicado').length;
  const convRate    = totalViews > 0 ? ((totalLeads/totalViews)*100).toFixed(1) : '0.0';

  const STATS = [
    { label:'Total de páginas',  value:String(pages.length), icon:'page',  color:'#1D39C4' },
    { label:'Visualizações',     value:fmtNum(totalViews),   icon:'eye',   color:'#36CFC9' },
    { label:'Capturas / Leads',  value:String(totalLeads),   icon:'mail',  color:'#22C55E' },
    { label:'Taxa de conversão', value:convRate+'%',         icon:'tag',   color:'#FA541C' },
    { label:'Páginas ativas',    value:String(activePages),  icon:'check', color:'#7C3AED' },
  ];

  return (
    <div style={{ padding:'24px 28px', display:'flex', flexDirection:'column', gap:18 }}>

      {/* Hero */}
      <Card padding={22} style={{ background:'linear-gradient(135deg,rgba(29,57,196,0.22) 0%,rgba(54,207,201,0.10) 60%,transparent 100%),var(--bg-surface)', borderColor:'var(--geek-blue-a40)' }}>
        <div style={{ display:'flex', alignItems:'center', gap:18 }}>
          <div style={{ flex:1 }}>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)' }}>Páginas públicas</div>
            <h2 style={{ margin:'4px 0 0', fontSize:22, fontWeight:700 }}>Apresente, colete e converta — sem sair do inBrivvo.</h2>
            <p style={{ margin:'6px 0 0', color:'var(--fg-secondary)', fontSize:14 }}>Portfólios, bio links, formulários, briefings, agendas e aprovações — tudo com URL pública e sua identidade visual.</p>
          </div>
          <Button icon="plus" onClick={() => setCriarOpen(true)}>Criar página</Button>
        </div>
      </Card>

      {/* Estatísticas */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:12 }}>
        {STATS.map(s => (
          <Card key={s.label} padding={0} style={{ overflow:'hidden' }}>
            <div style={{ height:3, background:s.color, borderRadius:'4px 4px 0 0' }}/>
            <div style={{ padding:'14px 16px' }}>
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
                <div style={{ width:30, height:30, borderRadius:8, background:s.color+'18', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  <Icon d={ICONS[s.icon]} size={14} style={{ color:s.color }}/>
                </div>
                <div style={{ fontSize:24, fontWeight:900, fontFamily:'var(--font-display)', color:'var(--fg-primary)', letterSpacing:'-0.02em' }}>{s.value}</div>
              </div>
              <div style={{ fontSize:11, color:'var(--fg-muted)', fontWeight:500, lineHeight:1.3 }}>{s.label}</div>
            </div>
          </Card>
        ))}
      </div>

      {/* Grid de páginas */}
      {loading && <div style={{ padding:'40px 0', textAlign:'center', color:'var(--fg-muted)', fontSize:14 }}>Carregando páginas…</div>}
      {!loading && pages.length === 0 && (
        <div style={{ padding:'48px 24px', textAlign:'center', color:'var(--fg-muted)' }}>
          <div style={{ fontSize:15, fontWeight:600, marginBottom:6 }}>Nenhuma página ainda</div>
          <div style={{ fontSize:13 }}>Clique em "Criar página" para começar.</div>
        </div>
      )}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:16 }}>
        {pages.map((p, i) => {
          const conv = p.views > 0 ? ((p.leads/p.views)*100).toFixed(1) : null;
          return (
            <Card key={i} hoverable padding={0} style={{ overflow:'hidden', display:'flex', flexDirection:'column' }}>

              {/* ── Cover ─────────────────────────────────────────────── */}
              <div style={{ height:156, background:p.c, position:'relative', overflow:'hidden', flexShrink:0 }}>
                {/* bottom scrim */}
                <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg,rgba(0,0,0,0.06) 0%,rgba(0,0,0,0.48) 100%)' }}/>
                {/* kind badge — top left */}
                <div style={{ position:'absolute', top:13, left:14 }}>
                  <div style={{ display:'inline-flex', alignItems:'center', padding:'3px 9px', borderRadius:999, background:'rgba(255,255,255,0.18)', backdropFilter:'blur(8px)', border:'1px solid rgba(255,255,255,0.22)' }}>
                    <span style={{ fontSize:10, fontWeight:700, color:'#fff', letterSpacing:'0.08em', textTransform:'uppercase' }}>{p.kind}</span>
                  </div>
                </div>
                {/* share icon — top right */}
                <div style={{ position:'absolute', top:10, right:12, cursor:'pointer' }}
                  onClick={() => { setActiveIdx(i); setView('preview'); }}>
                  <div style={{ width:30, height:30, borderRadius:8, background:'rgba(255,255,255,0.18)', backdropFilter:'blur(8px)', border:'1px solid rgba(255,255,255,0.22)', display:'flex', alignItems:'center', justifyContent:'center' }}>
                    <Icon d={ICONS.share} size={13} style={{ color:'#fff' }}/>
                  </div>
                </div>
                {/* status + estilo — bottom */}
                <div style={{ position:'absolute', bottom:13, left:14, right:14, display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                  <Badge tone={p.tone}>{p.status}</Badge>
                  <span style={{ fontSize:10, fontWeight:600, color:'rgba(255,255,255,0.72)', letterSpacing:'0.06em', textTransform:'capitalize' }}>{p.estilo}</span>
                </div>
              </div>

              {/* ── Body ──────────────────────────────────────────────── */}
              <div style={{ padding:'15px 16px 14px', display:'flex', flexDirection:'column', gap:10, flex:1 }}>
                {/* title + url */}
                <div>
                  <div style={{ fontSize:14, fontWeight:700, lineHeight:1.3, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{p.t}</div>
                  <div style={{ fontSize:11, color:'var(--geek-blue-300)', marginTop:3, fontFamily:'var(--font-mono)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', opacity:0.85 }}>{p.url}</div>
                </div>
                {/* mini stats — bordered grid */}
                <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', borderRadius:8, border:'1px solid var(--border-subtle)', overflow:'hidden' }}>
                  {[
                    { v:fmtNum(p.views),      l:'Views'     },
                    { v:String(p.leads ?? 0), l:'Capturas'  },
                    { v:conv ? conv+'%' : '—', l:'Conversão', success:!!conv },
                  ].map((s, j) => (
                    <div key={j} style={{ padding:'7px 4px', textAlign:'center', borderLeft:j>0?'1px solid var(--border-subtle)':'' }}>
                      <div style={{ fontSize:14, fontWeight:800, color:s.success?'#22C55E':'var(--fg-primary)', letterSpacing:'-0.01em' }}>{s.v}</div>
                      <div style={{ fontSize:9, color:'var(--fg-muted)', marginTop:1, textTransform:'uppercase', letterSpacing:'0.05em', fontWeight:600 }}>{s.l}</div>
                    </div>
                  ))}
                </div>
                {/* actions */}
                <div style={{ display:'flex', gap:5, marginTop:'auto' }}>
                  {deletingIdx === i ? (
                    <>
                      <span style={{ fontSize:11, color:'var(--fg-muted)', flex:1, alignSelf:'center' }}>Confirmar exclusão?</span>
                      <Button variant="ghost"  size="sm" onClick={() => setDeletingIdx(null)}>Não</Button>
                      <Button variant="danger" size="sm" onClick={async () => {
                        if (p.id) { try { await sb.from('pages').delete().eq('id', p.id); } catch {} }
                        setPages(prev => prev.filter((_, idx) => idx !== i));
                        setDeletingIdx(null);
                        window.__toast?.('Página apagada', { tone:'danger' });
                      }}>Apagar</Button>
                    </>
                  ) : (
                    <>
                      <Button variant="ghost"     size="sm" onClick={() => setDeletingIdx(i)}>Apagar</Button>
                      <Button variant="ghost"     size="sm" style={{ flex:1 }} onClick={() => { setActiveIdx(i); setView('editor'); }}>Editar</Button>
                      <Button variant="secondary" size="sm" style={{ flex:1 }} onClick={() => { setActiveIdx(i); setView('preview'); }}>Abrir →</Button>
                    </>
                  )}
                </div>
              </div>
            </Card>
          );
        })}
      </div>

      {criarOpen && (
        <CriarPaginaModal
          onClose={() => setCriarOpen(false)}
          onCreate={async p => {
            const newPage = { ...p, blocks: defaultBlocks(p.kind) };
            try {
              const { data: { user } } = await sb.auth.getUser();
              const { data: row, error } = await sb.from('pages').insert({
                user_id:  user.id,
                title:    newPage.t,
                url:      newPage.url,
                kind:     newPage.kind,
                estilo:   newPage.estilo || 'moderno',
                status:   newPage.status || 'rascunho',
                tone:     newPage.tone || 'neutral',
                blocks:   newPage.blocks || [],
                gradient: newPage.c,
                views:    0,
                leads:    0,
              }).select().single();
              if (error) { window.__toast?.(error.message, { tone:'danger' }); return; }
              setPages(prev => [rowToPage(row), ...prev]);
            } catch { window.__toast?.('Erro ao criar página', { tone:'danger' }); }
          }}
        />
      )}
      {view === 'preview' && activeIdx !== null && (
        <VisualizarPaginaModal
          page={pages[activeIdx]}
          onClose={() => setView('list')}
          onEdit={() => setView('editor')}
          onStatusChange={(updated) => handleSavePage(updated)}
        />
      )}
    </div>
  );
}
window.Pages = Pages;

// ─── Agendar modal ────────────────────────────────────────────────────────────
async function msgGcCreateMeet({ title, description, start, end }) {
  try {
    const { data } = await window.sb.auth.getSession();
    const token = data?.session?.provider_token;
    if (!token) return null;
    const body = {
      summary: title, description,
      start: { dateTime: start, timeZone: 'America/Sao_Paulo' },
      end:   { dateTime: end,   timeZone: 'America/Sao_Paulo' },
      conferenceData: { createRequest: { requestId: 'inbrivvo-msg-' + Date.now(), conferenceSolutionKey: { type: 'hangoutsMeet' } } },
    };
    const res = await fetch('https://www.googleapis.com/calendar/v3/calendars/primary/events?conferenceDataVersion=1', {
      method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body),
    });
    if (!res.ok) return null;
    const ev = await res.json();
    return ev.hangoutLink || ev.conferenceData?.entryPoints?.find(p => p.entryPointType === 'video')?.uri || null;
  } catch { return null; }
}

function AgendarModal({ contactName, onClose }) {
  const [tipo,     setTipo]     = useState('reuniao');
  const [titulo,   setTitulo]   = useState('');
  const [data,     setData]     = useState(() => new Date().toISOString().slice(0, 10));
  const [hora,     setHora]     = useState('10:00');
  const [desc,     setDesc]     = useState('');
  const [withMeet, setWithMeet] = useState(false);
  const [saving,   setSaving]   = useState(false);
  const [meetLink, setMeetLink] = useState('');

  async function confirmar() {
    if (!titulo.trim()) { window.__toast?.('Informe o título', { tone:'danger' }); return; }
    setSaving(true);
    if (tipo === 'reuniao' && withMeet) {
      const endH = String(Math.min(parseInt(hora.slice(0,2),10)+1,23)).padStart(2,'0');
      const link = await msgGcCreateMeet({
        title: titulo.trim(), description: desc || `Reunião com ${contactName} via inBrivvo`,
        start: `${data}T${hora}:00`, end: `${data}T${endH}:${hora.slice(3)}:00`,
      });
      setSaving(false);
      if (link) { setMeetLink(link); return; }
      window.__toast?.('Erro ao criar Meet. Verifique a conexão Google nas Configurações.', { tone:'danger' });
      return;
    }
    setSaving(false);
    const labels = { reuniao:'Reunião', entrega:'Entrega', call:'Call' };
    window.__toast?.(`${labels[tipo]} "${titulo}" agendada para ${data} às ${hora}`, { tone:'success' });
    onClose();
  }

  if (meetLink) {
    return (
      <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.7)', backdropFilter:'blur(6px)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
        <div onClick={e=>e.stopPropagation()} style={{ width:'min(420px,100%)', background:'var(--bg-surface)', border:'1px solid var(--border-strong)', borderRadius:16, padding:28, boxShadow:'0 24px 64px rgba(0,0,0,0.5)', textAlign:'center' }}>
          <div style={{ fontSize:44, marginBottom:12 }}>📹</div>
          <h3 style={{ margin:'0 0 8px', fontSize:17, fontWeight:700 }}>Reunião criada!</h3>
          <p style={{ fontSize:13, color:'var(--fg-muted)', marginBottom:16 }}>Link Google Meet gerado:</p>
          <div style={{ background:'var(--bg-elevated)', borderRadius:8, padding:'10px 14px', fontFamily:'var(--font-mono,monospace)', fontSize:11, wordBreak:'break-all', border:'1px solid var(--border-subtle)', marginBottom:18, textAlign:'left' }}>{meetLink}</div>
          <div style={{ display:'flex', gap:10, justifyContent:'center' }}>
            <Button variant="secondary" onClick={() => { navigator.clipboard?.writeText(meetLink); window.__toast?.('Copiado!', { tone:'success' }); }}>Copiar link</Button>
            <Button onClick={onClose}>Fechar</Button>
          </div>
        </div>
      </div>
    );
  }

  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(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)' }}>Agenda · {contactName}</div>
            <h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Novo agendamento</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}>Tipo</span>
            <div style={{ display:'flex', gap:8 }}>
              {[{ v:'reuniao',l:'Reunião',c:'#1D39C4' },{ v:'entrega',l:'Entrega',c:'#22C55E' },{ v:'call',l:'Call',c:'#FA541C' }].map(t => (
                <button key={t.v} onClick={() => setTipo(t.v)} style={{ flex:1, padding:'9px 0', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background: tipo===t.v ? t.c+'22' : 'var(--bg-elevated)', color: tipo===t.v ? t.c : 'var(--fg-muted)', border:`1.5px solid ${tipo===t.v ? t.c+'66' : 'var(--border-subtle)'}` }}>{t.l}</button>
              ))}
            </div>
          </div>
          <div>
            <span style={LS}>Título</span>
            <input autoFocus value={titulo} onChange={e => setTitulo(e.target.value)} onKeyDown={e => e.key==='Enter' && confirmar()} placeholder={tipo==='reuniao'?'Ex: Apresentação de proposta':'Ex: Entrega versão final'} style={IS}/>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 130px', gap:12 }}>
            <div><span style={LS}>Data</span><input type="date" value={data} onChange={e => setData(e.target.value)} style={IS}/></div>
            <div><span style={LS}>Hora</span><input type="time" value={hora} onChange={e => setHora(e.target.value)} style={IS}/></div>
          </div>
          <div>
            <span style={LS}>Observação (opcional)</span>
            <textarea value={desc} onChange={e => setDesc(e.target.value)} placeholder="Detalhes do agendamento…" rows={2} style={{ ...IS, resize:'none', lineHeight:1.55 }}/>
          </div>
          {tipo === 'reuniao' && (
            <label style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer', userSelect:'none', padding:'10px 14px', borderRadius:10, background: withMeet ? 'rgba(0,137,123,0.08)' : 'var(--bg-elevated)', border:`1px solid ${withMeet ? 'rgba(0,137,123,0.35)' : 'var(--border-subtle)'}`, transition:'all 180ms' }}>
              <button type="button" onClick={() => setWithMeet(m => !m)} style={{ width:40, height:22, borderRadius:11, border:'none', cursor:'pointer', background: withMeet ? '#00897b' : 'var(--border-strong)', position:'relative', transition:'background 200ms', flexShrink:0 }}>
                <span style={{ position:'absolute', top:2, left: withMeet ? 'calc(100% - 20px)' : 2, width:18, height:18, borderRadius:'50%', background:'#fff', transition:'left 200ms', boxShadow:'0 1px 4px rgba(0,0,0,0.3)' }}/>
              </button>
              <div>
                <div style={{ fontSize:13, fontWeight:600, color: withMeet ? '#00897b' : 'var(--fg-secondary)' }}>📹 Criar link Google Meet</div>
                <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>Gera link Meet e cria evento no Google Calendar</div>
              </div>
            </label>
          )}
        </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 onClick={confirmar} style={{ opacity:saving?0.6:1, pointerEvents:saving?'none':'auto', ...(withMeet && tipo==='reuniao' ? { background:'#00897b' } : {}) }}>
            {saving ? 'Criando…' : withMeet && tipo==='reuniao' ? '📹 Criar reunião com Meet' : 'Confirmar agendamento'}
          </Button>
        </div>
      </div>
    </div>
  );
}

// ─── Dados de prévia dos projetos ─────────────────────────────────────────────
const MINI_PROJECT_DATA = {
  'Rebranding · Astra': { status:'Em andamento', sc:'#1890FF', progress:68, color:'#1D39C4', tasks:12, done:8,  deadline:'20 Mai 2026', team:['Ana S.','Marcos R.'], tasks3:[{ t:'Logo versão final',done:true },{ t:'Paleta de cores',done:true },{ t:'Manual de marca',done:false }] },
  'Site Café Norte':    { status:'Em revisão',   sc:'#FADB14', progress:85, color:'#36CFC9', tasks:8,  done:7,  deadline:'15 Mai 2026', team:['Lucas V.'],            tasks3:[{ t:'Homepage responsiva',done:true },{ t:'Integração formulário',done:true },{ t:'SEO e meta tags',done:false }] },
  'App Bemvindo':       { status:'Em andamento', sc:'#1890FF', progress:42, color:'#FA541C', tasks:18, done:7,  deadline:'30 Jun 2026', team:['Ana S.','Lucas V.'],   tasks3:[{ t:'Fluxo de onboarding',done:true },{ t:'Tela de perfil',done:false },{ t:'Notificações push',done:false }] },
  'Identidade Visual':  { status:'Aguardando',   sc:'#7A859A', progress:20, color:'#7C3AED', tasks:6,  done:1,  deadline:'—',           team:['Marcos R.'],            tasks3:[{ t:'Pesquisa de referências',done:true },{ t:'Primeiros estudos',done:false },{ t:'Apresentação de conceito',done:false }] },
};

const ATTACHMENT_LIST = [
  { name:'palette-final.pdf', ext:'PDF', color:'#FA541C', size:'2.4 MB',  desc:'Paleta de cores final — Rebranding Astra' },
  { name:'mockups-v3.fig',    ext:'FIG', color:'#A0D911', size:'8.1 MB',  desc:'Mockups versão 3 — arquivo Figma'          },
  { name:'briefing.docx',     ext:'DOC', color:'#1890FF', size:'340 KB',  desc:'Briefing preenchido pelo cliente'           },
];

// ─── Prévia de arquivo ────────────────────────────────────────────────────────
function FilePreviewModal({ file, onClose }) {
  const OV = { position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:300, display:'flex', alignItems:'center', justifyContent:'center', padding:24 };

  function download() {
    window.__toast?.(`Baixando ${file.name}…`, { tone:'success' });
    onClose();
  }

  const EXT_VISUALS = {
    PDF: { lines: ['#FA541C44','#FA541C33','#FA541C22','#FA541C44','#FA541C33'], label:'Documento PDF' },
    FIG: { lines: ['#A0D91144','#A0D91133','#A0D91122','#A0D91144','#A0D91133'], label:'Arquivo Figma'  },
    DOC: { lines: ['#1890FF44','#1890FF33','#1890FF22','#1890FF44','#1890FF33'], label:'Documento Word' },
  };
  const vis = EXT_VISUALS[file.ext] || EXT_VISUALS.DOC;

  return (
    <div onClick={onClose} style={OV}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(440px,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:'18px 22px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:12 }}>
          <span style={{ fontFamily:'var(--font-display)', fontSize:10, fontWeight:700, color:'#fff', background:file.color, padding:'4px 8px', borderRadius:6 }}>{file.ext}</span>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:14, fontWeight:700, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{file.name}</div>
            <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>{file.size}</div>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4 }}><Icon d={ICONS.x} size={16}/></button>
        </div>
        <div style={{ padding:'20px 22px', background:'var(--bg-elevated)', borderBottom:'1px solid var(--border-subtle)' }}>
          <div style={{ borderRadius:10, border:`1px solid ${file.color}33`, background:file.color+'0a', padding:18, display:'flex', flexDirection:'column', gap:10 }}>
            <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:4 }}>
              <div style={{ width:32, height:40, borderRadius:4, background:file.color+'33', border:`1px solid ${file.color}44`, display:'grid', placeItems:'center' }}>
                <span style={{ fontFamily:'var(--font-display)', fontSize:8, fontWeight:700, color:file.color }}>{file.ext}</span>
              </div>
              <div>
                <div style={{ fontSize:12, fontWeight:600 }}>{file.name}</div>
                <div style={{ fontSize:11, color:'var(--fg-muted)' }}>{vis.label} · {file.size}</div>
              </div>
            </div>
            {vis.lines.map((bg, i) => (
              <div key={i} style={{ height:8, borderRadius:4, background:bg, width: [90,75,85,60,70][i]+'%' }}/>
            ))}
          </div>
        </div>
        <div style={{ padding:'14px 22px' }}>
          <div style={{ fontSize:12, color:'var(--fg-secondary)', lineHeight:1.5 }}>{file.desc}</div>
        </div>
        <div style={{ padding:'12px 22px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'flex-end', gap:10, background:'var(--bg-elevated)' }}>
          <Button variant="ghost" onClick={onClose}>Fechar</Button>
          <Button onClick={download}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{ marginRight:6 }}><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
            Baixar arquivo
          </Button>
        </div>
      </div>
    </div>
  );
}

// ─── Miniatura do projeto ─────────────────────────────────────────────────────
function MiniProjectPanel({ projName, projClient, onOpenFull, onClose }) {
  const data = MINI_PROJECT_DATA[projName] || { status:'Em andamento', sc:'#1890FF', progress:0, color:'#1D39C4', tasks:0, done:0, deadline:'—', team:[], tasks3:[] };
  const OV = { position:'fixed', inset:0, background:'rgba(8,12,28,0.55)', backdropFilter:'blur(4px)', zIndex:300, display:'flex', alignItems:'center', justifyContent:'center', padding:24 };

  return (
    <div onClick={onClose} style={OV}>
      <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={{ background:`linear-gradient(135deg, ${data.color}2a, ${data.color}0f)`, borderBottom:'1px solid var(--border-subtle)', padding:'18px 22px', display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
          <div>
            <div style={{ fontFamily:'var(--font-display)', fontSize:11, fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--geek-blue-300)', marginBottom:4 }}>Projetos · Prévia rápida</div>
            <h2 style={{ margin:0, fontSize:19, fontWeight:700 }}>{projName}</h2>
            <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:4 }}>{projClient}</div>
          </div>
          <button onClick={onClose} style={{ background:'transparent', border:'none', color:'var(--fg-muted)', cursor:'pointer', padding:4, flexShrink:0 }}><Icon d={ICONS.x} size={16}/></button>
        </div>
        <div style={{ padding:'18px 22px', display:'flex', flexDirection:'column', gap:18 }}>
          <div>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:10 }}>
              <span style={{ fontSize:12, fontWeight:600, color:data.sc, background:data.sc+'18', padding:'3px 12px', borderRadius:20 }}>{data.status}</span>
              <span style={{ fontSize:14, fontWeight:700, fontFamily:'var(--font-display)', color:data.color }}>{data.progress}%</span>
            </div>
            <div style={{ height:8, background:'var(--bg-elevated)', borderRadius:999, overflow:'hidden' }}>
              <div style={{ width:data.progress+'%', height:'100%', background:data.color, borderRadius:999 }}/>
            </div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:10 }}>
            {[{ v:`${data.done}/${data.tasks}`,l:'Tarefas' },{ v:data.deadline,l:'Entrega' },{ v:data.team.join(', '),l:'Equipe' }].map(s => (
              <div key={s.l} style={{ padding:'10px 12px', borderRadius:10, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', textAlign:'center' }}>
                <div style={{ fontSize:12, fontWeight:700, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{s.v}</div>
                <div style={{ fontSize:10, color:'var(--fg-muted)', marginTop:3 }}>{s.l}</div>
              </div>
            ))}
          </div>
          <div>
            <div style={{ fontSize:10, fontFamily:'var(--font-display)', fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)', marginBottom:10 }}>Últimas tarefas</div>
            <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
              {data.tasks3.map((task, i) => (
                <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 12px', borderRadius:8, background:'var(--bg-elevated)' }}>
                  <div style={{ width:16, height:16, borderRadius:'50%', background:task.done?data.color:'transparent', border:`2px solid ${task.done?data.color:'var(--border-strong)'}`, display:'grid', placeItems:'center', flexShrink:0 }}>
                    {task.done && <svg width="8" height="8" viewBox="0 0 8 8"><path d="M1.5 4l2 2 3-3" stroke="#fff" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                  </div>
                  <span style={{ fontSize:13, flex:1, color:task.done?'var(--fg-muted)':'var(--fg-primary)', textDecoration:task.done?'line-through':'none' }}>{task.t}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div style={{ padding:'12px 22px', borderTop:'1px solid var(--border-subtle)', display:'flex', justifyContent:'space-between', alignItems:'center', background:'var(--bg-elevated)' }}>
          <Button variant="ghost" onClick={onClose}>Fechar</Button>
          <Button onClick={onOpenFull}>Abrir projeto completo →</Button>
        </div>
      </div>
    </div>
  );
}

// ─── Criar projeto (a partir da conversa) ────────────────────────────────────
function CriarProjetoModal({ contactName, onClose, onCreate }) {
  const [name,     setName]     = useState('');
  const [tipo,     setTipo]     = useState('Identidade Visual');
  const [deadline, setDeadline] = useState('');

  const TYPES = ['Identidade Visual','Site','App','Social Media','Branding','Outro'];
  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 };

  function create() {
    if (!name.trim()) { window.__toast?.('Informe o nome do projeto', { tone:'danger' }); return; }
    onCreate({ name: name.trim(), client: contactName, tipo, deadline });
  }

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(8,12,28,0.65)', backdropFilter:'blur(6px)', zIndex:300, display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'min(460px,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)' }}>Mensagens · {contactName}</div>
            <h2 style={{ margin:'4px 0 0', fontSize:18, fontWeight:700 }}>Criar 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={{ padding:24, display:'flex', flexDirection:'column', gap:18 }}>
          <div>
            <span style={LS}>Nome do projeto *</span>
            <input autoFocus value={name} onChange={e => setName(e.target.value)} onKeyDown={e => e.key==='Enter' && create()} placeholder={`Ex: Identidade Visual · ${contactName}`} style={IS}/>
          </div>
          <div>
            <span style={LS}>Tipo</span>
            <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
              {TYPES.map(t => (
                <button key={t} onClick={() => setTipo(t)} style={{ padding:'6px 14px', borderRadius:20, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', background:tipo===t?'var(--primary)22':'var(--bg-elevated)', color:tipo===t?'var(--accent-primary)':'var(--fg-muted)', border:`1.5px solid ${tipo===t?'var(--primary)66':'var(--border-subtle)'}` }}>{t}</button>
              ))}
            </div>
          </div>
          <div>
            <span style={LS}>Data de entrega (opcional)</span>
            <input type="date" value={deadline} onChange={e => setDeadline(e.target.value)} style={IS}/>
          </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={create}>Criar projeto</Button>
        </div>
      </div>
    </div>
  );
}

// ─── Messages ─────────────────────────────────────────────────────────────────
function Messages({ onNav }) {
  const [active,           setActive]           = useState(0);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
  const [agendarOpen,      setAgendarOpen]      = useState(false);
  const [attachedFile,     setAttachedFile]     = useState(null);
  const [inputText,        setInputText]        = useState('');
  const [selectedFile,     setSelectedFile]     = useState(null);
  const [projPanelOpen,    setProjPanelOpen]    = useState(false);
  const [creatingProj,     setCreatingProj]     = useState(false);
  const fileRef = React.useRef(null);
  const msgsEnd = React.useRef(null);

  const [threads, setThreads] = useState([
    { n:'Renata · Astra',     last:'Mandei o feedback nos mockups, dá uma olhada quando puder!', when:'12:24', unread:2, company:'Astra Cosméticos',  projName:'Rebranding · Astra', projClient:'Astra Cosméticos'  },
    { n:'Pedro · Café Norte', last:'Posso aprovar a versão 02?',          when:'11:08', unread:0, company:'Café Norte',       projName:'Site Café Norte',    projClient:'Café Norte'        },
    { n:'Mariana · Bemvindo', last:'Adorei a apresentação 🙌',            when:'09:42', unread:0, company:'Studio Bemvindo',   projName:'App Bemvindo',       projClient:'Studio Bemvindo'   },
    { n:'João · Norte Foods', last:'Vamos remarcar a call?',              when:'Ontem', unread:1, company:'Norte Foods',       projName:'Identidade Visual',  projClient:'Norte Foods'       },
    { n:'Equipe · #design',   last:'Sub. ícones — pronto pra review',    when:'Ontem', unread:0, company:'Interno',           projName:null,                 projClient:null                },
  ]);

  const [messages, setMessages] = useState([
    { who:'Renata', t:'Oi Ana, tudo bem? Recebi os primeiros estudos.', mine:false, h:'12:18', file:null },
    { who:'Renata', t:'Acho que estamos super alinhados na direção 02.',mine:false, h:'12:19', file:null },
    { who:'Ana',    t:'Que bom! Posso seguir com ela então?',           mine:true,  h:'12:21', file:null },
    { who:'Renata', t:'Mandei o feedback nos mockups, dá uma olhada quando puder!', mine:false, h:'12:24', file:null },
  ]);

  React.useEffect(() => { msgsEnd.current?.scrollIntoView({ behavior:'smooth' }); }, [messages.length]);

  function nowTime() {
    const d = new Date();
    return `${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
  }

  function sendMessage() {
    if (!inputText.trim() && !attachedFile) return;
    setMessages(prev => [...prev, { who:'Ana', t:inputText.trim(), mine:true, h:nowTime(), file: attachedFile?.name || null }]);
    setInputText('');
    setAttachedFile(null);
  }

  function openFullProject() {
    const th = threads[active];
    setProjPanelOpen(false);
    if (window.__openProject) window.__openProject({ name: th.projName, client: th.projClient });
    else onNav?.('projects');
  }

  function createProject(data) {
    setThreads(prev => prev.map((t, i) => i === active ? { ...t, projName: data.name, projClient: data.client } : t));
    setCreatingProj(false);
    window.__toast?.(`Projeto "${data.name}" criado com sucesso`, { tone:'success' });
  }

  const th = threads[active];

  const hBtn = (onClick, children, extra = {}) => (
    <button onClick={onClick} style={{ padding:'6px 12px', borderRadius:7, border:'1px solid var(--border-subtle)', background:'var(--bg-elevated)', color:'var(--fg-secondary)', cursor:'pointer', fontSize:12, fontWeight:600, fontFamily:'inherit', display:'flex', alignItems:'center', gap:6, flexShrink:0, ...extra }}
      onMouseEnter={e => e.currentTarget.style.background='var(--border-subtle)'}
      onMouseLeave={e => e.currentTarget.style.background = extra.background || 'var(--bg-elevated)'}>
      {children}
    </button>
  );

  return (
    <div style={{ display:'grid', gridTemplateColumns:`300px 1fr${sidebarCollapsed ? '' : ' 290px'}`, height:'calc(100vh - 80px)', borderTop:'1px solid var(--border-subtle)' }}>

      {/* ── Thread list ── */}
      <div style={{ borderRight:'1px solid var(--border-subtle)', overflow:'auto', display:'flex', flexDirection:'column' }}>
        <div style={{ padding:'12px 14px', borderBottom:'1px solid var(--border-subtle)', flexShrink:0 }}>
          <Field icon="search" placeholder="Buscar conversa…"/>
        </div>
        {threads.map((t, i) => (
          <div key={i} onClick={() => setActive(i)}
            style={{ padding:'13px 14px', borderBottom:'1px solid var(--border-subtle)', cursor:'pointer', background: active===i ? 'var(--primary-soft)' : 'transparent', display:'flex', gap:10, alignItems:'flex-start' }}
            onMouseEnter={e => { if (active!==i) e.currentTarget.style.background='var(--bg-elevated)'; }}
            onMouseLeave={e => { if (active!==i) e.currentTarget.style.background='transparent'; }}>
            <Avatar name={t.n} size={38} idx={i}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap:6 }}>
                <span style={{ fontSize:13, fontWeight:600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{t.n}</span>
                <span style={{ fontSize:10, color:'var(--fg-muted)', fontFamily:'var(--font-mono)', flexShrink:0 }}>{t.when}</span>
              </div>
              <div style={{ fontSize:12, color:'var(--fg-muted)', marginTop:2, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{t.last}</div>
            </div>
            {t.unread > 0 && <span style={{ background:'var(--primary)', color:'#fff', fontSize:10, fontFamily:'var(--font-mono)', borderRadius:999, padding:'1px 7px', fontWeight:700, flexShrink:0 }}>{t.unread}</span>}
          </div>
        ))}
      </div>

      {/* ── Chat ── */}
      <div style={{ display:'flex', flexDirection:'column', minWidth:0 }}>
        <div style={{ padding:'11px 16px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:8, flexShrink:0, flexWrap:'wrap' }}>
          <Avatar name={th.n} size={34} idx={active}/>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:14, fontWeight:700, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{th.n}</div>
            <div style={{ fontSize:11, color:'var(--fg-muted)' }}>online · {th.company}</div>
          </div>
          {hBtn(() => setAgendarOpen(true), <><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>Agendar</>)}
          {th.projName
            ? hBtn(() => setProjPanelOpen(true), <><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z"/></svg>Projeto</>)
            : hBtn(() => setCreatingProj(true), <><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>Criar projeto</>)
          }
          <button onClick={() => setSidebarCollapsed(c => !c)} title={sidebarCollapsed ? 'Expandir painel' : 'Compactar painel'} style={{ width:32, height:32, borderRadius:7, border:'1px solid var(--border-subtle)', background: sidebarCollapsed ? 'var(--primary)18' : 'var(--bg-elevated)', color: sidebarCollapsed ? 'var(--accent-primary)' : 'var(--fg-muted)', cursor:'pointer', display:'grid', placeItems:'center', flexShrink:0 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              {sidebarCollapsed ? <><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><polyline points="11 9 7 12 11 15"/></> : <><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><polyline points="19 9 15 12 19 15"/></>}
            </svg>
          </button>
        </div>

        <div style={{ flex:1, overflow:'auto', padding:'18px 22px', display:'flex', flexDirection:'column', gap:12 }}>
          {messages.map((m, i) => (
            <div key={i} style={{ display:'flex', gap:10, justifyContent: m.mine ? 'flex-end' : 'flex-start' }}>
              {!m.mine && <Avatar name={m.who} size={28} idx={0}/>}
              <div style={{ maxWidth:'65%', background: m.mine ? 'var(--primary)' : 'var(--bg-elevated)', color: m.mine ? '#fff' : 'var(--fg-primary)', padding:'10px 14px', borderRadius: m.mine ? '14px 14px 4px 14px' : '14px 14px 14px 4px', fontSize:13, lineHeight:1.5 }}>
                {m.t && <div>{m.t}</div>}
                {m.file && (
                  <div style={{ display:'flex', alignItems:'center', gap:7, marginTop: m.t ? 7 : 0, background: m.mine ? 'rgba(255,255,255,0.15)' : 'var(--bg-surface)', borderRadius:7, padding:'6px 10px' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
                    <span style={{ fontSize:12, fontWeight:500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', maxWidth:160 }}>{m.file}</span>
                  </div>
                )}
                <div style={{ fontSize:10, color: m.mine ? 'rgba(255,255,255,0.65)' : 'var(--fg-muted)', marginTop:5, fontFamily:'var(--font-mono)' }}>{m.h}</div>
              </div>
            </div>
          ))}
          <div ref={msgsEnd}/>
        </div>

        <div style={{ padding:'10px 16px', borderTop:'1px solid var(--border-subtle)', flexShrink:0 }}>
          {attachedFile && (
            <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:8, padding:'5px 10px', borderRadius:8, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', fontSize:12 }}>
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--accent-primary)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
              <span style={{ flex:1, color:'var(--fg-primary)', fontWeight:500 }}>{attachedFile.name}</span>
              <button onClick={() => setAttachedFile(null)} style={{ background:'transparent', border:'none', cursor:'pointer', color:'var(--fg-muted)', fontSize:15, lineHeight:1, padding:'0 2px' }}>✕</button>
            </div>
          )}
          <div style={{ display:'flex', gap:8, alignItems:'center' }}>
            <input ref={fileRef} type="file" style={{ display:'none' }} onChange={e => { const f = e.target.files?.[0]; if (f) setAttachedFile(f); e.target.value=''; }}/>
            <button onClick={() => fileRef.current?.click()} title="Anexar arquivo" style={{ width:34, height:34, borderRadius:7, border:'1px solid var(--border-subtle)', background: attachedFile ? 'var(--primary)18' : 'var(--bg-elevated)', color: attachedFile ? 'var(--accent-primary)' : 'var(--fg-muted)', cursor:'pointer', display:'grid', placeItems:'center', flexShrink:0 }}>
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
            </button>
            <input value={inputText} onChange={e => setInputText(e.target.value)} onKeyDown={e => e.key==='Enter' && !e.shiftKey && sendMessage()} placeholder="Escreva uma mensagem…" style={{ flex:1, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', borderRadius:10, padding:'10px 14px', color:'var(--fg-primary)', fontFamily:'inherit', fontSize:13, outline:'none' }}/>
            <button onClick={sendMessage} style={{ padding:'9px 18px', borderRadius:8, border:'none', background:'var(--primary)', color:'#fff', cursor:'pointer', fontSize:13, fontWeight:600, fontFamily:'inherit', flexShrink:0 }}>Enviar</button>
          </div>
        </div>
      </div>

      {/* ── Right panel (collapsible) ── */}
      {!sidebarCollapsed && (
        <div style={{ borderLeft:'1px solid var(--border-subtle)', overflow:'auto', display:'flex', flexDirection:'column' }}>
          <div style={{ padding:'16px 16px 12px', borderBottom:'1px solid var(--border-subtle)', display:'flex', alignItems:'center', gap:12, flexShrink:0 }}>
            <Avatar name={th.n} size={40} idx={active}/>
            <div style={{ minWidth:0 }}>
              <div style={{ fontSize:13, fontWeight:700, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{th.n}</div>
              <div style={{ fontSize:11, color:'var(--fg-muted)', marginTop:2 }}>{th.company}</div>
            </div>
          </div>
          <div style={{ flex:1, overflow:'auto', padding:'14px 14px', display:'flex', flexDirection:'column', gap:16 }}>
            <div>
              <div style={{ fontSize:10, fontFamily:'var(--font-display)', fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)', marginBottom:8 }}>Projeto</div>
              {th.projName ? (
                <div onClick={() => setProjPanelOpen(true)} style={{ padding:'11px 13px', borderRadius:10, background:'var(--bg-elevated)', border:'1px solid var(--border-subtle)', cursor:'pointer' }}
                  onMouseEnter={e => e.currentTarget.style.borderColor='var(--primary)'}
                  onMouseLeave={e => e.currentTarget.style.borderColor='var(--border-subtle)'}>
                  <div style={{ fontSize:13, fontWeight:600 }}>{th.projName}</div>
                  <div style={{ fontSize:11, color:'var(--accent-primary)', marginTop:3 }}>Ver prévia do projeto →</div>
                </div>
              ) : (
                <div style={{ padding:'11px 13px', borderRadius:10, background:'var(--bg-elevated)', border:'1px dashed var(--border-subtle)' }}>
                  <div style={{ fontSize:12, color:'var(--fg-muted)', marginBottom:8 }}>Nenhum projeto vinculado.</div>
                  <button onClick={() => setCreatingProj(true)} style={{ width:'100%', padding:'7px 0', borderRadius:7, border:'1px solid var(--primary)66', background:'var(--primary)18', color:'var(--accent-primary)', cursor:'pointer', fontSize:12, fontWeight:600, fontFamily:'inherit' }}>+ Criar projeto</button>
                </div>
              )}
            </div>
            <div>
              <div style={{ fontSize:10, fontFamily:'var(--font-display)', fontWeight:700, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--fg-muted)', marginBottom:8 }}>Anexos recentes</div>
              {ATTACHMENT_LIST.map(f => (
                <div key={f.name} onClick={() => setSelectedFile(f)} style={{ display:'flex', alignItems:'center', gap:10, padding:'9px 11px', borderRadius:8, background:'var(--bg-elevated)', marginBottom:6, cursor:'pointer' }}
                  onMouseEnter={ev => ev.currentTarget.style.background='var(--border-subtle)'}
                  onMouseLeave={ev => ev.currentTarget.style.background='var(--bg-elevated)'}>
                  <span style={{ fontFamily:'var(--font-display)', fontSize:9, fontWeight:700, color:'#fff', background:f.color, padding:'3px 6px', borderRadius:4, flexShrink:0 }}>{f.ext}</span>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:12, fontWeight:500, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{f.name}</div>
                    <div style={{ fontSize:10, color:'var(--fg-muted)', marginTop:1 }}>{f.size}</div>
                  </div>
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--fg-muted)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {agendarOpen    && <AgendarModal     contactName={th.n} onClose={() => setAgendarOpen(false)} />}
      {selectedFile   && <FilePreviewModal file={selectedFile} onClose={() => setSelectedFile(null)} />}
      {projPanelOpen  && <MiniProjectPanel projName={th.projName} projClient={th.projClient} onOpenFull={openFullProject} onClose={() => setProjPanelOpen(false)} />}
      {creatingProj   && <CriarProjetoModal contactName={th.company} onClose={() => setCreatingProj(false)} onCreate={createProject} />}
    </div>
  );
}
window.Messages = Messages;
