// Packages — matches old site: Boost / Signature (featured) / Komplettpaket / Custom
// Animated: staggered card reveal + magnetic hover tilt + gold sheen sweep
const { useState: useSt, useRef: useR, useEffect: useEf } = React;

function Packages({ lang }) {
  const t = (de, pl) => lang === 'de' ? de : pl;
  const [visible, setVisible] = useSt(false);
  const sectionRef = useR(null);

  useEf(() => {
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setVisible(true); obs.disconnect(); }
    }, { threshold: 0.2 });
    if (sectionRef.current) obs.observe(sectionRef.current);
    return () => obs.disconnect();
  }, []);

  const tiers = [
    { name: 'Boost', price: t('Auf Anfrage','Na zapytanie'),
      f: [t('2x Social-Media-Videos','2x filmy na media społecznościowe'),
          t('Videoproduzent bei Bedarf','Producent wideo w razie potrzeby'),
          t('Thumbnails inklusive','Thumbnails w cenie'),
          t('Skript & Musik','Skrypt i muzyka')],
      cta: t('Anfragen','Zapytaj') },
    { name: 'Signature', price: t('Auf Anfrage','Na zapytanie'),
      f: [t('4x Social Media Videos','4x filmy Social Media'),
          t('N8N Einrichtung + Datenbank','Konfiguracja N8N + baza danych'),
          t('1x KI-Automatisierung','1x Automatyzacja AI'),
          t('WhatsApp Priority-Support < 24h','WhatsApp Priority-Support < 24h')],
      cta: t('Anfragen','Zapytaj'), popular: true },
    { name: t('Komplettpaket','Pełny pakiet'), price: t('Auf Anfrage','Na zapytanie'),
      f: [t('Alles aus Signature inklusive','Wszystko z Signature w cenie'),
          t('8 Videos pro Monat','8 filmów miesięcznie'),
          t('Content-Plan & Strategie','Plan treści i strategia'),
          t('Kanalverwaltung & Werbeanzeigen','Zarządzanie kanałami i reklamy')],
      cta: t('Anfragen','Zapytaj') },
    { name: 'Custom', price: t('Individuell','Indywidualnie'),
      f: [t('Einzelvideos & N8N-Einrichtung','Pojedyncze filmy i konfiguracja N8N'),
          t('Individuelle KI-Automatisierungen','Indywidualne automatyzacje AI'),
          t('Monatlicher Automations-Support','Miesięczny support automatyzacji'),
          t('Kostenlose Prozessanalyse vorab','Bezpłatna analiza procesu')],
      cta: t('Gespräch vereinbaren','Umów rozmowę') }
  ];

  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const pkgScrollerRef = useR(null);
  const [pkgActive, setPkgActive] = useSt(1); // start on Signature (popular)
  const didInitScroll = useR(false);

  // Initial scroll to popular tier — runs ONCE
  useEf(() => {
    if (!isMobile) return;
    if (didInitScroll.current) return;
    const el = pkgScrollerRef.current;
    if (!el) return;
    didInitScroll.current = true;
    requestAnimationFrame(() => {
      el.scrollLeft = el.clientWidth;
    });
  }, [isMobile]);

  // Scroll listener — attached once, no pkgActive dep
  useEf(() => {
    if (!isMobile) return;
    const el = pkgScrollerRef.current;
    if (!el) return;
    let raf;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const idx = Math.round(el.scrollLeft / el.clientWidth);
        setPkgActive(prev => (prev !== idx && idx >= 0 && idx < tiers.length) ? idx : prev);
      });
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => { el.removeEventListener('scroll', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, [isMobile, tiers.length]);

  const scrollToPkg = (i) => {
    const el = pkgScrollerRef.current;
    if (!el) return;
    el.scrollTo({ left: i * el.clientWidth, behavior: 'smooth' });
  };

  return (
    <section ref={sectionRef} id="packages" className="section" style={{ position: 'relative', padding: isMobile ? '80px 0' : '120px 0', overflow: 'hidden' }}>
      {/* Ambient gold glow — sanft, damit Packages atmosphärisch unterscheidbar bleibt ohne harte Kante */}
      <div style={{
        position: 'absolute',
        top: '50%', left: '50%',
        width: 1200, height: 700,
        transform: 'translate(-50%, -50%)',
        borderRadius: '50%',
        background: 'radial-gradient(ellipse, rgba(212,175,55,.05) 0%, rgba(212,175,55,.02) 40%, transparent 70%)',
        filter: 'blur(60px)',
        pointerEvents: 'none',
        zIndex: 0
      }}/>
      <div className="container" style={{ position: 'relative', zIndex: 1 }}>
        <div style={{ textAlign: 'center', marginBottom: isMobile ? 44 : 72 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--gold)', letterSpacing: '.25em', textTransform: 'uppercase', marginBottom: 18 }}>— {t('Pakete','Pakiety')}</div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontSize: isMobile ? 'clamp(34px, 9vw, 44px)' : 64, lineHeight: 1.05, letterSpacing: '-0.03em' }}>
            {t('Wähle dein Paket','Wybierz swój pakiet')}
          </h2>
          <p style={{ fontSize: isMobile ? 14 : 16, color: 'var(--text-2)', marginTop: 16 }}>
            {t('Jedes Paket bringt dein Unternehmen messbar nach vorne.','Każdy pakiet mierzalnie rozwija Twój biznes.')}
          </p>
        </div>
        {isMobile ? (
          <div>
            {/* Pagination dots */}
            <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 18 }}>
              {tiers.map((tr, i) => (
                <button key={tr.name}
                  onClick={() => scrollToPkg(i)}
                  aria-label={`Go to ${tr.name}`}
                  style={{
                    width: i === pkgActive ? 28 : 8, height: 8, borderRadius: 50,
                    background: i === pkgActive ? 'var(--gold)' : 'rgba(212,175,55,.2)',
                    border: 'none', padding: 0, cursor: 'pointer',
                    transition: 'all .35s cubic-bezier(.2,.9,.3,1)',
                    boxShadow: i === pkgActive ? '0 0 12px rgba(212,175,55,.5)' : 'none'
                  }}/>
              ))}
            </div>
            {/* Snap scroller */}
            <div
              ref={pkgScrollerRef}
              className="pkg-mobile-scroller"
              style={{
                display: 'flex',
                overflowX: 'auto',
                overflowY: 'hidden',
                scrollSnapType: 'x mandatory',
                margin: '0 -20px',
                padding: '14px 20px 4px',
                gap: 14,
                scrollbarWidth: 'none',
                touchAction: 'pan-x',
                overscrollBehaviorX: 'contain'
              }}
            >
              {tiers.map((tr, i) => (
                <div key={tr.name} style={{
                  flex: '0 0 calc(100% - 28px)',
                  scrollSnapAlign: 'center'
                }}>
                  <PackageCard tr={tr} i={i} visible={visible} popularLabel={t('Beliebteste','Najpopularniejszy')} isMobile={isMobile}/>
                </div>
              ))}
            </div>
            {/* Swipe hint */}
            <div style={{
              display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8,
              marginTop: 16,
              fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.2em',
              color: 'var(--text-3)', textTransform: 'uppercase'
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>
              </svg>
              {t('Wischen', 'Przesuń')}
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>
              </svg>
            </div>
          </div>
        ) : (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(4,1fr)',
            gap: 18
          }}>
            {tiers.map((tr, i) => <PackageCard key={tr.name} tr={tr} i={i} visible={visible} popularLabel={t('Beliebteste','Najpopularniejszy')} isMobile={isMobile}/>)}
          </div>
        )}
      </div>
      <style>{`.pkg-mobile-scroller::-webkit-scrollbar { display: none; }`}</style>
    </section>
  );
}

