// Sem números inventados — quem chama este componente deve passar `stats` vindo de /api/stats
// (contagens reais do catálogo). Esse default só cobre o caso de a chamada da API ainda não ter
// voltado (evita number flicker), nunca deveria aparecer publicado de verdade.
const DEFAULT_STATS = [
  { num: '—', label: 'ensaios', sub: 'no catálogo' },
  { num: '—', label: 'modelos', sub: 'cadastradas' },
  { num: '—', label: 'fotos',   sub: 'no total' },
];

function useIsNarrow(bp) {
  const [narrow, setNarrow] = React.useState(typeof window !== 'undefined' && window.innerWidth < bp);
  React.useEffect(() => {
    const on = () => setNarrow(window.innerWidth < bp);
    window.addEventListener('resize', on);
    return () => window.removeEventListener('resize', on);
  }, [bp]);
  return narrow;
}

/**
 * Sexy Geek DS — banner de conversão de assinatura. V2: peça de destaque de verdade (não mais
 * uma tira fina de estatísticas) — usa o vocabulário "geek" do DS (geek-fx.css): cantos
 * pixelados, scanlines de CRT, ruído sutil, badge estilo prompt de terminal com cursor piscando,
 * e o headline com glitch de separação RGB contínuo (roda sozinho, não depende de hover pra ser
 * percebido).
 *
 * `backdrop` (opcional): um nó qualquer (ex: <DriftWall/>) usado pra fundir a seção de assinatura
 * com uma vitrine de fotos, em vez de serem dois blocos separados na página. No desktop vira um
 * pano de fundo em tela cheia com véu escuro pra legibilidade; no mobile vira um bloco próprio
 * (uma tira do mural) empilhado ACIMA do bloco de informações — nada de foto atrás de texto lá,
 * pra sobrar mais foto visível numa tela estreita (ver `renderMobileStacked` abaixo).
 */
