// Services — Premium interactive showcase. Replaces boring 3-col card grid.
// Design: large feature card on the left locked to the currently-hovered service,
// with a vertical list of services on the right. Hover/click a service — the big card
// morphs to show that service's content with:
//  - huge outlined number that fades in
//  - animated metric counter (ticks up)
//  - service-specific mini visualization
//  - gold gradient sweep

const { useState: useSvcState, useEffect: useSvcEffect } = React;

function Services({ lang }) {
  const t = (de, pl) => lang === 'de' ? de : pl;

  const services = [
    {
      n: '01',
      title: t('Social Media Content', 'Treści Social Media'),
      d: t('Reels, TikToks und Shorts — professionell produziert für maximale Reichweite.', 'Reels, TikToki i Shorty — profesjonalnie produkowane dla maksymalnego zasięgu.'),
      metric: { value: 347, suffix: '%', label: t('Durchschnittliche Reichweitensteigerung', 'Średni wzrost zasięgu') },
      viz: 'content',
      tags: [t('Kurzvideo', 'Krótkie wideo'), 'Reels', 'TikTok', 'Shorts', t('Scripting', 'Skrypty')]
    },
    {
      n: '02',
      title: t('AI Automationen', 'Automatyzacje AI'),
      d: t('Wiederkehrende Prozesse automatisieren. Mehr Zeit für das, was zählt.', 'Automatyzujemy powtarzalne procesy. Więcej czasu na to, co ważne.'),
      metric: { value: 28, suffix: 'h', label: t('Gesparte Arbeitsstunden pro Woche', 'Zaoszczędzonych godzin tygodniowo') },
      viz: 'automation',
      tags: ['n8n', 'Make', 'Zapier', 'OpenAI', 'Claude', 'CRM']
    },
    {
      n: '03',
      title: t('Content Strategie', 'Strategia Treści'),
      d: t('Maßgeschneiderte Content-Pläne, die deine Marke nach vorne bringen.', 'Spersonalizowane plany treści, które rozwijają Twoją markę.'),
      metric: { value: 90, suffix: t(' Tage', ' dni'), label: t('Vollständiger Content-Fahrplan', 'Pełny plan treści') },
      viz: 'strategy',
      tags: [t('Recherche', 'Badania'), 'Positioning', 'Hooks', 'Pillars', 'Calendar']
    },
    {
      n: '04',
      title: t('Lead Generation', 'Generowanie Leadów'),
      d: t('Qualifizierte Anfragen direkt in dein Postfach — planbar und skalierbar.', 'Wykwalifikowane zapytania prosto do Twojej skrzynki — skalowalne.'),
      metric: { value: 12, suffix: 'x', label: t('ROI im ersten Quartal', 'ROI w pierwszym kwartale') },
      viz: 'leads',
      tags: ['Meta Ads', 'TikTok Ads', 'Funnels', 'Landing', 'CRM Sync']
    },
    {
      n: '05',
      title: t('Business Optimization', 'Optymalizacja Biznesu'),
      d: t('Prozesse analysieren, Engpässe lösen, Effizienz steigern.', 'Analizujemy procesy, usuwamy wąskie gardła, zwiększamy wydajność.'),
      metric: { value: 40, suffix: '%', label: t('Effizienzsteigerung im Schnitt', 'Średni wzrost wydajności') },
      viz: 'optimization',
      tags: [t('Audit', 'Audyt'), 'Workflow', 'Tools', 'SOPs', 'KPI']
    },
    {
      n: '06',
      title: t('Branding & Design', 'Branding i Design'),
      d: t('Einheitliches Erscheinungsbild, das Vertrauen schafft und verkauft.', 'Spójny wizerunek, który buduje zaufanie i sprzedaje.'),
      metric: { value: 3.2, suffix: 'x', decimals: 1, label: t('Höhere Conversion durch starke Marke', 'Wyższa konwersja dzięki silnej marce') },
      viz: 'branding',
      tags: ['Logo', t('Farbwelt', 'Paleta'), 'Typography', 'Guidelines', 'Assets']
    }
  ];

  const [active, setActive] = useSvcState(0);
  const current = services[active];
  const isMobile = window.useIsMobile ? window.useIsMobile() : false;
  const scrollerRef = React.useRef(null);

  // Sync active index from horizontal scroll position (mobile only)
  React.useEffect(() => {
    if (!isMobile) return;
    const el = scrollerRef.current;
    if (!el) return;
    let raf;
    const onScroll = () => {
      if (raf) return;
      raf = requestAnimationFrame(() => {
        raf = null;
        const cardW = el.clientWidth;
        const idx = Math.round(el.scrollLeft / cardW);
        setActive(prev => (prev !== idx && idx >= 0 && idx < services.length) ? idx : prev);
      });
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => { el.removeEventListener('scroll', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, [isMobile, services.length]);

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

  return (
    <section id="services" className="section" style={{ position: 'relative', overflow: 'hidden', padding: isMobile ? '80px 0' : '120px 0' }}>

      {/* Ambient gold glow — static, GPU-cheap */}
      <div style={{
        position: 'absolute',
        top: '40%',
        left: '12%',
        width: 480, height: 480,
        borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(212,175,55,.06) 0%, transparent 70%)',
        pointerEvents: 'none',
        zIndex: 0
      }}/>

      <div className="container" style={{ position: 'relative', zIndex: 1 }}>
        {/* Header with running ticker */}
        <div style={{ marginBottom: isMobile ? 40 : 72, display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: isMobile ? 20 : 40, flexWrap: 'wrap' }}>
          <div>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--gold)',
              letterSpacing: '.25em', textTransform: 'uppercase', marginBottom: 18,
              display: 'flex', alignItems: 'center', gap: 10
            }}>
              <span style={{ width: 24, height: 1, background: 'var(--gold)' }}/>
              {t('Leistungen', 'Usługi')}
              <span style={{ opacity: .4 }}>/ {String(active + 1).padStart(2, '0')}—{String(services.length).padStart(2, '0')}</span>
            </div>
            <h2 style={{
              fontFamily: 'var(--font-display)',
              fontSize: isMobile ? 'clamp(36px, 9vw, 48px)' : 72,
              lineHeight: 1.02,
              letterSpacing: '-0.035em', maxWidth: 900, fontWeight: 700, margin: 0
            }}>
              {t('Alles, was dein Business', 'Wszystko, czego potrzebuje')}<br/>
              <span style={{ color: 'var(--text-2)' }}>
                {t('zum ', 'Twój biznes, aby ')}
              </span>
              <span style={{
                background: 'linear-gradient(90deg, #F4CF5B, #D4AF37)',
                WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', backgroundClip: 'text',
                fontStyle: 'italic', fontFamily: 'var(--font-body)', fontWeight: 400
              }}>
                {t('Wachsen', 'rosnąć')}
              </span>
              <span style={{ color: 'var(--text-2)' }}>{t(' braucht.', '.')}</span>
            </h2>
          </div>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-2)',
            letterSpacing: '.1em', display: 'flex', alignItems: 'center', gap: 8,
            padding: '10px 16px',
            border: '1px solid rgba(212,175,55,.15)', borderRadius: 50,
            background: 'rgba(212,175,55,.03)'
          }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%', background: '#4ade80',
              boxShadow: '0 0 10px rgba(74,222,128,.7)',
              animation: 'pulseDot 1.6s ease-in-out infinite'
            }}/>
            {t('Alle Dienste live', 'Wszystkie usługi aktywne')}
          </div>
        </div>

        {/* MOBILE: horizontal snap-carousel — each service is a self-contained card */}
        {isMobile && (
          <div>
            {/* Pagination dots */}
            <div style={{
              display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 18
            }}>
              {services.map((s, i) => (
                <button key={s.n}
                  onClick={() => scrollToCard(i)}
                  aria-label={`Go to ${s.title}`}
                  style={{
                    width: i === active ? 28 : 8, height: 8, borderRadius: 50,
                    background: i === active ? 'var(--gold)' : 'rgba(212,175,55,.2)',
                    border: 'none', padding: 0, cursor: 'pointer',
                    transition: 'all .35s cubic-bezier(.2,.9,.3,1)',
                    boxShadow: i === active ? '0 0 12px rgba(212,175,55,.5)' : 'none'
                  }}/>
              ))}
            </div>

            {/* Snap scroller */}
            <div
              ref={scrollerRef}
              style={{
                display: 'flex',
                overflowX: 'auto',
                scrollSnapType: 'x mandatory',
                scrollBehavior: 'smooth',
                gap: 0,
                margin: '0 -20px',
                padding: '0 20px',
                WebkitOverflowScrolling: 'touch',
                scrollbarWidth: 'none'
              }}
              className="svc-mobile-scroller"
            >
              {services.map((s, i) => (
                <div key={s.n} style={{
                  flex: '0 0 100%',
                  scrollSnapAlign: 'center',
                  scrollSnapStop: 'always',
                  paddingRight: i === services.length - 1 ? 0 : 14
                }}>
                  <div style={{
                    position: 'relative',
                    borderRadius: 22,
                    overflow: 'hidden',
                    background: 'linear-gradient(135deg, rgba(30,25,10,.6) 0%, rgba(15,12,8,.9) 100%)',
                    border: '1px solid rgba(212,175,55,.18)',
                    padding: 22,
                    display: 'flex', flexDirection: 'column', gap: 18,
                    minHeight: 540
                  }}>
                    {/* Animated rim */}
                    <div style={{
                      position: 'absolute', inset: -1, borderRadius: 22, padding: 1,
                      background: 'conic-gradient(from 0deg at 50% 50%, transparent 0%, rgba(212,175,55,.4) 25%, transparent 50%, rgba(212,175,55,.3) 75%, transparent 100%)',
                      WebkitMask: 'linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)',
                      WebkitMaskComposite: 'xor', maskComposite: 'exclude',
                      animation: i === active ? 'svcRim 8s linear infinite' : 'none',
                      pointerEvents: 'none', zIndex: 1
                    }}/>

                    {/* Outlined number watermark */}
                    <div style={{
                      position: 'absolute', top: 4, right: 8,
                      fontFamily: 'var(--font-display)', fontWeight: 700,
                      fontSize: 160, lineHeight: .85, letterSpacing: '-0.05em',
                      color: 'transparent',
                      WebkitTextStroke: '1.5px rgba(212,175,55,.14)',
                      pointerEvents: 'none'
                    }}>{s.n}</div>

                    {/* Viz */}
                    <div style={{
                      position: 'relative', zIndex: 2,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      minHeight: 180
                    }}>
                      <ServiceViz kind={s.viz}/>
                    </div>

                    {/* Metric */}
                    <div style={{
                      position: 'relative', zIndex: 2,
                      padding: '14px 16px', borderRadius: 14,
                      background: 'linear-gradient(135deg, rgba(212,175,55,.14), rgba(212,175,55,.03))',
                      border: '1px solid rgba(212,175,55,.22)'
                    }}>
                      <div style={{
                        fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '.25em',
                        color: 'var(--gold)', textTransform: 'uppercase', marginBottom: 6
                      }}>
                        {t('Im Schnitt', 'Średnio')}
                      </div>
                      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
                        {i === active ? (
                          <MetricCounter
                            key={`mm-${i}-${active}`}
                            target={s.metric.value}
                            decimals={s.metric.decimals || 0}
                            size={42}
                          />
                        ) : (
                          <span style={{
                            fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 42,
                            color: 'var(--gold)', letterSpacing: '-0.04em', lineHeight: 1,
                            fontVariantNumeric: 'tabular-nums'
                          }}>{(s.metric.value).toFixed(s.metric.decimals || 0)}</span>
                        )}
                        <span style={{
                          fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 26,
                          color: 'var(--gold)', letterSpacing: '-0.02em'
                        }}>{s.metric.suffix}</span>
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--text-2)', marginTop: 4 }}>{s.metric.label}</div>
                    </div>

                    {/* Content */}
                    <div style={{ position: 'relative', zIndex: 2 }}>
                      <div style={{
                        fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '.3em',
                        color: 'var(--gold)', marginBottom: 10, textTransform: 'uppercase'
                      }}>
                        {s.n} / {t('Leistung', 'Usługa')}
                      </div>
                      <h3 style={{
                        fontFamily: 'var(--font-display)', fontSize: 24, fontWeight: 700,
                        letterSpacing: '-0.02em', lineHeight: 1.05, marginBottom: 10
                      }}>{s.title}</h3>
                      <p style={{
                        fontSize: 13, color: 'var(--text-2)', lineHeight: 1.6, marginBottom: 14
                      }}>{s.d}</p>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                        {s.tags.map(tag => (
                          <span key={tag} style={{
                            padding: '5px 10px', borderRadius: 50,
                            fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '.12em',
                            color: 'var(--text-2)', textTransform: 'uppercase',
                            border: '1px solid rgba(212,175,55,.14)',
                            background: 'rgba(212,175,55,.03)'
                          }}>{tag}</span>
                        ))}
                      </div>
                    </div>
                  </div>
                </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>
        )}

        {/* DESKTOP: 2-col feature panel + service list (unchanged) */}
        {!isMobile && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: '1.35fr 1fr',
          gap: 28
        }}>

          {/* LEFT: big cinematic feature card */}
          <div style={{
            position: 'relative',
            borderRadius: isMobile ? 22 : 28,
            overflow: 'hidden',
            background: 'linear-gradient(135deg, rgba(30,25,10,.6) 0%, rgba(15,12,8,.9) 100%)',
            border: '1px solid rgba(212,175,55,.15)',
            minHeight: isMobile ? 440 : 560,
            padding: isMobile ? 24 : 48,
            display: 'flex', flexDirection: 'column', justifyContent: 'space-between'
          }}>
            {/* Animated gradient rim */}
            <div style={{
              position: 'absolute', inset: -1, borderRadius: isMobile ? 22 : 28, padding: 1,
              background: 'conic-gradient(from 0deg at 50% 50%, transparent 0%, rgba(212,175,55,.4) 25%, transparent 50%, rgba(212,175,55,.3) 75%, transparent 100%)',
              WebkitMask: 'linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0)',
              WebkitMaskComposite: 'xor', maskComposite: 'exclude',
              animation: 'svcRim 8s linear infinite',
              pointerEvents: 'none', zIndex: 1
            }}/>

            {/* Huge outlined number */}
            <div key={`n-${active}`} style={{
              position: 'absolute', top: isMobile ? 8 : 20, right: isMobile ? 12 : 30,
              fontFamily: 'var(--font-display)', fontWeight: 700,
              fontSize: isMobile ? 180 : 360, lineHeight: .85, letterSpacing: '-0.05em',
              color: 'transparent',
              WebkitTextStroke: '1.5px rgba(212,175,55,.14)',
              pointerEvents: 'none',
              animation: 'svcNumFade .6s cubic-bezier(.2,.9,.3,1)'
            }}>{current.n}</div>

            {/* Service viz */}
            <div style={{ position: 'relative', zIndex: 2, flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: isMobile ? '0' : '0 -24px' }}>
              <ServiceViz kind={current.viz}/>
            </div>

            {/* Content */}
            <div style={{ position: 'relative', zIndex: 2 }}>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.3em',
                color: 'var(--gold)', marginBottom: 14, textTransform: 'uppercase'
              }}>
                {current.n} / {t('Leistung', 'Usługa')}
              </div>
              <h3 key={`title-${active}`} style={{
                fontFamily: 'var(--font-display)', fontSize: isMobile ? 28 : 44, fontWeight: 700,
                letterSpacing: '-0.02em', lineHeight: 1.05, marginBottom: 16,
                animation: 'svcTextIn .5s cubic-bezier(.2,.9,.3,1)'
              }}>{current.title}</h3>
              <p key={`desc-${active}`} style={{
                fontSize: isMobile ? 14 : 16, color: 'var(--text-2)', lineHeight: 1.65, maxWidth: 500, marginBottom: 24,
                animation: 'svcTextIn .5s .08s cubic-bezier(.2,.9,.3,1) backwards'
              }}>{current.d}</p>

              {/* Tags */}
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {current.tags.map((tag, i) => (
                  <span key={`${active}-${tag}`} style={{
                    padding: '6px 12px', borderRadius: 50,
                    fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.12em',
                    color: 'var(--text-2)', textTransform: 'uppercase',
                    border: '1px solid rgba(212,175,55,.14)',
                    background: 'rgba(212,175,55,.03)',
                    animation: `svcTextIn .5s ${0.15 + i*0.04}s cubic-bezier(.2,.9,.3,1) backwards`
                  }}>{tag}</span>
                ))}
              </div>
            </div>
          </div>

          {/* RIGHT: service list with live metric */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {/* Metric readout */}
            <div style={{
              padding: isMobile ? '18px 20px' : '24px 28px', borderRadius: 20,
              background: 'linear-gradient(135deg, rgba(212,175,55,.14), rgba(212,175,55,.03))',
              border: '1px solid rgba(212,175,55,.22)',
              marginBottom: 12
            }}>
              <div style={{
                fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '.25em',
                color: 'var(--gold)', textTransform: 'uppercase', marginBottom: 10
              }}>
                {t('Im Schnitt erreichen wir', 'Średnio osiągamy')}
              </div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginBottom: 8 }}>
                <MetricCounter
                  key={`m-${active}`}
                  target={current.metric.value}
                  decimals={current.metric.decimals || 0}
                  size={isMobile ? 54 : 72}
                />
                <span style={{
                  fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: isMobile ? 32 : 44,
                  color: 'var(--gold)', letterSpacing: '-0.02em'
                }}>{current.metric.suffix}</span>
              </div>
              <div style={{ fontSize: isMobile ? 12 : 13, color: 'var(--text-2)' }}>{current.metric.label}</div>
            </div>

            {/* Service list */}
            {services.map((s, i) => {
              const isActive = i === active;
              return (
                <button key={s.n}
                  onClick={() => setActive(i)}
                  onFocus={() => setActive(i)}
                  style={{
                    display: 'flex', alignItems: 'center', gap: isMobile ? 12 : 18,
                    padding: isMobile ? '14px 16px' : '18px 24px', borderRadius: 16,
                    background: isActive ? 'rgba(212,175,55,.09)' : 'transparent',
                    border: `1px solid ${isActive ? 'rgba(212,175,55,.3)' : 'rgba(212,175,55,.08)'}`,
                    cursor: 'pointer',
                    transition: 'all .35s cubic-bezier(.16,1,.3,1)',
                    textAlign: 'left',
                    color: 'inherit',
                    position: 'relative',
                    overflow: 'hidden'
                  }}>
                  {/* Gold accent line — fills on active */}
                  <div style={{
                    position: 'absolute', left: 0, top: 0, bottom: 0,
                    width: 2, background: 'var(--gold)',
                    transform: `scaleY(${isActive ? 1 : 0})`,
                    transformOrigin: 'center',
                    transition: 'transform .4s cubic-bezier(.2,.9,.3,1)'
                  }}/>
                  <span style={{
                    fontFamily: 'var(--font-mono)', fontSize: 11,
                    color: isActive ? 'var(--gold)' : 'var(--text-3)',
                    letterSpacing: '.2em',
                    transition: 'color .3s',
                    minWidth: 22
                  }}>{s.n}</span>
                  <span style={{
                    flex: 1,
                    fontFamily: 'var(--font-display)', fontSize: isMobile ? 16 : 19, fontWeight: 600,
                    letterSpacing: '-0.005em',
                    color: isActive ? '#fff' : 'var(--text-2)',
                    transition: 'color .3s'
                  }}>{s.title}</span>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none"
                    stroke={isActive ? 'var(--gold)' : 'rgba(255,255,255,.3)'}
                    strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round"
                    style={{
                      transform: `translateX(${isActive ? 0 : -6}px)`,
                      opacity: isActive ? 1 : .5,
                      transition: 'all .3s cubic-bezier(.2,.9,.3,1)'
                    }}>
                    <path d="M5 12h14"/><path d="m12 5 7 7-7 7"/>
                  </svg>
                </button>
              );
            })}
          </div>
        </div>
        )}
      </div>

      <style>{`
        .svc-mobile-scroller::-webkit-scrollbar { display: none; }
        @keyframes pulseDot { 0%,100% { opacity: 1; } 50% { opacity: .5; } }
        @keyframes svcRim { to { transform: rotate(360deg); } }
        @keyframes svcNumFade {
          from { opacity: 0; transform: translateY(20px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes svcTextIn {
          from { opacity: 0; transform: translateY(12px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes vizContentLine {
          0% { transform: translateX(-100%); }
          100% { transform: translateX(100%); }
        }
        @keyframes phoneTrioEntrance {
          from { opacity: 0; transform: translateY(60px) scale(0.85) rotate(calc(var(--phone-rot, 0deg) + 18deg)); }
          to   { opacity: 1; transform: translateY(0) scale(1) rotate(var(--phone-rot, 0deg)); }
        }
        @keyframes phoneTrioFloat {
          0%, 100% { transform: translateY(0) rotate(var(--phone-rot, 0deg)); }
          50%      { transform: translateY(-6px) rotate(var(--phone-rot, 0deg)); }
        }
        @keyframes phoneTrioRim {
          0%, 100% { box-shadow: 0 18px 40px rgba(0,0,0,.5), 0 0 0 1px rgba(212,175,55,.25); }
          50%      { box-shadow: 0 18px 40px rgba(0,0,0,.5), 0 0 0 1px rgba(212,175,55,.55), 0 0 24px rgba(212,175,55,.15); }
        }
      `}</style>
    </section>
  );
}

