const { Reveal, Icon, MagneticBtn, useLandingStats } = window;
const { useEffect, useState } = React;

// Formate le temps restant jusqu'à endsAt (ISO string) → "5j 12h" / "12h 34m 05s" / null si expiré/invalide
function formatCountdown(endsAt) {
  if (!endsAt) return null;
  const end = new Date(endsAt).getTime();
  if (Number.isNaN(end)) return null;
  const diff = end - Date.now();
  if (diff <= 0) return null;
  const sec = Math.floor(diff / 1000);
  const days = Math.floor(sec / 86400);
  const hours = Math.floor((sec % 86400) / 3600);
  const mins = Math.floor((sec % 3600) / 60);
  const secs = sec % 60;
  if (days >= 1) return `${days}j ${hours}h`;
  return `${String(hours).padStart(2, '0')}h ${String(mins).padStart(2, '0')}m ${String(secs).padStart(2, '0')}s`;
}

function useCountdown(endsAt) {
  const [label, setLabel] = useState(() => formatCountdown(endsAt));
  useEffect(() => {
    if (!endsAt) { setLabel(null); return; }
    setLabel(formatCountdown(endsAt));
    const id = setInterval(() => setLabel(formatCountdown(endsAt)), 1000);
    return () => clearInterval(id);
  }, [endsAt]);
  return label;
}