function ComboBanner({
  stats = DEFAULT_STATS, price = '29,90', period = '/mês', ctaLabel = 'Assinar agora',
  headline = 'ACESSO TOTAL AO CATÁLOGO', badgeLabel = 'sexy_geek --subscribe',
  backdrop, secondaryCtaLabel, onSecondaryCta, onSubscribe,
}) {
  const [hov, setHov] = React.useState(false);
  const isMobile = useIsNarrow(760);
  const overlay = !!backdrop && !isMobile; // só sobrepõe texto na foto no desktop

  const badge = (
    <span
      className="gx-caret"
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 7, alignSelf: 'flex-start',
        padding: '5px 12px', borderRadius: 6, background: 'rgba(98,216,255,0.08)',
        border: '1px solid rgba(98,216,255,0.35)', fontFamily: 'var(--font-mono)', fontSize: 11,
        color: 'var(--blue-light)', letterSpacing: '0.01em',
      }}
    >
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--blue-light)', boxShadow: '0 0 8px var(--blue-light)' }} />
      {'> ' + badgeLabel}
    </span>
  );

  const headlineEl = (
    <h3
      className="gx-glitch"
      data-text={headline}
      style={{
        fontFamily: 'var(--font-display)', fontWeight: 700, textTransform: 'uppercase',
        fontSize: isMobile ? 24 : 'clamp(26px, 2.6vw, 38px)', lineHeight: 1.08, letterSpacing: '-0.01em',
        color: '#fff', margin: 0, textShadow: overlay ? '0 2px 12px rgba(0,0,0,0.6)' : 'none',
      }}
    >
      {headline}
    </h3>
  );

  const paragraph = (
    <p style={{ fontFamily: 'var(--font-ui)', fontSize: 13.5, color: 'var(--text-secondary)', maxWidth: 440, lineHeight: 1.6, margin: 0 }}>
      Toda foto exclusiva de todo ensaio, liberada na hora. Sem taxa de adesão, cancele quando quiser.
    </p>
  );

  const statsRow = (
    <div style={{ display: 'flex', gap: isMobile ? 18 : 28, flexWrap: 'wrap', marginTop: 4 }}>
      {stats.map((s, i) => (
        <div key={i}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, lineHeight: 1, letterSpacing: '-0.02em', background: 'linear-gradient(135deg,#62D8FF,#0876C9 58%,#04518F)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text' }}>{s.num}</div>
          <div style={{ fontFamily: 'var(--font-ui)', fontSize: 11, color: 'var(--text-muted)', marginTop: 4, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{s.label}</div>
        </div>
      ))}
    </div>
  );

  const secondaryLink = secondaryCtaLabel && (
    <button
      type="button" onClick={onSecondaryCta}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6, alignSelf: 'flex-start', marginTop: 2,
        background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
        fontFamily: 'var(--font-ui)', fontSize: 12, fontWeight: 600, letterSpacing: '0.03em',
        textTransform: 'uppercase', color: 'var(--text-secondary)', pointerEvents: 'auto',
      }}
    >
      {secondaryCtaLabel}
      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14M12 5l7 7-7 7" /></svg>
    </button>
  );

  const priceCard = (
    <div
      className="gx-pixel-corners-sm"
      style={{
        flexShrink: 0, zIndex: 2, position: 'relative', alignSelf: isMobile ? 'stretch' : 'center',
        width: isMobile ? 'auto' : 220, background: 'rgba(20,20,28,0.75)', backdropFilter: 'blur(8px)',
        border: '1px solid rgba(255,255,255,0.1)', padding: '22px 22px 20px',
        display: 'flex', flexDirection: 'column', alignItems: isMobile ? 'stretch' : 'center', gap: 14,
        textAlign: isMobile ? 'left' : 'center',
      }}
    >
      <div style={{ display: 'flex', alignItems: isMobile ? 'baseline' : 'center', flexDirection: isMobile ? 'row' : 'column', gap: isMobile ? 8 : 0, justifyContent: isMobile ? 'space-between' : 'flex-start' }}>
        <span style={{ fontSize: 10, color: 'var(--text-muted)', fontFamily: 'var(--font-ui)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>A partir de</span>
        <span style={{ display: 'flex', alignItems: 'baseline', gap: 3 }}>
          <span style={{ fontSize: 13, color: '#EFEFEF', fontWeight: 500, fontFamily: 'var(--font-ui)' }}>R$</span>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 32, color: '#fff', lineHeight: 1, letterSpacing: '-0.02em' }}>{price}</span>
          <span style={{ fontSize: 12, color: 'var(--text-muted)', fontFamily: 'var(--font-ui)' }}>{period}</span>
        </span>
      </div>
      <button type="button" onClick={onSubscribe}
        onMouseEnter={e => { e.currentTarget.style.transform = 'scale(1.03)'; e.currentTarget.style.boxShadow = '0 0 30px rgba(8,118,201,0.6)'; }}
        onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; e.currentTarget.style.boxShadow = '0 0 16px rgba(8,118,201,0.35)'; }}
        style={{
          width: '100%', background: 'var(--gradient-sx)', border: 'none', borderRadius: 9999,
          padding: '13px 22px', fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13.5,
          color: '#fff', cursor: 'pointer', letterSpacing: '0.03em', textTransform: 'uppercase',
          boxShadow: '0 0 16px rgba(8,118,201,0.35)', whiteSpace: 'nowrap', transition: 'transform 0.2s, box-shadow 0.2s',
        }}>
        {ctaLabel}
      </button>
      <span style={{ fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-ui)' }}>Cancele quando quiser</span>
    </div>
  );

  // ── Mobile + mural: duas tiras empilhadas — fotos em cima, informações embaixo. Nada de
  // texto sobre foto aqui (era o motivo do pedido de "mais visão das fotos" no mobile).
  if (backdrop && isMobile) {
    return (
      <div
        className="gx-pixel-corners"
        style={{
          position: 'relative', overflow: 'hidden', background: '#0d0d14',
          border: '1px solid rgba(255,255,255,0.08)', boxShadow: '0 8px 32px rgba(0,0,0,0.45)',
        }}
      >
        {/* `overflow:hidden` aqui é cinto-e-suspensório: o `height` já vai clonado pro valor certo
            abaixo, mas sem isso, se algum dia alguém passar um backdrop com altura própria maior
            que a tira, os tiles de baixo ficariam clicáveis por baixo do bloco de informações
            mesmo invisíveis — o mesmo tipo de bug do clique que já resolvemos pro desktop. */}
        <div style={{ position: 'relative', height: 220, overflow: 'hidden', pointerEvents: 'none' }}>
          {/* O `backdrop` recebido já vem com a altura do desktop (480) — clona só pra encaixar
              na tira mobile, em vez de confiar só no corte visual do wrapper. `pointerEvents:none`
              aqui + reset em `.dw-viewport` (geek-fx.css), mesmo motivo do branch desktop acima. */}
          {React.isValidElement(backdrop) ? React.cloneElement(backdrop, { height: 220 }) : backdrop}
          {/* Transição suave pro bloco de baixo — não é um véu de legibilidade, só evita um
              corte seco entre o mural e o fundo sólido. */}
          <div style={{
            position: 'absolute', inset: 0,
            background: 'linear-gradient(to bottom, transparent 65%, #0d0d14 100%)',
          }} />
        </div>
        <div
          className="gx-scanlines gx-noise"
          style={{
            position: 'relative', display: 'flex', flexDirection: 'column', gap: 16, padding: '22px 20px 26px',
            background: 'radial-gradient(ellipse 90% 70% at 20% 0%, rgba(98,216,255,0.14), transparent 65%), #0d0d14',
          }}
        >
          {badge}
          {headlineEl}
          {paragraph}
          {statsRow}
          {secondaryLink}
          <div style={{ marginTop: 4 }}>{priceCard}</div>
        </div>
      </div>
    );
  }

  return (
    <div
      className="gx-pixel-corners gx-scanlines gx-noise"
      onMouseEnter={() => setHov(true)} onMouseLeave={() => setHov(false)}
      style={{
        position: 'relative', overflow: 'hidden',
        background: backdrop ? '#0d0d14' :
                    'radial-gradient(ellipse 70% 100% at 0% 0%, rgba(98,216,255,0.22), transparent 60%),' +
                    'radial-gradient(ellipse 60% 90% at 100% 100%, rgba(8,118,201,0.26), transparent 55%),' +
                    '#0d0d14',
        border: `1px solid ${hov ? 'rgba(8,118,201,0.5)' : 'rgba(255,255,255,0.08)'}`,
        boxShadow: hov ? '0 0 48px rgba(8,118,201,0.22), 0 12px 40px rgba(0,0,0,0.5)' : '0 8px 32px rgba(0,0,0,0.45)',
        transition: 'border-color 0.3s, box-shadow 0.3s',
        display: 'flex', flexDirection: isMobile ? 'column' : 'row',
        alignItems: 'stretch', gap: isMobile ? 24 : 0,
        padding: isMobile ? '28px 22px' : '44px 48px',
        minHeight: overlay ? 480 : 'auto',
      }}
    >
      {overlay && (
        <React.Fragment>
          {/* `pointerEvents:none` aqui é o que garante que as fotos continuam clicáveis: sem
              isso, essa div (mesmo transparente) intercepta o clique sempre que a rotação 3D do
              mural desalinha um pouco a geometria do que está pintado na tela vs. onde o
              navegador acha que o elemento "realmente" está. `.dw-viewport` reativa
              pointer-events por conta própria (ver geek-fx.css), então as fotos continuam
              recebendo clique normalmente. */}
          <div style={{ position: 'absolute', inset: 0, zIndex: 0, pointerEvents: 'none' }}>{backdrop}</div>
          <div style={{
            position: 'absolute', inset: 0, zIndex: 1, pointerEvents: 'none',
            background: 'linear-gradient(100deg, rgba(6,6,10,0.94) 0%, rgba(6,6,10,0.8) 34%, rgba(6,6,10,0.35) 62%, rgba(6,6,10,0.15) 100%)',
          }} />
        </React.Fragment>
      )}

      {/* `pointerEvents:none` aqui pelo mesmo motivo dos wrappers do backdrop acima: essa coluna
          é `flex:1` (ocupa a largura toda sobrando pro texto), mas o texto em si não preenche
          essa caixa — as fotos por trás ficavam bloqueadas em qualquer espaço vazio ao redor das
          linhas. O único filho interativo (link "Ver todas as modelos") reativa pointer-events
          nele mesmo. */}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 16, zIndex: 2, position: 'relative', pointerEvents: overlay ? 'none' : 'auto' }}>
        {badge}
        {headlineEl}
        {paragraph}
        {statsRow}
        {secondaryLink}
      </div>

      {priceCard}
    </div>
  );
}

window.SexyGeekDS = window.SexyGeekDS || {};
window.SexyGeekDS.ComboBanner = ComboBanner;
