// DualPlanCard — card comparativo (produto individual x Combo Premium), usado nas páginas de
// conteúdo/projeto/home/perfil pra oferecer a assinatura individual ao lado do combo. Componente
// global autocontido (sem bundler) — cada página que precisar dele adiciona:
//   <script type="text/babel" src="/assets/dual-plan-card.jsx"></script>
// antes do próprio script da página, e usa <DualPlanCard individualSlug="pimentinhas" />.

(function () {
  // Cache simples em memória — evita refazer o fetch de /api/products em cada instância/página.
  let productsPromise = null;
  function loadProducts() {
    if (!productsPromise) {
      productsPromise = fetch('/api/products').then(r => r.json()).catch(() => []);
    }
    return productsPromise;
  }

  function fmtPriceCents(cents) {
    return (cents / 100).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  // Logos de marca — mesmos arquivos usados pela landing real do combo (landing.jsx). SVGs vêm
  // pretos por padrão, invertidos pra branco via filter (mesmo padrão de lá); o PNG do
  // Pimentinhas já vem pronto, sem filtro.
  const PROJECT_LOGOS = {
    sxclube: '/assets/logo-sexy-clube.svg',
    papo: '/assets/logo-papo-pijama.svg',
    pimentinhas: '/assets/logo-pimentinhas.png',
    casapim: '/assets/logo-casa-pimentinhas.svg',
  };
  const COMBO_LOGOS = ['sxclube', 'papo', 'pimentinhas', 'casapim'].map(k => PROJECT_LOGOS[k]);

  function BrandLogos({ logos, size = 22 }) {
    if (!logos || logos.length === 0) return null;
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
        {logos.map(src => (
          <img key={src} src={src} height={size} alt=""
            style={{ opacity: 0.95, filter: src.endsWith('.svg') ? 'brightness(0) invert(1)' : 'none' }} />
        ))}
      </div>
    );
  }

  function PlanCard({ product, href, logos }) {
    const featured = product.display?.style === 'featured';
    return (
      <div style={{
        flex: '1 1 240px', minWidth: 240,
        background: featured ? 'var(--bg-elevated)' : 'var(--bg-surface)',
        border: featured ? '1px solid rgba(123,63,242,0.4)' : '1px solid var(--border-subtle)',
        borderRadius: 'var(--radius-lg)',
        padding: 24,
        boxShadow: featured ? 'var(--shadow-card), var(--glow-purple)' : 'var(--shadow-card)',
        transform: featured ? 'scale(1.02)' : 'none',
        display: 'flex', flexDirection: 'column', gap: 16,
      }}>
        <BrandLogos logos={logos} size={logos && logos.length > 1 ? 18 : 24} />
        {product.display?.badge && (
          <span style={{
            alignSelf: 'flex-start', fontSize: 'var(--text-xs)', fontWeight: 700,
            letterSpacing: 'var(--tracking-widest)', textTransform: 'uppercase',
            padding: '4px 12px', borderRadius: 'var(--radius-full)',
            background: 'var(--gradient-sx)', color: '#fff',
          }}>{product.display.badge}</span>
        )}
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)', color: 'var(--text-primary)' }}>
            {product.name}
          </div>
          <div style={{ marginTop: 6, display: 'flex', alignItems: 'baseline', gap: 4 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-3xl)', color: 'var(--text-primary)' }}>
              R$ {fmtPriceCents(product.priceCents)}
            </span>
            <span style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>/mês</span>
          </div>
        </div>
        {Array.isArray(product.display?.features) && product.display.features.length > 0 && (
          <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {product.display.features.map(f => (
              <li key={f} style={{ display: 'flex', alignItems: 'flex-start', gap: 8, fontSize: 'var(--text-sm)', color: 'var(--text-secondary)' }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={featured ? 'var(--purple-light)' : 'var(--text-secondary)'} strokeWidth="2.5" style={{ flexShrink: 0, marginTop: 2 }}>
                  <path d="M20 6L9 17l-5-5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                {f}
              </li>
            ))}
          </ul>
        )}
        <a href={href} style={{
          marginTop: 'auto', textAlign: 'center', textDecoration: 'none',
          padding: '12px 20px', borderRadius: 'var(--radius-full)',
          fontSize: 'var(--text-sm)', fontWeight: 700, fontFamily: 'var(--font-ui)',
          background: featured ? 'var(--gradient-sx)' : 'transparent',
          color: featured ? '#fff' : 'var(--text-primary)',
          border: featured ? 'none' : '1px solid var(--border-strong)',
          boxShadow: featured ? '0 0 20px rgba(123,63,242,0.35)' : 'none',
        }}>
          Assinar {product.name}
        </a>
      </div>
    );
  }

  function DualPlanCard({ individualSlug, title = 'Escolha seu acesso' }) {
    const [products, setProducts] = React.useState(null);

    React.useEffect(() => {
      let alive = true;
      loadProducts().then(list => { if (alive) setProducts(list); });
      return () => { alive = false; };
    }, []);

    if (!products) return null;

    const combo = products.find(p => p.slug === 'combo_premium');
    // /api/products só lista produtos "reais" (sem alias) — casapim não aparece ali (é o mesmo
    // produto que pimentinhas), então também casamos por `projetos` pra não perder o card
    // individual em páginas do projeto casapim.
    const individual = individualSlug
      ? products.find(p => p.slug === individualSlug || (p.projetos && p.projetos.includes(individualSlug)))
      : null;
    if (!combo) return null;

    return (
      <div style={{ margin: '32px 0' }}>
        {title && (
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'var(--text-xl)', color: 'var(--text-primary)', marginBottom: 16 }}>
            {title}
          </div>
        )}
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap' }}>
          {individual && (
            <PlanCard
              product={individual}
              href={`/assinar?produto=${individualSlug}`}
              logos={[PROJECT_LOGOS[individualSlug] || PROJECT_LOGOS[individual.slug]]}
            />
          )}
          <PlanCard product={combo} href={`/assinar?produto=${combo.slug}`} logos={COMBO_LOGOS} />
        </div>
      </div>
    );
  }

  window.DualPlanCard = DualPlanCard;
})();