function Pricing() {
  const { packs, landing } = useLandingStats();
  const ctaUrls = {
    starter: landing?.ctaStarter || '#',
    pro:     landing?.ctaPro     || '#',
    premium: landing?.ctaPremium || '#',
  };

  const PACKS = [
    {
      id: 'starter', name: 'Starter',
      price: packs.starter.price,
      originalPrice: packs.starter.originalPrice,
      promo: packs.starter.promo,
      href: ctaUrls.starter,
      tagline: 'Fondations solides.',
      cta: "Je passe à l'action",
      hours: packs.starter.hours ?? 9,
      lessons: packs.starter.lessons ?? 48,
      commission: packs.starter.commission,
      incl: [
        { label: `Plus de ${packs.starter.hours ?? 9}h de formation`, locked: false },
        { label: `${packs.starter.commission}% de commission d'évolution`, locked: false },
        { label: 'VIZION Web inclus', locked: false },
        { label: 'VIZION Flow + Planner + Tracker verrouillés', locked: true },
        { label: 'VIZION IA + VIZION Trends verrouillés', locked: true },
      ],
    },
    {
      id: 'pro', name: 'Pro',
      price: packs.pro.price,
      originalPrice: packs.pro.originalPrice,
      promo: packs.pro.promo,
      href: ctaUrls.pro,
      tagline: 'Stratégie avancée.',
      cta: 'Je monte de niveau',
      hours: packs.pro.hours ?? 14,
      lessons: packs.pro.lessons ?? 144,
      commission: packs.pro.commission,
      popular: true,
      incl: [
        { label: `Plus de ${packs.pro.hours ?? 14}h de formation`, locked: false },
        { label: `${packs.pro.commission}% de commission d'évolution`, locked: false },
        { label: 'VIZION Web inclus', locked: false },
        { label: 'VIZION Flow + Planner + Tracker inclus', locked: false },
        { label: 'VIZION IA + VIZION Trends verrouillés', locked: true },
      ],
    },
    {
      id: 'premium', name: 'Premium',
      price: packs.premium.price,
      originalPrice: packs.premium.originalPrice,
      promo: packs.premium.promo,
      href: ctaUrls.premium,
      tagline: 'Formation intégrale.',
      cta: 'Je prends le meilleur',
      hours: packs.premium.hours ?? 17,
      lessons: packs.premium.lessons ?? 250,
      commission: packs.premium.commission,
      incl: [
        { label: `Plus de ${packs.premium.hours ?? 17}h de formation`, locked: false },
        { label: `${packs.premium.commission}% de commission d'évolution`, locked: false },
        { label: 'VIZION Web inclus', locked: false },
        { label: 'VIZION Flow + Planner + Tracker inclus', locked: false },
        { label: 'VIZION IA + VIZION Trends inclus', locked: false },
      ],
    },
  ];

  return (
    <section id="pricing" className="section">
      <div className="container">
        <Reveal className="section-header" style={{ textAlign: 'center', alignItems: 'center', marginLeft: 'auto', marginRight: 'auto' }}>
          <h2 className="h2" style={{ textAlign: 'center', textTransform: 'none' }}>
            <span style={{ fontSize: '1.15em' }}>Choisis ton niveau.</span><br />
            <span className="serif-i" style={{ color: 'var(--accent)', fontWeight: 400 }}>passe au niveau supérieur.</span>
          </h2>
          <p style={{ color: 'var(--ink-dim)', fontSize: 18, maxWidth: 520, textAlign: 'center', margin: '0 auto' }}>
            Trois packs, un paiement unique. Tu gardes l'accès à vie aux modules, aux outils et aux mises à jour.
          </p>
        </Reveal>

        <div className="packs-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
          {PACKS.map((p, i) => <PackCard key={p.id} pack={p} delay={i + 1} />)}
        </div>

        {/* Phrase de réassurance */}
        <p style={{ textAlign: 'center', color: 'var(--ink-mute)', fontSize: 13, marginTop: 32, marginBottom: 0 }}>
          Quel que soit le pack choisi, tu pourras toujours évoluer vers le suivant en ne payant que la différence.
        </p>

        {/* Badges garanties */}
        <div style={{ marginTop: 16, display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          {[
            { icon: <Icon.Check size={14} />, label: 'Paiement sécurisé' },
            { icon: <Icon.User size={14} />, label: 'Support inclus' },
            { icon: <Icon.Arrow size={14} />, label: 'Mises à jour à vie' },
          ].map((b, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 8,
              padding: '10px 18px', borderRadius: 999,
              background: 'var(--bg-card)', border: '1px solid var(--line)',
              color: 'var(--ink-dim)', fontSize: 13, fontWeight: 500,
            }}>
              <span style={{ color: 'var(--accent)', display: 'flex' }}>{b.icon}</span>
              {b.label}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function PackCard({ pack, delay }) {
  const isPop = pack.popular;
  const hasPromo = !!pack.promo && pack.originalPrice > pack.price;
  // Libellé brut selon le type de promo encodé en DB (fixed: -100€, percent: -20%)
  const promoLabel = hasPromo
    ? (pack.promo.type === 'percent' ? `-${pack.promo.value}%` : `-${pack.promo.value}€`)
    : '';
  const countdown = useCountdown(hasPromo ? pack.promo.endsAt : null);

  return (
    <Reveal delay={delay}>
      {/* Wrapper relatif pour les badges qui débordent au-dessus */}
      <div style={{ position: 'relative', paddingTop: 18 }}>

        {/* Badge POPULAIRE centré */}
        {isPop && !hasPromo && (
          <div style={{
            position: 'absolute', top: 0, left: '50%',
            transform: 'translateX(-50%)',
            zIndex: 2,
            padding: '5px 16px', borderRadius: 999,
            background: 'var(--accent)', color: 'var(--bg)',
            fontSize: 10, fontFamily: 'Geist Mono', letterSpacing: '0.12em', fontWeight: 700,
            whiteSpace: 'nowrap',
            boxShadow: '0 4px 20px -4px var(--accent-glow)',
          }}>POPULAIRE</div>
        )}

        {/* Badge PROMO centré — remplace POPULAIRE quand une promo est active */}
        {hasPromo && (
          <div style={{
            position: 'absolute', top: 0, left: '50%',
            transform: 'translateX(-50%)',
            zIndex: 2,
            padding: '5px 14px', borderRadius: 999,
            background: 'var(--accent)', color: 'var(--bg)',
            fontSize: 10, fontFamily: 'Geist Mono', letterSpacing: '0.12em', fontWeight: 700,
            whiteSpace: 'nowrap',
            boxShadow: '0 4px 20px -4px var(--accent-glow)',
            display: 'inline-flex', alignItems: 'center', gap: 6,
            animation: 'breathe 2.4s ease-in-out infinite',
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--bg)' }} />
            {pack.promo.label}
          </div>
        )}

      <div style={{
        padding: '28px 28px 32px', borderRadius: 28,
        background: (isPop || hasPromo) ? 'color-mix(in oklab, var(--accent) 5%, var(--bg-card))' : 'var(--bg-card)',
        border: (isPop || hasPromo) ? '1px solid var(--accent)' : '1px solid var(--line)',
        boxShadow: (isPop || hasPromo) ? '0 0 50px -10px var(--accent-glow)' : 'none',
        position: 'relative', overflow: 'hidden',
        transition: 'transform 0.3s',
        display: 'flex', flexDirection: 'column',
      }}
      onMouseEnter={e => e.currentTarget.style.transform = 'translateY(-6px)'}
      onMouseLeave={e => e.currentTarget.style.transform = 'translateY(0)'}
      data-cursor="hover">

        {/* Glow discret */}
        {(isPop || hasPromo) && <div style={{ position: 'absolute', top: -60, right: -60, width: 200, height: 200, background: 'radial-gradient(circle, var(--accent-glow), transparent 70%)', filter: 'blur(30px)', pointerEvents: 'none' }} />}

        {/* Tagline + Badge droits de revente sur la même ligne */}
        <div className="pack-header" style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 16 }}>
          <span style={{ fontSize: 11, fontFamily: 'Geist Mono', letterSpacing: '0.08em', color: 'var(--ink-mute)', textTransform: 'uppercase' }}>{pack.tagline}</span>
          <div className="pack-badge" style={{
            display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
            padding: '4px 10px', borderRadius: 6,
            background: 'color-mix(in oklab, var(--accent) 10%, transparent)',
            border: '1px solid color-mix(in oklab, var(--accent) 35%, transparent)',
            fontSize: 11, fontWeight: 700, color: 'var(--accent)', fontFamily: 'Geist, sans-serif',
          }}>
            <Icon.Check size={10} /> 100% droits de revente
          </div>
        </div>

        {/* Nom + Prix sur la même ligne */}
        <div className="pack-title-row" style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: hasPromo ? 8 : 20 }}>
          <h3 className="pack-title" style={{ fontSize: 38, fontFamily: 'Geist, sans-serif', fontWeight: 800, letterSpacing: '-0.03em', lineHeight: 1.05, margin: 0 }}>Pack<br />{pack.name}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', flexShrink: 0 }}>
            {hasPromo && (
              <span className="serif" style={{
                fontSize: 22, letterSpacing: '-0.02em', lineHeight: 1,
                color: 'var(--ink-mute)',
                textDecoration: 'line-through',
                textDecorationColor: 'color-mix(in oklab, var(--accent) 60%, transparent)',
                textDecorationThickness: 2,
                marginBottom: 2,
              }}>{pack.originalPrice}€</span>
            )}
            <span className="pack-price serif" style={{
              fontSize: 64, letterSpacing: '-0.04em', lineHeight: 1,
              color: hasPromo ? 'var(--accent)' : undefined,
            }}>{pack.price}€</span>
          </div>
        </div>

        {/* Libellé brut de la promo (valeur encodée en DB, non calculée) + countdown */}
        {hasPromo && (
          <div style={{
            display: 'flex', flexDirection: 'column', alignItems: 'flex-end',
            gap: 6, marginBottom: 20,
          }}>
            <div style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              padding: '4px 10px', borderRadius: 6,
              background: 'color-mix(in oklab, var(--accent) 14%, transparent)',
              border: '1px solid color-mix(in oklab, var(--accent) 40%, transparent)',
              fontSize: 11, fontWeight: 700, color: 'var(--accent)',
              fontFamily: 'Geist Mono', letterSpacing: '0.04em',
            }}>
              {promoLabel}
            </div>
            {countdown && (
              <div style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                fontSize: 10, fontFamily: 'Geist Mono',
                color: 'var(--ink-mute)', letterSpacing: '0.06em',
                textTransform: 'uppercase',
              }}>
                <span style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: 'var(--accent)',
                  boxShadow: '0 0 6px var(--accent-glow)',
                  animation: 'breathe 1.6s ease-in-out infinite',
                }} />
                Plus que {countdown}
              </div>
            )}
          </div>
        )}

        {/* Métriques */}
        <div className="pack-metrics" style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)',
          padding: '14px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)',
          marginBottom: 20, gap: 0,
        }}>
          <MetricCell n={`${pack.hours}h`} l="de formation" />
          <MetricCell n={pack.lessons} l="leçons" />
          <MetricCell n={`${pack.commission}%`} l="commission" accent />
        </div>

        {/* Features */}
        <ul style={{ listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10, marginBottom: 24, flex: 1 }}>
          {pack.incl.map((inc, i) => (
            <li key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, lineHeight: 1.4,
              color: inc.locked ? 'var(--ink-mute)' : 'var(--ink-dim)',
              opacity: inc.locked ? 0.5 : 1,
            }}>
              <span style={{ color: inc.locked ? 'var(--ink-mute)' : 'var(--accent)', marginTop: 0, flexShrink: 0 }}>
                {inc.locked ? <Icon.Lock size={12} /> : <Icon.Check size={12} />}
              </span>
              <span style={{ textDecoration: inc.locked ? 'line-through' : 'none' }}>{inc.label}</span>
            </li>
          ))}
        </ul>

        <MagneticBtn
          variant={(isPop || hasPromo) ? 'primary' : 'ghost'}
          href={pack.href}
          {...(pack.href && pack.href !== '#' ? { target: '_blank', rel: 'noopener noreferrer' } : {})}
          style={{ justifyContent: 'center', width: '100%' }}
        >
          {pack.cta} <span className="btn-arrow"><Icon.Arrow /></span>
        </MagneticBtn>
      </div>
      </div>
    </Reveal>
  );
}

function MetricCell({ n, l, accent }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontSize: 22, fontFamily: 'Geist, sans-serif', fontWeight: 800, letterSpacing: '-0.03em', color: accent ? 'var(--accent)' : 'var(--ink)', lineHeight: 1 }}>{n}</div>
      <div className="label" style={{ marginTop: 6, fontSize: 10 }}>{l}</div>
    </div>
  );
}

Object.assign(window, { Pricing });