function PackageCard({ tr, i, visible, popularLabel, isMobile = false }) {
  const [hover, setHover] = useSt(false);
  const [tilt, setTilt] = useSt({ x: 0, y: 0 });
  const ref = useR(null);

  const onMove = (e) => {
    if (isMobile) return;
    const r = ref.current.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width - 0.5;
    const py = (e.clientY - r.top) / r.height - 0.5;
    setTilt({ x: -py * 6, y: px * 6 });
  };

  return (
    <div
      ref={ref}
      onMouseEnter={() => { if (!isMobile) setHover(true); }}
      onMouseLeave={() => { if (!isMobile) { setHover(false); setTilt({ x: 0, y: 0 }); } }}
      onMouseMove={onMove}
      style={{
        position: 'relative',
        opacity: visible ? 1 : 0,
        transform: isMobile
          ? (visible ? 'translateY(0)' : 'translateY(20px)')
          : (visible
              ? `perspective(1000px) rotateX(${tilt.x}deg) rotateY(${tilt.y}deg) translateY(${hover ? -6 : 0}px)`
              : 'perspective(1000px) translateY(40px)'),
        transition: `opacity .9s cubic-bezier(.16,1,.3,1) ${0.1 + i*0.12}s, transform .5s cubic-bezier(.16,1,.3,1) ${visible ? 0 : (0.1 + i*0.12)}s`,
        transformStyle: isMobile ? 'flat' : 'preserve-3d',
        paddingTop: tr.popular ? 14 : 0,
        height: '100%'
      }}
    >
      {/* Popular badge — OUTSIDE overflow-clipped card */}
      {tr.popular && (
        <div style={{
          position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)',
          padding: '7px 16px', borderRadius: 50,
          background: 'linear-gradient(135deg,#F0D060,#D4AF37)', color: '#0A0A0A',
          fontFamily: 'var(--font-mono)', fontSize: 9.5, fontWeight: 700, letterSpacing: '.15em', textTransform: 'uppercase',
          boxShadow: '0 6px 16px rgba(212,175,55,.4)',
          whiteSpace: 'nowrap',
          zIndex: 3
        }}>{popularLabel}</div>
      )}

      {/* Card inner — clipped for sheen */}
      <div style={{
        position: 'relative',
        padding: '44px 28px 36px', borderRadius: 20,
        background: tr.popular
          ? 'linear-gradient(180deg, rgba(212,175,55,.08) 0%, rgba(212,175,55,.02) 60%, transparent 100%)'
          : 'rgba(212,175,55,.03)',
        border: tr.popular ? '1px solid rgba(212,175,55,.3)' : '1px solid rgba(212,175,55,.1)',
        boxShadow: tr.popular ? '0 24px 80px rgba(212,175,55,.1)' : 'none',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
        height: '100%'
      }}>
      {/* Sheen on hover */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'linear-gradient(110deg, transparent 40%, rgba(212,175,55,.12) 50%, transparent 60%)',
        transform: hover ? 'translateX(50%)' : 'translateX(-50%)',
        opacity: hover ? 1 : 0,
        transition: 'transform 1s cubic-bezier(.16,1,.3,1), opacity .4s'
      }}/>

      <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 600, marginBottom: 4 }}>{tr.name}</div>
      <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-3)', marginBottom: 28, letterSpacing: '.08em' }}>{tr.price}</div>

      <ul style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 32, flex: 1 }}>
        {tr.f.map(f => (
          <li key={f} style={{ display: 'flex', gap: 10, fontSize: 13, color: 'var(--text-2)', lineHeight: 1.5 }}>
            <span style={{
              flexShrink: 0, marginTop: 3,
              width: 14, height: 14, borderRadius: '50%',
              border: '1.5px solid rgba(212,175,55,.35)',
              display: 'flex', alignItems: 'center', justifyContent: 'center'
            }}>
              <svg width="7" height="5" viewBox="0 0 7 5" fill="none" stroke="var(--gold)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="1 2.5 2.8 4 6 1"/></svg>
            </span>
            {f}
          </li>
        ))}
      </ul>
      <button style={{
        width: '100%', padding: '13px 20px', borderRadius: 10,
        background: tr.popular ? 'linear-gradient(135deg,#F0D060,#D4AF37)' : 'transparent',
        color: tr.popular ? '#0A0A0A' : 'var(--text)',
        border: tr.popular ? 'none' : '1px solid rgba(212,175,55,.3)',
        fontFamily: 'var(--font-display)', fontSize: 13.5, fontWeight: 600, letterSpacing: '.01em',
        boxShadow: tr.popular ? '0 6px 20px rgba(212,175,55,.3)' : 'none',
        cursor: 'pointer'
      }}>{tr.cta}</button>
      </div>
    </div>
  );
}

window.Packages = Packages;
