// components-offer.jsx — Subscription offer card with countdown, plans, bumps, dynamic total

function Countdown({ deadline }) {
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  let diff = Math.max(0, deadline - now);
  const h = Math.floor(diff / 3600000); diff -= h * 3600000;
  const m = Math.floor(diff / 60000); diff -= m * 60000;
  const s = Math.floor(diff / 1000);
  return (
    <span style={{ fontVariantNumeric: 'tabular-nums', color: 'var(--body-text)' }}>
      {h}h {String(m).padStart(2,'0')}m {String(s).padStart(2,'0')}s
    </span>
  );
}

function Bump({ id, on, onToggle, title, price }) {
  return (
    <div className="bump" id={id} data-on={on ? '1' : '0'} onClick={onToggle} role="checkbox" aria-checked={on}>
      <span className="bump__check">
        <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
          <path d="M2 6.5l2.5 2.5 5.5-6" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
        </svg>
      </span>
      <span className="bump__title">{title}</span>
      <span className="bump__price">+{formatBRL(price)}</span>
    </div>
  );
}

function formatBRL(n) {
  return 'R$ ' + n.toFixed(2).replace('.', ',');
}

function PlanCard({ popular, badges, strike, price, period, ctaLabel, ctaPrimary, selected, onSelect, planoKey, openCheckout }) {
  const onCta = (e) => {
    e.stopPropagation();
    if (openCheckout) openCheckout(e);
  };
  return (
    <div
      className={'plan' + (popular ? ' plan--popular' : '')}
      onClick={onSelect}
      style={{ cursor: 'pointer', outline: selected ? '2px solid rgba(255,32,112,0.6)' : 'none', outlineOffset: -1 }}
    >
      <div className="plan__badges">
        {badges.map((b, i) => (
          <span key={i} className={'pill ' + (b.style === 'outline' ? 'pill--pink-outline' : 'pill--pink')}>{b.label}</span>
        ))}
      </div>
      <div>
        <div className="plan__strike">{formatBRL(strike)}</div>
        <div className="plan__price">{formatBRL(price)}<small>/{period}</small></div>
      </div>
      <button
        className={'btn btn--full ' + (ctaPrimary ? 'btn--primary' : 'btn--secondary')}
        data-plano={planoKey}
        onClick={onCta}
      >
        {ctaLabel}
      </button>
    </div>
  );
}

function OfferSection({ planLayout, deadlineRef, plan, setPlan, bumps, setBumps, total, openCheckout }) {
  const stacked = planLayout !== 'side-by-side';

  const mensal = (
    <PlanCard
      popular
      badges={[{ label: 'Mais popular', style: 'fill' }, { label: 'Economize 80%', style: 'outline' }]}
      strike={89.90}
      price={17.90}
      period="mês"
      ctaLabel="Assinar agora"
      ctaPrimary
      selected={plan === 'mes'}
      onSelect={() => setPlan('mes')}
      planoKey="mensal"
      openCheckout={openCheckout}
    />
  );
  const trimestral = (
    <PlanCard
      badges={[{ label: 'Economize 81%', style: 'outline' }]}
      strike={179.90}
      price={33.90}
      period="3 meses"
      ctaLabel="Quero 3 meses"
      ctaPrimary={false}
      selected={plan === 'tri'}
      onSelect={() => setPlan('tri')}
      planoKey="trimestral"
      openCheckout={openCheckout}
    />
  );

  return (
    <section className="section" id="offer">
      <div className="card">
        <div className="spark section__title section__title--small" style={{ marginBottom: 14 }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="#FF2070">
              <path d="M12 2l1.8 6.5L20 10l-6.2 1.5L12 18l-1.8-6.5L4 10l6.2-1.5z"/>
            </svg>
            Oferta de assinatura
          </span>
        </div>

        <div style={{ marginBottom: 14, display: 'flex', alignItems: 'baseline', gap: 6, fontSize: 13 }}>
          <span style={{ color: 'var(--muted)' }}>Termina em</span>
          <Countdown deadline={deadlineRef} />
        </div>

        <div className="scarcity">
          <span className="scarcity__dot" />
          Restam apenas <strong style={{ color: '#fff', fontWeight: 600 }}>7 vagas</strong> neste valor
        </div>

        <div style={{
          display: stacked ? 'flex' : 'grid',
          flexDirection: 'column',
          gridTemplateColumns: stacked ? undefined : '1fr 1fr',
          gap: 12,
          marginTop: 8,
        }}>
          {mensal}
          {trimestral}
        </div>

        <p style={{
          textAlign: 'center', margin: '12px 0 0', fontSize: 12,
          color: 'var(--muted)',
        }}>
          Quer economizar mais? <strong style={{ color: 'var(--pink-light)', fontWeight: 500 }}>Pegando 3 meses você economiza 81%</strong>
        </p>

        <div style={{ marginTop: 16 }}>
          <Bump
            id="bump-fotos"
            on={bumps.fotos}
            onToggle={() => setBumps((b) => ({ ...b, fotos: !b.fotos }))}
            title="Pack de fotos exclusivas"
            price={9.90}
          />
          <div style={{ borderTop: '1px solid var(--border)' }} />
          <Bump
            id="bump-video"
            on={bumps.video}
            onToggle={() => setBumps((b) => ({ ...b, video: !b.video }))}
            title="Videochamada privada com a Gaby"
            price={50.00}
          />
        </div>

        <div className="total">
          <span className="total__lbl">Total:</span>
          <span className="total__val">{formatBRL(total)}</span>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { OfferSection, formatBRL });
