// ============================================================================
// Página de Playbooks de Vendas
// ============================================================================

function PagePlaybooks({ open }) {
  const [active, setActive] = useState('todos');
  const filters = [
    { id: 'todos', label: 'Todos os playbooks', count: PLAYBOOKS.length },
    { id: 'investimento', label: 'Usinas de Investimento' },
    { id: 'assinatura', label: 'Energia por Assinatura' },
    { id: 'convencional', label: 'Sistemas Convencionais' },
    { id: 'arrendamento', label: 'Arrendamento' },
    { id: 'bess', label: 'BESS · Armazenamento' },
  ];
  const list = active === 'todos' ? PLAYBOOKS : PLAYBOOKS.filter(p => p.pal === active);
  return (
    <div style={{ padding: '28px 28px 60px' }}>
      <PageHeader
        eyebrow="01 · Playbooks de Vendas"
        title={<>Playbooks comerciais <em style={{ fontFamily: 'Instrument Serif, serif', fontStyle: 'italic', color: 'var(--amber)' }}>vivos</em>, por produto.</>}
        sub="Cada playbook traz a jornada comercial, diagnóstico, argumentos, diferenciais Ampexx, objeções e roteiro de apresentação. Use durante a reunião e mantenha sincronizado com o time."
        cta={[{ label: 'Como propor um novo playbook', kind: 'ghost' }, { label: 'Modelo padrão de playbook', kind: 'primary' }]}
      />

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '8px 0 22px', flexWrap: 'wrap' }}>
        {filters.map(f => (
          <button key={f.id} onClick={() => setActive(f.id)} style={{
            padding: '8px 14px', borderRadius: 999, fontSize: 12.5, fontWeight: 600,
            background: active === f.id ? 'var(--navy)' : 'var(--paper)',
            color: active === f.id ? '#fff' : 'var(--ink-2)',
            border: active === f.id ? '1px solid var(--navy)' : '1px solid var(--line)',
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>
            {f.label}
            {f.count != null && <span style={{ background: active === f.id ? 'rgba(255,255,255,.15)' : 'var(--bg-2)', borderRadius: 99, padding: '1px 6px', fontSize: 10 }}>{f.count}</span>}
          </button>
        ))}
        <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, color: 'var(--ink-3)' }}>
          <Icon.filter s={14}/> Ordenar: Mais atualizados
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 22 }}>
        {list.map(p => <PlaybookCard key={p.id} p={p} open={open}/>)}
      </div>

      <PlaybookProcessBanner />
    </div>
  );
}