// Animated counter: ticks up to target
function MetricCounter({ target, decimals = 0, size = 72 }) {
  const [val, setVal] = useSvcState(0);
  useSvcEffect(() => {
    const start = performance.now();
    const dur = 800;
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setVal(target * eased);
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target]);
  return (
    <span style={{
      fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: size,
      color: 'var(--gold)', letterSpacing: '-0.04em', lineHeight: 1,
      fontVariantNumeric: 'tabular-nums'
    }}>
      {val.toFixed(decimals)}
    </span>
  );
}

// Phone-trio with real videos, IntersectionObserver entrance + hover focus
function PhoneTrio() {
  const [hovered, setHovered] = React.useState(null);
  const [entered, setEntered] = React.useState(false);
  const phoneRef = React.useRef(null);
  const isMobile = (typeof window !== 'undefined' && window.useIsMobile) ? window.useIsMobile() : false;

  React.useEffect(() => {
    if (!phoneRef.current) return;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) { setEntered(true); obs.disconnect(); }
    }, { threshold: 0.2 });
    obs.observe(phoneRef.current);
    return () => obs.disconnect();
  }, []);

  const phoneVideos = [
    { src: 'assets/phone-1-lambo.mp4',     poster: 'assets/phone-1-lambo.jpg',     likes: '124K' },
    { src: 'assets/phone-2-saaler.mp4',    poster: 'assets/phone-2-saaler.jpg',    likes: '892K' },
    { src: 'assets/phone-3-speedramp.mp4', poster: 'assets/phone-3-speedramp.jpg', likes: '2.4M' },
  ];

  const phoneW = isMobile ? 100 : 150;
  const phoneH = isMobile ? 178 : 266;
  const fontSize = isMobile ? 9 : 11;

  return (
    <div ref={phoneRef} style={{
      width: '100%',
      maxWidth: isMobile ? 360 : 600,
      height: isMobile ? 260 : 340,
      position: 'relative',
      margin: '0 auto',
    }}>
      {phoneVideos.map((v, i) => {
        const baseRot = -6 + i*4;
        const isHovered = hovered === i;
        const isOther = hovered !== null && hovered !== i;
        return (
          <div
            key={i}
            onMouseEnter={() => setHovered(i)}
            onMouseLeave={() => setHovered(null)}
            style={{
              position: 'absolute',
              left: `${4 + i*30}%`, top: `${2 + i*9}%`,
              width: phoneW, height: phoneH,
              borderRadius: 18,
              overflow: 'hidden',
              background: '#0A0A0A',
              border: '2px solid rgba(212,175,55,.35)',
              '--phone-rot': `${baseRot}deg`,
              transform: `rotate(${isHovered ? 0 : baseRot}deg) scale(${isHovered ? 1.1 : isOther ? 0.94 : 1})`,
              opacity: !entered ? 0 : isOther ? 0.5 : 1,
              zIndex: isHovered ? 10 : 1,
              animation: entered
                ? `phoneTrioEntrance .9s cubic-bezier(.16,1,.3,1) ${i*200}ms both, phoneTrioFloat 4s ease-in-out ${i*1300 + 1100}ms infinite, phoneTrioRim 3.5s ease-in-out ${i*800}ms infinite`
                : 'none',
              transition: 'transform .45s cubic-bezier(.16,1,.3,1), opacity .35s ease',
              cursor: 'pointer',
              willChange: 'transform, opacity',
            }}
          >
            <video
              src={v.src}
              poster={v.poster}
              muted
              playsInline
              loop
              autoPlay
              preload="metadata"
              style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}
            />
            <div style={{
              position: 'absolute', bottom: 10, left: 10, right: 10,
              fontFamily: 'var(--font-mono)', fontSize,
              color: '#fff', textShadow: '0 1px 4px rgba(0,0,0,.9)',
              letterSpacing: '.05em',
              pointerEvents: 'none',
              lineHeight: 1.3,
            }}>
              <div style={{ fontWeight: 700 }}>@jk_media</div>
              <div style={{ opacity: .85, marginTop: 1 }}>{v.likes} ♥</div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// Per-service visualization — distinct for each
function ServiceViz({ kind }) {
  const base = { width: '100%', maxWidth: 480, height: 240, position: 'relative' };
  if (kind === 'content') {
    return (
      <div style={base}>
        <PhoneTrio />
      </div>
    );
  }
  if (kind === 'automation') {
    // Flowing nodes connected by animated lines
    return (
      <svg viewBox="0 0 480 240" style={{ width: '100%', maxWidth: 480, height: 240 }}>
        <defs>
          <linearGradient id="flowGrad" x1="0" x2="1">
            <stop offset="0" stopColor="transparent"/>
            <stop offset=".5" stopColor="#D4AF37"/>
            <stop offset="1" stopColor="transparent"/>
          </linearGradient>
        </defs>
        {[[80,80],[200,60],[320,100],[400,180],[240,180]].map(([x,y],i) => (
          <g key={i}>
            <circle cx={x} cy={y} r="28" fill="rgba(212,175,55,.08)" stroke="rgba(212,175,55,.4)" strokeWidth="1"/>
            <circle cx={x} cy={y} r="6" fill="#D4AF37"/>
          </g>
        ))}
        {[[80,80,200,60],[200,60,320,100],[320,100,400,180],[200,60,240,180],[240,180,320,100]].map(([x1,y1,x2,y2],i) => (
          <g key={i}>
            <line x1={x1} y1={y1} x2={x2} y2={y2} stroke="rgba(212,175,55,.25)" strokeWidth="1.5"/>
            <circle r="4" fill="#D4AF37">
              <animateMotion dur={`${2 + i*0.4}s`} repeatCount="indefinite" path={`M${x1},${y1} L${x2},${y2}`}/>
            </circle>
          </g>
        ))}
      </svg>
    );
  }
  if (kind === 'strategy') {
    // Calendar grid of 90 days, some highlighted
    return (
      <div style={{ ...base, display: 'grid', gridTemplateColumns: 'repeat(15,1fr)', gap: 6, padding: 12 }}>
        {[...Array(90)].map((_,i) => {
          const active = [3,4,8,12,13,18,23,27,28,32,37,41,42,47,52,56,57,61,66,70,71,75,80,84,85,88].includes(i);
          return (
            <div key={i} style={{
              aspectRatio: '1',
              borderRadius: 3,
              background: active ? 'var(--gold)' : 'rgba(212,175,55,.1)',
              boxShadow: active ? '0 0 8px rgba(212,175,55,.5)' : 'none',
              animation: active ? `stratPulse 3s ${i*0.05}s ease-in-out infinite` : 'none'
            }}/>
          );
        })}
        <style>{`@keyframes stratPulse { 0%,100% { opacity: 1; } 50% { opacity: .5; } }`}</style>
      </div>
    );
  }
  if (kind === 'leads') {
    // Funnel with qualified leads dropping into inbox
    return (
      <svg viewBox="0 0 480 240" style={{ width: '100%', maxWidth: 480, height: 240 }}>
        <defs>
          <linearGradient id="funnelGrad" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0" stopColor="rgba(212,175,55,.3)"/>
            <stop offset="1" stopColor="rgba(212,175,55,.05)"/>
          </linearGradient>
        </defs>
        <path d="M80,40 L400,40 L320,140 L240,200 L160,140 Z" fill="url(#funnelGrad)" stroke="rgba(212,175,55,.4)" strokeWidth="1.5"/>
        {[50,110,170,230,290,350].map((x, i) => (
          <circle key={i} cx={x} cy="20" r="4" fill="#D4AF37">
            <animate attributeName="cy" values="20;220" dur={`${2+i*0.3}s`} begin={`${i*0.3}s`} repeatCount="indefinite"/>
            <animate attributeName="opacity" values="1;1;0" dur={`${2+i*0.3}s`} begin={`${i*0.3}s`} repeatCount="indefinite"/>
          </circle>
        ))}
        <rect x="200" y="210" width="80" height="20" rx="3" fill="rgba(212,175,55,.15)" stroke="var(--gold)" strokeWidth="1"/>
        <text x="240" y="223" textAnchor="middle" fontFamily="ui-monospace,monospace" fontSize="9" fill="#D4AF37" letterSpacing="1.5">INBOX</text>
      </svg>
    );
  }
  if (kind === 'optimization') {
    // Before/after bar chart
    return (
      <div style={{ ...base, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: 24, paddingBottom: 24 }}>
        {[[30,'Vorher','Przed'],[52,'Vorher','Przed'],[38,'Vorher','Przed'],[60,'Vorher','Przed']].map(([h, de],i)=>(
          <div key={`a${i}`} style={{ display: 'flex', gap: 8, alignItems: 'flex-end' }}>
            <div style={{
              width: 22, height: `${h}%`,
              background: 'rgba(255,255,255,.1)',
              borderRadius: '4px 4px 0 0',
              animation: `barGrow${i} 1.2s ease-out`
            }}/>
            <div style={{
              width: 22, height: `${h+30}%`,
              background: 'linear-gradient(180deg, #F4CF5B, #D4AF37)',
              borderRadius: '4px 4px 0 0',
              boxShadow: '0 0 20px rgba(212,175,55,.4)',
              animation: `barGrow${i+4} 1.2s ${0.15+i*0.1}s ease-out backwards`
            }}/>
          </div>
        ))}
        <style>{`
          ${[0,1,2,3,4,5,6,7].map(i => `@keyframes barGrow${i} { from { height: 0; } }`).join('\n')}
        `}</style>
      </div>
    );
  }
  if (kind === 'branding') {
    // Color swatches + logo mark
    return (
      <div style={{ ...base, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 20 }}>
        <div style={{
          width: 120, height: 120, borderRadius: 20,
          background: 'radial-gradient(circle at 30% 30%, #F4CF5B, #D4AF37 40%, #8a6f1a 100%)',
          boxShadow: '0 20px 50px rgba(212,175,55,.35), inset 0 2px 0 rgba(255,255,255,.3)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontSize: 48, fontWeight: 800, color: '#1a1410',
          transform: 'rotate(-6deg)'
        }}>JK</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {['#D4AF37','#0a0a0a','#ffffff','#1a1a1a'].map(c => (
            <div key={c} style={{
              display: 'flex', alignItems: 'center', gap: 10
            }}>
              <div style={{
                width: 48, height: 48, borderRadius: 10, background: c,
                border: '1px solid rgba(212,175,55,.2)',
                boxShadow: '0 4px 12px rgba(0,0,0,.4)'
              }}/>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-2)', letterSpacing: '.1em' }}>{c.toUpperCase()}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return null;
}

window.Services = Services;