// ============================================================================
// Card vertical estilo "G4 pílulas" — mas com ilustração própria por produto
// ============================================================================
function PlaybookCard({ p, open }) {
  const pal = PRODUCT_PALETTES[p.pal];
  const isDark = pal.ink === '#fff';
  return (
    <Card hoverable onClick={() => open && open(p)} style={{
      overflow: 'hidden', border: 'none',
      background: 'transparent', padding: 0,
    }}>
      <div style={{
        background: pal.bg, color: pal.ink,
        borderRadius: 18, overflow: 'hidden', position: 'relative',
        minHeight: 360, padding: '20px 22px 22px', display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, opacity: .7, letterSpacing: '.08em' }}>{p.code}</span>
            <StatusPill status={p.status} dark={isDark}/>
          </div>
          <AmpexxMark size={20} color={pal.ink} accent={pal.accent}/>
        </div>

        <PlaybookCover kind={p.cover} ink={pal.ink} accent={pal.accent}/>

        <div style={{ marginTop: 'auto' }}>
          <div style={{ fontSize: 11, opacity: .75, letterSpacing: '.04em' }}>Playbook de Vendas</div>
          <h3 style={{
            margin: '6px 0 0', fontFamily: 'Instrument Serif, serif',
            fontWeight: 400, fontSize: 30, lineHeight: 1.05, letterSpacing: '-0.02em',
          }}>{p.title}</h3>
          <div style={{ marginTop: 8, fontSize: 12.5, opacity: .8, lineHeight: 1.4 }}>{p.subtitle}</div>

          <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 14, fontSize: 11, opacity: .7 }}>
            <span>{p.sections} capítulos</span><span>·</span>
            <span>{p.duration}</span><span>·</span>
            <span>Atualizado {p.updated}</span>
          </div>
        </div>
      </div>

      {/* rodapé com info de manutenção */}
      <div style={{ padding: '12px 4px 4px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-3)' }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
          <Icon.shield s={13}/>
          <span>{p.owner}</span>
        </div>
        <button style={{ fontWeight: 600, color: 'var(--ink)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>Abrir <Icon.arrow s={12}/></button>
      </div>
    </Card>
  );
}

function StatusPill({ status, dark }) {
  const m = {
    'Atualizado': { bg: 'rgba(47,107,79,.22)', fg: '#9CC9B0' },
    'Novo':       { bg: 'rgba(232,155,44,.22)', fg: '#F0B656' },
    'Revisão':    { bg: 'rgba(184,83,51,.22)', fg: '#F3A88B' },
    'Rascunho':   { bg: 'rgba(255,255,255,.12)', fg: dark ? 'rgba(255,255,255,.75)' : 'var(--ink-3)' },
  }[status] || { bg: 'rgba(0,0,0,.08)', fg: dark ? '#fff' : 'var(--ink-2)' };
  if (!dark) {
    // versão sobre fundo claro
    const light = {
      'Atualizado': { bg: 'rgba(47,107,79,.14)', fg: '#1F4F37' },
      'Novo':       { bg: 'rgba(232,155,44,.18)', fg: '#8A560A' },
      'Revisão':    { bg: 'rgba(184,83,51,.16)', fg: '#7B341A' },
      'Rascunho':   { bg: 'rgba(14,31,56,.08)', fg: 'var(--navy)' },
    }[status] || m;
    return <span style={{ padding: '3px 8px', borderRadius: 99, fontSize: 10, fontWeight: 700, background: light.bg, color: light.fg, letterSpacing: '.04em' }}>{status}</span>;
  }
  return <span style={{ padding: '3px 8px', borderRadius: 99, fontSize: 10, fontWeight: 700, background: m.bg, color: m.fg, letterSpacing: '.04em' }}>{status}</span>;
}

// Ilustração por playbook — geométrica, original
function PlaybookCover({ kind, ink, accent }) {
  const stroke = ink === '#fff' ? 'rgba(255,255,255,.55)' : 'rgba(14,26,43,.55)';
  const faint = ink === '#fff' ? 'rgba(255,255,255,.15)' : 'rgba(14,26,43,.15)';
  if (kind === 'sun-grid') {
    return (
      <svg viewBox="0 0 280 160" width="100%" height="120" style={{ marginTop: 16 }}>
        {/* grid base */}
        {[20,50,80,110,140].map(y => <line key={y} x1="0" x2="280" y1={y} y2={y} stroke={faint}/>)}
        {/* arcos */}
        <g transform="translate(200,80)">
          <circle r="48" fill="none" stroke={stroke}/>
          <circle r="34" fill="none" stroke={stroke}/>
          <circle r="22" fill={accent}/>
        </g>
        {/* "ativos" empilhados */}
        {[0,1,2,3,4,5,6].map(i => (
          <rect key={i} x={20+i*14} y={120 - (i*8)} width="10" height={20 + i*8} fill={accent} opacity={0.4 + i*0.08}/>
        ))}
      </svg>
    );
  }
  if (kind === 'meter') {
    return (
      <svg viewBox="0 0 280 160" width="100%" height="120" style={{ marginTop: 16 }}>
        {/* medidor */}
        <rect x="30" y="35" width="120" height="90" rx="6" fill="none" stroke={stroke}/>
        <rect x="42" y="55" width="96" height="22" fill={accent} opacity=".25"/>
        <rect x="42" y="55" width="60" height="22" fill={accent}/>
        <rect x="42" y="86" width="80" height="6" fill={stroke} opacity=".5"/>
        <rect x="42" y="98" width="50" height="6" fill={stroke} opacity=".5"/>
        {/* seta indicando economia */}
        <path d="M178 70 L240 40" stroke={accent} strokeWidth="2"/>
        <path d="M240 40 L233 38 M240 40 L238 47" stroke={accent} strokeWidth="2"/>
        <text x="190" y="100" fill={ink} fontSize="11" fontFamily="JetBrains Mono, monospace" opacity=".7">- 22%</text>
      </svg>
    );
  }
  if (kind === 'panel') {
    return (
      <svg viewBox="0 0 280 160" width="100%" height="120" style={{ marginTop: 16 }}>
        {/* painéis solares em perspectiva */}
        <g transform="skewX(-18) translate(50,20)">
          <rect x="0" y="0" width="160" height="100" fill="none" stroke={stroke}/>
          {[0,1,2,3].map(r => <line key={`r${r}`} x1="0" y1={r*25} x2="160" y2={r*25} stroke={faint}/>)}
          {[0,1,2,3,4].map(c => <line key={`c${c}`} x1={c*40} y1="0" x2={c*40} y2="100" stroke={faint}/>)}
          <rect x="0" y="0" width="40" height="25" fill={accent} opacity=".7"/>
          <rect x="80" y="50" width="40" height="25" fill={accent} opacity=".5"/>
        </g>
        <circle cx="240" cy="35" r="16" fill={accent}/>
      </svg>
    );
  }
  if (kind === 'handshake') {
    return (
      <svg viewBox="0 0 280 160" width="100%" height="120" style={{ marginTop: 16 }}>
        {/* duas formas se encontrando */}
        <path d="M30 100 L100 100 L130 70 L160 100 L240 100" stroke={stroke} fill="none" strokeWidth="1.5"/>
        <circle cx="70" cy="100" r="14" fill={accent}/>
        <circle cx="200" cy="100" r="14" fill="none" stroke={accent} strokeWidth="2"/>
        <rect x="130" y="55" width="30" height="30" fill={accent} opacity=".4"/>
      </svg>
    );
  }
  if (kind === 'battery') {
    return (
      <svg viewBox="0 0 280 160" width="100%" height="120" style={{ marginTop: 16 }}>
        <rect x="40" y="50" width="180" height="60" rx="6" fill="none" stroke={stroke}/>
        <rect x="220" y="68" width="10" height="24" fill={stroke}/>
        <rect x="48" y="58" width="46" height="44" fill={accent}/>
        <rect x="100" y="58" width="46" height="44" fill={accent} opacity=".5"/>
        <rect x="152" y="58" width="46" height="44" fill="none" stroke={stroke} strokeDasharray="3 3"/>
      </svg>
    );
  }
  return null;
}

// ============================================================================
// Banner com processo padrão de criação
// ============================================================================
function PlaybookProcessBanner() {
  const steps = [
    { n: '01', t: 'Objetivo' },
    { n: '02', t: 'Visão Geral' },
    { n: '03', t: 'Público-alvo' },
    { n: '04', t: 'Jornada' },
    { n: '05', t: 'Diagnóstico' },
    { n: '06', t: 'Argumentos' },
    { n: '07', t: 'Diferenciais' },
    { n: '08', t: 'Objeções' },
    { n: '09', t: 'Roteiro' },
    { n: '10', t: 'Qualificação' },
    { n: '11', t: 'Próximos passos' },
    { n: '12', t: 'FAQ' },
  ];
  return (
    <section style={{ marginTop: 48, background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 22, padding: '28px 32px' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 32, alignItems: 'flex-start' }}>
        <div>
          <Pill tone="amber"><Icon.shield s={11}/> Padrão Ampexx</Pill>
          <h3 style={{ margin: '12px 0 8px', fontFamily: 'Instrument Serif, serif', fontWeight: 400, fontSize: 32, lineHeight: 1.05, letterSpacing: '-0.02em' }}>
            Estrutura padrão de um playbook
          </h3>
          <p style={{ margin: 0, fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.55 }}>
            Todo playbook publicado no portal segue exatamente esses 12 blocos. Antes de propor um novo playbook, valide o esqueleto com a coordenação comercial.
          </p>
          <button style={{
            marginTop: 14, padding: '10px 14px', borderRadius: 10,
            background: 'var(--navy)', color: '#fff', fontWeight: 600, fontSize: 12.5,
            display: 'inline-flex', alignItems: 'center', gap: 6,
          }}>Abrir modelo em branco <Icon.arrow s={13}/></button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
          {steps.map(s => (
            <div key={s.n} style={{ border: '1px solid var(--line)', borderRadius: 12, padding: '12px 14px', background: 'var(--bg)' }}>
              <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: 'var(--amber)', letterSpacing: '.08em' }}>{s.n}</div>
              <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: 4 }}>{s.t}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---- Header padrão de página -----------------------------------------------
function PageHeader({ eyebrow, title, sub, cta }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 32, padding: '0 0 24px', borderBottom: '1px solid var(--line)', marginBottom: 28 }}>
      <div style={{ maxWidth: 700 }}>
        <div style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '.16em', textTransform: 'uppercase', marginBottom: 8 }}>{eyebrow}</div>
        <h1 style={{
          margin: 0, fontFamily: 'Instrument Serif, serif', fontWeight: 400,
          fontSize: 48, lineHeight: 1.02, letterSpacing: '-0.02em', color: 'var(--ink)',
        }}>{title}</h1>
        {sub && <p style={{ margin: '14px 0 0', fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.55 }}>{sub}</p>}
      </div>
      {cta && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto', paddingBottom: 8 }}>
          {cta.map((c, i) => (
            <button key={i} style={
              c.kind === 'primary'
                ? { padding: '11px 16px', borderRadius: 10, background: 'var(--navy)', color: '#fff', fontWeight: 600, fontSize: 12.5 }
                : { padding: '11px 16px', borderRadius: 10, background: 'transparent', color: 'var(--ink-2)', fontWeight: 600, fontSize: 12.5, border: '1px solid var(--line)' }
            }>{c.label}</button>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PagePlaybooks, PageHeader, PlaybookCard, PlaybookCover, StatusPill });
