/* global React */
const { useState, useRef, useEffect } = React;

// Reuse color tokens already defined in components.jsx (C) by grabbing from window,
// but it's a local const there — so we redeclare a mirror for home-only sections.
const HC = {
  bg: 'rgb(6,11,24)',
  bgDeep: 'rgb(21,19,49)',
  gold: '#E6C79C',
  goldDark: '#9E7B4B',
  lavender: 'rgb(186,171,212)',
  muted: 'rgb(78,70,114)',
  peach: 'rgb(255,180,111)',
  white: 'rgb(255,255,255)',
  violet: 'rgba(59,39,172,0.5)'
};

// ────────── HOME HERO ──────────
function HomeStars() {
  // Sparse, gently blinking stars layered over the hero night sky only.
  const stars = [
  // Top band
  { top: '4%', left: '6%', size: 2, dur: 4.5, delay: 0, bright: 1.0 },
  { top: '5%', left: '24%', size: 2, dur: 5, delay: 2.7, bright: 0.9 },
  { top: '6%', left: '46%', size: 3, dur: 4, delay: 5.1, bright: 1.0 },
  { top: '4%', left: '64%', size: 2, dur: 5.5, delay: 1.4, bright: 0.95 },
  { top: '7%', left: '78%', size: 3, dur: 5, delay: 3.9, bright: 1.0 },
  { top: '5%', left: '94%', size: 2, dur: 4.5, delay: 6.3, bright: 1.0 },
  { top: '12%', left: '14%', size: 2, dur: 5, delay: 0.8, bright: 0.95 },
  { top: '13%', left: '36%', size: 2, dur: 4, delay: 4.5, bright: 1.0 },
  { top: '14%', left: '54%', size: 3, dur: 5.5, delay: 2.1, bright: 1.0 },
  { top: '12%', left: '72%', size: 2, dur: 4.5, delay: 6.8, bright: 0.9 },
  { top: '15%', left: '88%', size: 2, dur: 5, delay: 1.7, bright: 0.95 },
  { top: '20%', left: '4%', size: 2, dur: 5, delay: 5.4, bright: 0.95 },
  { top: '21%', left: '28%', size: 3, dur: 4.5, delay: 3.2, bright: 1.0 },
  { top: '22%', left: '50%', size: 2, dur: 5.5, delay: 0.4, bright: 0.9 },
  { top: '21%', left: '68%', size: 2, dur: 4, delay: 4.9, bright: 1.0 },
  { top: '23%', left: '84%', size: 2, dur: 5, delay: 2.5, bright: 0.95 },
  // Middle band
  { top: '30%', left: '10%', size: 3, dur: 4.5, delay: 6.1, bright: 1.0 },
  { top: '32%', left: '32%', size: 2, dur: 5, delay: 1, bright: 0.9 },
  { top: '31%', left: '52%', size: 2, dur: 5.5, delay: 3.6, bright: 0.95 },
  { top: '33%', left: '74%', size: 2, dur: 4.5, delay: 5.7, bright: 1.0 },
  { top: '34%', left: '92%', size: 2, dur: 5, delay: 2.3, bright: 0.9 },
  { top: '40%', left: '6%', size: 2, dur: 4.5, delay: 4.2, bright: 0.9 },
  { top: '42%', left: '26%', size: 3, dur: 5, delay: 0.6, bright: 1.0 },
  { top: '41%', left: '60%', size: 2, dur: 4, delay: 5.9, bright: 0.95 },
  { top: '43%', left: '82%', size: 2, dur: 5.5, delay: 3, bright: 0.9 },
  { top: '50%', left: '16%', size: 2, dur: 5, delay: 1.8, bright: 0.95 },
  { top: '52%', left: '40%', size: 3, dur: 5.5, delay: 6.5, bright: 1.0 },
  { top: '51%', left: '66%', size: 2, dur: 4.5, delay: 4.7, bright: 0.95 },
  { top: '53%', left: '90%', size: 2, dur: 5, delay: 0.2, bright: 0.9 },
  // Lower band
  { top: '60%', left: '8%', size: 2, dur: 4.5, delay: 5.3, bright: 0.95 },
  { top: '62%', left: '30%', size: 2, dur: 5, delay: 2.9, bright: 0.9 },
  { top: '61%', left: '54%', size: 3, dur: 5.5, delay: 6.7, bright: 1.0 },
  { top: '63%', left: '78%', size: 2, dur: 5, delay: 1.2, bright: 0.95 },
  { top: '70%', left: '14%', size: 3, dur: 4.5, delay: 3.8, bright: 1.0 },
  { top: '72%', left: '42%', size: 2, dur: 5, delay: 5, bright: 0.95 },
  { top: '71%', left: '68%', size: 2, dur: 5.5, delay: 2.6, bright: 0.9 },
  { top: '73%', left: '94%', size: 2, dur: 4.5, delay: 4.4, bright: 0.95 },
  { top: '80%', left: '4%', size: 2, dur: 5, delay: 0.9, bright: 0.9 },
  { top: '82%', left: '36%', size: 3, dur: 4.5, delay: 6.2, bright: 1.0 },
  { top: '81%', left: '60%', size: 2, dur: 5.5, delay: 3.4, bright: 0.95 },
  { top: '83%', left: '86%', size: 2, dur: 5, delay: 5.6, bright: 0.9 },
  { top: '90%', left: '20%', size: 2, dur: 4.5, delay: 1.5, bright: 0.95 },
  { top: '92%', left: '50%', size: 2, dur: 5, delay: 4.1, bright: 1.0 },
  { top: '91%', left: '74%', size: 3, dur: 5.5, delay: 0, bright: 1.0 }];

  const starColor = 'rgb(240, 245, 255)';
  const glowColor = 'rgba(200, 215, 255, 0.85)';
  return (
    <div aria-hidden style={{
      position: 'absolute', inset: 0,
      pointerEvents: 'none', zIndex: 1, overflow: 'hidden'
    }}>
      {stars.map((s, i) =>
      <span key={i} className="luna-star" style={{
        top: s.top, left: s.left,
        width: s.size, height: s.size,
        background: starColor,
        animationDuration: `${s.dur}s`,
        animationDelay: `${s.delay}s`,
        boxShadow: `0 0 ${s.size * 3}px rgba(240, 245, 255, ${s.bright}), 0 0 ${s.size * 6}px ${glowColor}`
      }} />
      )}
    </div>);
}

function HomeHero() {
  useHomeData(); // re-render on luna-home-loaded
  return (
    <section style={{
      position: 'relative', height: 1000, paddingTop: 84,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      overflow: 'hidden'
    }}>
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: `url(assets/hero-bg.png)`,
        backgroundSize: 'cover', backgroundPosition: 'center',
        opacity: 0,
        animation: 'heroFadeIn 1.6s ease-out 0.1s forwards'
      }} />
      <HomeStars />
      <div style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(${HC.bg} 0%, rgba(6,11,24,0) 18%, rgba(6,11,24,0) 82%, ${HC.bg} 100%)`
      }} />

      <div style={{
        position: 'relative', zIndex: 2, maxWidth: 1100,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 24,
        textAlign: 'center', padding: "40px 40px 0px"
      }}>
        <img src="assets/logo.png" alt="" style={{ width: 64, height: 80, objectFit: 'contain', marginBottom: 12 }} />
        <h1 style={{
          margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 72,
          lineHeight: 1.15, letterSpacing: '-0.022em', color: HC.white,
          textWrap: 'balance'
        }}>{homeText('hero.title', 'Odkryj swoją Lunarną Tożsamość')}</h1>
        <p style={{
          margin: '12px 0 0', maxWidth: 760,
          fontFamily: 'Nunito', fontSize: 18, lineHeight: 1.6,
          color: HC.lavender
        }}>{homeText('hero.subtitle', 'Pomagamy Ci ją zrozumieć i świadomie z niej korzystać')}</p>
        <div style={{ display: 'flex', gap: 36, marginTop: 24 }}>
          <BtnMain href={homeText('hero.btn_primary_href', '#eksperci')}>{homeText('hero.btn_primary_label', 'Znajdź eksperta')}</BtnMain>
          <BtnSecond href={homeText('hero.btn_secondary_href', '#uslugi')}>{homeText('hero.btn_secondary_label', 'Zobacz usługi')}</BtnSecond>
        </div>
      </div>
    </section>);

}

// ────────── DYSCYPLINY (5 cards horizontal scroll) ──────────
const DISCIPLINES = [
{
  tag: 'TAROT',
  slug: 'tarot',
  title: 'Większa jasność w ważnych momentach',
  body: 'Tarot to narzędzie refleksji, które pomaga spojrzeć na sytuację z większą jasnością. Pozwala dostrzec zależności, zrozumieć kontekst i lepiej przygotować się do podjęcia decyzji.',
  glyph: '✧'
},
{
  tag: 'NUMEROLOGIA',
  slug: 'numerologia',
  title: 'Liczby jako język zrozumienia Twojej drogi',
  body: 'Numerologia pomaga dostrzec zależności między wydarzeniami i lepiej zrozumieć swoją sytuację. Wspiera spokojne i świadome podejmowanie decyzji.',
  glyph: '✦'
},
{
  tag: 'ASTROLOGIA',
  slug: 'astrologia',
  title: 'Zrozum swój cykl życia i kierunek działania',
  body: 'Astrologia pomaga lepiej zrozumieć Twoje predyspozycje, moment życiowy i nadchodzące etapy. Wspiera podejmowanie decyzji oraz świadome planowanie kolejnych kroków.',
  glyph: '☿',
  featured: true
},
{
  tag: 'RUNY',
  slug: 'runy',
  title: 'Symbolika, która wspiera Twoje intencje',
  body: 'Runy pomagają pracować z konkretnym tematem lub celem. Wspierają proces zmiany, wzmacniają kierunek działania i pomagają utrzymać uwagę na tym, co dla Ciebie ważne.',
  glyph: 'ᚱ'
},
{
  tag: 'CHIROLOGIA',
  slug: 'chirologia',
  title: 'Poznaj swój potencjał i zrozum swoją naturę',
  body: 'Analiza dłoni pozwala lepiej zrozumieć Twoje cechy, sposób działania i naturalne kierunki rozwoju. Pomaga uporządkować doświadczenia i spojrzeć na swoją drogę z większą jasnością.',
  glyph: '✋'
},
{
  tag: 'ENERGIA',
  slug: 'energia',
  title: 'Praca z polem energetycznym i sygnałami z ciała',
  body: 'Energia to obszar, który łączy intuicję, ciało i emocje. Pomaga zauważyć, co realnie wpływa na Twoje samopoczucie i decyzje, oraz wzmocnić to, co Cię prowadzi.',
  glyph: '✦'
}];


function DisciplineCard({ d, width }) {
  const w = width || 555;
  return (
    <div style={{
      width: w, minWidth: w, height: 640,
      borderRadius: 16, border: '1px solid rgb(78, 70, 114)',
      background: 'rgba(21,19,49,0.25)',
      padding: 28, display: 'flex', flexDirection: 'column', gap: 18,
      alignItems: 'center', boxSizing: 'border-box',
      transition: 'transform .35s, border-color .35s, box-shadow .35s', transform: "none", boxShadow: "none"
    }}>
      {/* Illustration zone — discipline-specific mandala */}
      <DisciplineIllustration tag={d.tag} size={280} />
      <h3 style={{
        margin: 0, fontFamily: 'Playfair Display', fontSize: 40,
        textAlign: 'center', letterSpacing: '-0.022em', color: HC.gold, fontWeight: "400"
      }}>{d.tag}</h3>
      <div style={{
        fontFamily: 'Nunito', fontSize: 18,
        textAlign: 'center', color: HC.white, lineHeight: 1.5, fontWeight: "400"
      }}>{d.title}</div>
      <p style={{
        margin: 0, fontFamily: 'Nunito', fontSize: 16, lineHeight: 1.5,
        textAlign: 'center', color: HC.lavender
      }}>{d.body}</p>
      <BtnSecond small href={d.slug ? d.slug + '.html' : typeof discHref === 'function' ? discHref(d.tag) : '#'}>Zobacz więcej</BtnSecond>
    </div>);

}

function Dyscypliny() {
  const [vw, setVw] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth : 1440);
  React.useEffect(() => {
    const onR = () => setVw(window.innerWidth);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  const isMobile = vw <= 900;
  const CARD_W = isMobile ? Math.min(vw - 24, 360) : 555;
  const GAP = isMobile ? 12 : 48;
  const STEP = CARD_W + GAP;
  const n = DISCIPLINES.length;
  // Triple the list so we can always show neighbors on both sides
  const triple = [...DISCIPLINES, ...DISCIPLINES, ...DISCIPLINES];
  const [index, setIndex] = React.useState(n); // start in middle copy
  const [animate, setAnimate] = React.useState(true);
  const [dragX, setDragX] = React.useState(0);
  const dragRef = React.useRef({ active: false, startX: 0, moved: false });
  const trackRef = useRef(null);

  // After an animated transition that lands on an edge copy, silently snap
  // back to the middle copy so we can keep scrolling infinitely in either dir.
  const handleTransitionEnd = () => {
    if (index >= 2 * n) {
      setAnimate(false);
      setIndex(index - n);
    } else if (index < n) {
      setAnimate(false);
      setIndex(index + n);
    }
  };

  // Re-enable animation on the next frame after a silent snap
  React.useEffect(() => {
    if (!animate) {
      const id = requestAnimationFrame(() => setAnimate(true));
      return () => cancelAnimationFrame(id);
    }
  }, [animate]);

  const scroll = (dir) => setIndex((i) => i + dir);

  const onPointerDown = (e) => {
    if (e.button !== undefined && e.button !== 0) return;
    dragRef.current = { active: true, startX: e.clientX, moved: false, target: e.currentTarget, pointerId: e.pointerId };
    setAnimate(false);
    setDragX(0);
  };
  const onPointerMove = (e) => {
    if (!dragRef.current.active) return;
    const dx = e.clientX - dragRef.current.startX;
    if (Math.abs(dx) > 4 && !dragRef.current.moved) {
      dragRef.current.moved = true;
      try {dragRef.current.target.setPointerCapture(dragRef.current.pointerId);} catch (_) {}
    }
    if (dragRef.current.moved) setDragX(dx);
  };
  const onPointerEnd = (e) => {
    if (!dragRef.current.active) return;
    const dx = e.clientX - dragRef.current.startX;
    dragRef.current.active = false;
    const threshold = STEP * 0.18;
    setAnimate(true);
    setDragX(0);
    if (dx <= -threshold) setIndex((i) => i + 1);else
    if (dx >= threshold) setIndex((i) => i - 1);
    try {e.currentTarget.releasePointerCapture(e.pointerId);} catch (_) {}
  };
  const onClickCapture = (e) => {
    if (dragRef.current.moved) {
      e.preventDefault();
      e.stopPropagation();
      dragRef.current.moved = false;
    }
  };

  return (
    <section style={{
      position: 'relative', background: HC.bg,
      borderBottom: `1px solid ${HC.muted}`,
      padding: '80px 0', overflow: 'hidden'
    }}>
      <div style={{ maxWidth: 1312, margin: '0 auto 72px', padding: '0 40px' }}>
        <div style={{ maxWidth: 644, display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div style={{
            fontFamily: 'Nunito', fontWeight: 700, fontSize: 14,
            letterSpacing: '0.2em', color: HC.muted
          }}>NASZE DYSCYPLINY</div>
          <h2 style={{
            margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 48,
            lineHeight: 1.15, letterSpacing: '-0.022em', color: HC.white
          }}>Jedno miejsce, wiele perspektyw — od wglądu do działania.</h2>
          <p style={{
            margin: 0, fontFamily: 'Nunito', fontSize: 16, lineHeight: 1.6,
            color: HC.lavender
          }}>Praktyczna duchowość, która pomaga zrozumieć siebie i ruszyć dalej. Księżyc rozświetla drogę, a Ty wybierasz kolejny krok — my towarzyszymy w odkrywaniu sensu. To wgląd, który naprawdę porusza: sesje z ekspertami — od numerologii, przez tarota, po astrologię — dla realnej zmiany.</p>
        </div>
      </div>

      <div style={{ position: 'relative' }}>
        {/* Single section-level glow — fixed at viewport center, sits behind active card */}
        <img src="assets/disciplines/glow.png" alt="" aria-hidden style={{
          position: 'absolute', left: '50%', top: '50%',
          transform: 'translate(-50%, -50%)',
          width: 900, maxHeight: '100%', height: 'auto',
          pointerEvents: 'none', userSelect: 'none', zIndex: 0,
          objectFit: 'contain'
        }} />
        {/* Viewport — hides overflow, no scrollbar */}
        <div
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerEnd}
          onPointerCancel={onPointerEnd}
          onClickCapture={onClickCapture}
          style={{ overflow: 'hidden', position: 'relative', zIndex: 1, cursor: dragRef.current.active ? 'grabbing' : 'grab', touchAction: 'pan-y', userSelect: 'none' }}>
          {/* Track — centered so index 0 lands in the middle of the screen */}
          <div
            ref={trackRef}
            onTransitionEnd={handleTransitionEnd}
            style={{
              display: 'flex', gap: GAP,
              width: 'max-content',
              transform: `translate3d(calc(50vw - ${CARD_W / 2}px - ${index * STEP}px + ${dragX}px), 0, 0)`,
              transition: animate ? 'transform 550ms cubic-bezier(0.22, 1, 0.36, 1)' : 'none',
              willChange: 'transform'
            }}>
            {triple.map((d, i) =>
            <div key={i} style={{ flex: '0 0 auto' }}>
                <DisciplineCard d={d} width={CARD_W} />
              </div>
            )}
          </div>
        </div>
        <div style={{
          display: 'flex', justifyContent: 'center', gap: 16, marginTop: 32,
          position: 'relative', zIndex: 2, margin: "48px 0px 0px"
        }}>
          <RoundArrow dir="left" onClick={() => scroll(-1)} />
          <RoundArrow dir="right" onClick={() => scroll(1)} />
        </div>
      </div>
    </section>);

}

// ────────── WSTĘP HOME (intro with big photo) ──────────
function WstepHome() {
  useHomeData();
  const headlineLines = homeText('wstep.headline_lines', ['Czasem wiemy już wiele,', 'a mimo to nadal', 'stoimy w miejscu']);
  return (
    <section style={{
      position: 'relative', background: HC.bg,
      borderTop: `1px solid ${HC.muted}`, borderBottom: `1px solid ${HC.muted}`,
      padding: '0 24px 120px', overflow: 'hidden', minHeight: 720
    }}>
      {/* Full-bleed background image — starts from the very top of the section,
                                                                                               occupies the left half, fades into section bg on the right */}
      <div aria-hidden style={{
        position: 'absolute', top: 0, left: 0, width: '62%', height: '100%',
        backgroundImage: 'url(assets/wstep_pyl.jpg)',
        backgroundSize: 'cover', backgroundPosition: 'center top',
        backgroundRepeat: 'no-repeat',
        pointerEvents: 'none'
      }} />
      {/* Soft right-side fade so image blends into page bg */}
      <div aria-hidden style={{
        position: 'absolute', top: 0, left: 0, width: '62%', height: '100%',
        background: 'linear-gradient(90deg, rgba(6,11,24,0) 55%, rgba(6,11,24,1) 100%)',
        pointerEvents: 'none'
      }} />

      <div style={{
        position: 'relative', zIndex: 1,
        maxWidth: 1312, margin: '0 auto', padding: '40px'
      }}>
        {/* top two-column row — text aligned with right column, image lives in the background */}
        <div style={{
          display: 'grid', gridTemplateColumns: '620px 1fr', gap: 72, alignItems: 'center',
          minHeight: 547, marginBottom: 72
        }}>
          <div />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
            <h2 style={{
              margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 40,
              lineHeight: 1.2, letterSpacing: '-0.022em', color: HC.white,
              whiteSpace: 'nowrap'
            }}>
              {(Array.isArray(headlineLines) ? headlineLines : [headlineLines]).map((line, i) =>
                <span key={i} style={{ display: 'block' }}>{line}</span>
              )}
            </h2>
            <p style={{
              margin: 0, fontFamily: 'Nunito', fontSize: 16, lineHeight: 1.6,
              color: HC.lavender
            }}>{homeText('wstep.body', 'Każdy z nas trafia czasem na moment, w którym pojawia się więcej pytań niż odpowiedzi. Może to być poczucie powtarzalności, brak jasnego kierunku lub wrażenie, że coś pozostaje niedokończone. Przyjrzenie się temu z szerszej, być może nowej perspektywy pomaga lepiej zrozumieć sytuację.')}</p>
          </div>
        </div>

        {/* quote block */}
        <div style={{
          padding: '80px 20px', textAlign: 'center',
          display: 'flex', flexDirection: 'column', gap: 32, alignItems: 'center'
        }}>
          <blockquote style={{
            margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 24,
            lineHeight: 1.35, letterSpacing: '-0.022em', color: HC.white,
            fontStyle: 'italic', maxWidth: 1100, whiteSpace: 'pre-line'
          }}>{homeText('wstep.quote', 'Nie zawsze potrzebujesz więcej odpowiedzi.\nCzasem wystarczy lepiej zobaczyć to, co już jest.')}</blockquote>
          <img src="assets/logo.png" alt="" style={{ width: 48, height: 60, objectFit: 'contain', opacity: 1 }} />
        </div>
      </div>
    </section>);

}

// ────────── JAK PRACUJEMY ──────────
function JakPracujemy() {
  useHomeData();
  const cards = homeText('jakPracujemy.cards', [
    { icon: 'assets/jak-pracujemy/1.svg', title: 'Indywidualne podejście', body: 'Nie pracujemy według jednego schematu. Każda sytuacja jest inna, dlatego dobieramy podejście w zależności od Twoich potrzeb i momentu życia.' },
    { icon: 'assets/jak-pracujemy/2.svg', title: 'Dobór właściwego narzędzia', body: 'W zależności od sytuacji korzystamy z różnych dziedzin. Każda z nich pozwala spojrzeć na temat z innej strony i lepiej go zrozumieć.' },
    { icon: 'assets/jak-pracujemy/3.svg', title: 'Spokojny proces', body: 'Naszym celem nie jest szybka odpowiedź, lecz rzetelne przyjrzenie się sytuacji. Pracujemy w tempie, które pozwala na głębsze zrozumienie.' }
  ]);

  return (
    <section style={{
      position: 'relative', background: HC.bg,
      overflow: 'hidden', borderStyle: "solid", borderWidth: "0px", padding: "80px 24px"
    }}>
      {/* Background graphic — top right */}
      <img src="assets/jak-pracujemy/infinite.png" alt="" aria-hidden style={{
        position: 'absolute', top: 0, right: 0,
        width: 'min(58%, 980px)', height: 'auto',
        pointerEvents: 'none', userSelect: 'none',
        maskImage: 'radial-gradient(ellipse at 70% 45%, rgba(0,0,0,1) 40%, rgba(0,0,0,0) 75%)',
        WebkitMaskImage: 'radial-gradient(ellipse at 70% 45%, rgba(0,0,0,1) 40%, rgba(0,0,0,0) 75%)'
      }} />


      <div style={{ position: 'relative', maxWidth: 1312, margin: '0 auto', padding: "0px 16px" }}>
        <div style={{ maxWidth: 644, marginBottom: 150 }}>
          <div style={{
            fontFamily: 'Nunito', fontWeight: 700, fontSize: 14,
            letterSpacing: '0.2em', color: HC.muted, marginBottom: 20
          }}>{homeText('jakPracujemy.label', 'JAK PRACUJEMY')}</div>
          <h2 style={{
            margin: '0 0 20px', fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 48,
            lineHeight: 1.15, letterSpacing: '-0.022em', color: HC.white
          }}>{homeText('jakPracujemy.headline', 'Zaczynamy od zrozumienia miejsca w którym jesteś')}</h2>
          <p style={{
            margin: 0, fontFamily: 'Nunito', fontSize: 16, lineHeight: 1.6,
            color: HC.lavender
          }}>{homeText('jakPracujemy.body', 'Każda osoba trafia do nas z inną historią i w innym momencie życia. Czasem punktem wyjścia jest konkretna dziedzina, innym razem spotkanie z ekspertem. Niezależnie od tego, wspólnie dobieramy podejście, które najlepiej odpowiada Twojej sytuacji.')}</p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          {cards.map((c, i) =>
          <div key={i} style={{
            borderRadius: 16,
            display: 'flex', flexDirection: 'column', gap: 16, padding: "0px"
          }}>
              <div style={{
              width: 64, height: 64,
              display: 'flex', alignItems: 'center', justifyContent: 'center'
            }}>
              <img src={c.icon} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
            </div>
              <h3 style={{
              margin: 0, fontFamily: 'Nunito', fontSize: 22,
              letterSpacing: '-0.022em', color: HC.white, textAlign: "left", fontWeight: "400"
            }}>{c.title}</h3>
              <p style={{
              margin: 0, fontFamily: 'Nunito', fontSize: 15, lineHeight: 1.5,
              color: HC.lavender
            }}>{c.body}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ────────── USŁUGI HOME — reuses UslugiCarousel from main components.jsx ──────────
function UslugiHome() {
  useHomeData();
  return <div id="uslugi"><UslugiCarousel heading={homeText('uslugi.heading', 'Co dla Ciebie przygotujemy?')} /></div>;
}

// ────────── DLACZEGO WARTO ──────────
function DlaczegoWarto() {
  useHomeData();
  const points = homeText('dlaczegoWarto.points', [
    { title: 'Uważność zamiast schematów', body: 'Nie zakładamy jednej drogi dla wszystkich. Każda konsultacja i każda analiza opiera się na indywidualnym kontekście.' },
    { title: 'Różne specjalizacje, jeden standard jakości', body: 'Każdy ekspert wnosi własne doświadczenie i metodę pracy, ale łączy nas wspólny sposób myślenia: rzetelność, spokój i odpowiedzialność.' },
    { title: 'Zrozumienie, które porządkuje', body: 'Pomagamy zobaczyć więcej tam, gdzie pojawia się chaos, niepewność lub powtarzalność doświadczeń.' },
    { title: 'Przestrzeń do świadomych decyzji', body: 'Naszym celem nie jest dawanie gotowych recept, ale wspieranie Cię w lepszym rozumieniu siebie i swojej sytuacji.' }
  ]);

  return (
    <section style={{ background: HC.bg, padding: '80px 24px' }}>
      <div style={{
        maxWidth: 1312, margin: '0 auto',
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 64, padding: "0px 0px 0px 40px"
      }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20, justifyContent: 'flex-start' }}>
          <div style={{
            fontFamily: 'Nunito', fontWeight: 700, fontSize: 14,
            letterSpacing: '0.2em', color: HC.muted
          }}>{homeText('dlaczegoWarto.label', 'DLACZEGO WARTO')}</div>
          <h2 style={{
            margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 48,
            lineHeight: 1.15, letterSpacing: '-0.022em', color: HC.white
          }}>{homeText('dlaczegoWarto.headline', 'To co ważne, wymaga uważnego podejścia')}</h2>
          <p style={{
            margin: 0, fontFamily: 'Nunito', fontSize: 16, lineHeight: 1.6,
            color: HC.lavender
          }}>{homeText('dlaczegoWarto.body', 'W pracy z człowiekiem nie ma miejsca na przypadkowość ani uproszczenia. Dlatego łączymy doświadczenie ekspertów, spokojny proces i podejście, które pomaga lepiej zrozumieć swoją sytuację.')}</p>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 36 }}>
          {points.map((p, i) =>
          <div key={i} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <h3 style={{
              margin: 0, fontFamily: 'Nunito', fontSize: 24,
              color: HC.white, fontWeight: "400"
            }}>{p.title}</h3>
              <p style={{
              margin: 0, fontFamily: 'Nunito', fontSize: 16, lineHeight: 1.6,
              color: HC.lavender
            }}>{p.body}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ────────── EKSPERCI (3 cards grid) ──────────
const HOME_EXPERTS = [
{
  name: 'Konstancja Zahmala Lumia',
  slug: 'konstancjazahmalalumia',
  role: 'Tarocistka | Odczyty Energetyczne | Radiestetka',
  tags: ['Tarot', 'Intuicja'],
  img: 'assets/konstancja.png',
  bio: 'Urodzona pod mistrzowską energią, od zawsze czułam i widziałam więcej niż inni. Pracuję z tarotem jako narzędziem rozmowy — nie z przyszłością, ale z tym, co już w Tobie jest. Z tym, co czujesz, ale czego jeszcze nie nazwałeś.'
},
{
  name: 'Tomasz Buniek',
  slug: 'tomaszbuniek',
  role: 'Numerolog | Runista',
  tags: ['Numerologia', 'Runy'],
  img: 'assets/eksperci/tomaszbuniek.png',
  bio: 'Pomaga odkrywać potencjał, przełamywać blokady i zrozumieć wzorce poprzez numerologię. Specjalizuje się w pracy z runami i energią symboli, pomaga odkrywać ukryte wzorce, wzmacniać intencję oraz lepiej zrozumieć własną drogę.'
},
{
  name: 'Olga Konieczna',
  slug: 'olgakonieczna',
  role: 'Astrolog | Kosmogramy | Astrokartografia',
  tags: ['Astrologia'],
  img: 'assets/eksperci/annakonieczna.png',
  bio: 'Tłumaczę złożone układy w prosty sposób i pokazuję, jak przełożyć je na realne decyzje. Astrologia jest dla mnie językiem czasu — pomaga zrozumieć, co dojrzewa teraz, a co jeszcze poczeka.'
},
{
  name: 'Karolina Mardoll Kułakowska',
  slug: 'karolinamardoll',
  role: 'Analityk Duszy',
  tags: ['Tarot'],
  img: 'assets/eksperci/karolinamardoll.png',
  bio: 'Wiedźma nordycka, autorka czterech książek. Łączę duchowość i tradycje nordyckie — pomagam spojrzeć na życie z innej perspektywy i odnaleźć sens w trudnych doświadczeniach.'
},
{
  name: 'Karol Majewski',
  slug: 'karolmajewski',
  role: 'Chiromanta',
  tags: ['Chirologia'],
  img: 'assets/eksperci/karolmajewski.png',
  bio: 'Każda dłoń to unikalna mapa doświadczeń, talentów i możliwości. Pokazuję to, co często pozostaje niewidoczne — Twoją siłę, blokady, relacje i ścieżki rozwoju.'
}];


function ExpertCard({ e, scale, animate = true, width }) {
  // scale 1.0 = active, 0.78 = side
  const W = width || 1000;
  const isMobile = W < 700;
  const H = isMobile ? 620 : 420;
  const PAD = isMobile ? 20 : 36;
  const SQ = isMobile ? Math.min(W - PAD * 2, 220) : 420 - PAD * 2;
  return (
    <div style={{
      width: W, minWidth: W, height: H,
      transform: `scale(${scale})`,
      transformOrigin: 'center center',
      transition: animate ? 'transform 550ms cubic-bezier(0.22, 1, 0.36, 1), opacity 550ms' : 'none',
      opacity: scale > 0.9 ? 1 : 0.55,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      flex: '0 0 auto'
    }}>
      <div style={{
        width: W, height: H,
        borderRadius: 16, border: `1px solid ${HC.muted}`,
        background: '#060B18',
        position: 'relative',
        padding: PAD,
        display: isMobile ? 'flex' : 'grid',
        flexDirection: isMobile ? 'column' : undefined,
        gridTemplateColumns: isMobile ? undefined : `${SQ}px 1fr`,
        columnGap: 36,
        rowGap: isMobile ? 16 : undefined,
        alignItems: 'center',
        boxSizing: 'border-box'
      }}>
        {/* Photo zone — flat solid square inside the padded card */}
        <div style={{ position: 'relative', width: SQ, height: SQ }}>
          <div style={{
            position: 'absolute', inset: 0,
            borderRadius: 12,
            background: '#151331'
          }} />
          <img src={e.img || 'assets/expert.png'} alt={e.name}
          style={{
            position: 'absolute',
            left: '50%',
            transform: 'translateX(-50%)',
            bottom: 0,
            height: SQ + 56,
            width: 'auto',
            objectFit: 'contain',
            pointerEvents: 'none'
          }} />
        </div>

        {/* Right column — text (centers on mobile when stacked) */}
        <div style={{
          display: 'flex', flexDirection: 'column', gap: 16,
          paddingRight: isMobile ? 0 : 8,
          alignItems: isMobile ? 'center' : 'stretch',
          textAlign: isMobile ? 'center' : 'left'
        }}>
          <h3 style={{
            margin: 0, fontFamily: 'Playfair Display', fontWeight: 400,
            letterSpacing: '-0.022em', color: HC.white, lineHeight: 1.1, fontSize: "40px"
          }}>{e.name}</h3>
          <div style={{
            fontWeight: 400,
            color: HC.gold, letterSpacing: '0.01em', marginTop: -6, fontFamily: "\"Playfair Display\"", fontSize: "24px"
          }}>{e.role}</div>
          <p style={{
            margin: 0, fontFamily: 'Nunito', lineHeight: 1.7,
            color: HC.lavender, maxWidth: 460, fontSize: "16px"
          }}>{e.bio}</p>
          <div style={{ marginTop: 16 }}>
            <BtnSecond small href={e.slug ? e.slug + '.html' : expertHref(e.name)}>Poznaj eksperta</BtnSecond>
          </div>
        </div>
      </div>
    </div>);

}

function Eksperci() {
  const [vw, setVw] = React.useState(() => typeof window !== 'undefined' ? window.innerWidth : 1440);
  React.useEffect(() => {
    const onR = () => setVw(window.innerWidth);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  const isMobile = vw <= 900;
  const CARD_W = isMobile ? Math.min(vw - 24, 360) : 1000;
  const GAP = isMobile ? 12 : 48;
  const STEP = CARD_W + GAP;
  const n = HOME_EXPERTS.length;
  const triple = [...HOME_EXPERTS, ...HOME_EXPERTS, ...HOME_EXPERTS];
  const [index, setIndex] = React.useState(n);
  const [animate, setAnimate] = React.useState(true);
  const [dragX, setDragX] = React.useState(0);
  const dragRef = React.useRef({ active: false, startX: 0, moved: false });

  const handleTransitionEnd = () => {
    if (index >= 2 * n) {
      setAnimate(false);
      setIndex(index - n);
    } else if (index < n) {
      setAnimate(false);
      setIndex(index + n);
    }
  };

  React.useEffect(() => {
    if (!animate) {
      const id = requestAnimationFrame(() => setAnimate(true));
      return () => cancelAnimationFrame(id);
    }
  }, [animate]);

  const scroll = (dir) => setIndex((i) => i + dir);

  const onPointerDown = (e) => {
    if (e.button !== undefined && e.button !== 0) return;
    dragRef.current = { active: true, startX: e.clientX, moved: false, target: e.currentTarget, pointerId: e.pointerId };
    setAnimate(false);
    setDragX(0);
  };
  const onPointerMove = (e) => {
    if (!dragRef.current.active) return;
    const dx = e.clientX - dragRef.current.startX;
    if (Math.abs(dx) > 4 && !dragRef.current.moved) {
      dragRef.current.moved = true;
      try {dragRef.current.target.setPointerCapture(dragRef.current.pointerId);} catch (_) {}
    }
    if (dragRef.current.moved) setDragX(dx);
  };
  const onPointerEnd = (e) => {
    if (!dragRef.current.active) return;
    const dx = e.clientX - dragRef.current.startX;
    dragRef.current.active = false;
    const threshold = STEP * 0.18;
    setAnimate(true);
    setDragX(0);
    if (dx <= -threshold) setIndex((i) => i + 1);else
    if (dx >= threshold) setIndex((i) => i - 1);
    try {e.currentTarget.releasePointerCapture(e.pointerId);} catch (_) {}
  };
  const onClickCapture = (e) => {
    if (dragRef.current.moved) {
      e.preventDefault();
      e.stopPropagation();
      dragRef.current.moved = false;
    }
  };

  return (
    <section id="eksperci" style={{
      background: HC.bg, padding: '80px 0',
      borderTop: `1px solid ${HC.muted}`, borderBottom: `1px solid ${HC.muted}`,
      overflow: 'hidden'
    }}>
      <div style={{ maxWidth: 1312, margin: '0 auto 72px', padding: '0 40px' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{
            fontFamily: 'Nunito', fontWeight: 700, fontSize: 14,
            letterSpacing: '0.2em', color: HC.muted, marginBottom: 20
          }}>EKSPERCI</div>
          <h2 style={{
            margin: 0, fontFamily: 'Playfair Display', fontWeight: 400,
            lineHeight: 1.15, letterSpacing: '-0.022em', color: HC.white, fontSize: "48px"
          }}>Znajdź eksperta <em style={{ fontStyle: 'italic', fontSize: 48 }}>dla siebie</em></h2>
        </div>
      </div>

      <div style={{ position: 'relative' }}>
        <div
          onPointerDown={onPointerDown}
          onPointerMove={onPointerMove}
          onPointerUp={onPointerEnd}
          onPointerCancel={onPointerEnd}
          onClickCapture={onClickCapture}
          style={{ overflow: 'hidden', cursor: dragRef.current.active ? 'grabbing' : 'grab', touchAction: 'pan-y', userSelect: 'none' }}>
          <div
            onTransitionEnd={handleTransitionEnd}
            style={{
              display: 'flex', gap: GAP, alignItems: 'center',
              width: 'max-content',
              transform: `translate3d(calc(50vw - ${CARD_W / 2}px - ${index * STEP}px + ${dragX}px), 0, 0)`,
              transition: animate ? 'transform 550ms cubic-bezier(0.22, 1, 0.36, 1)' : 'none',
              willChange: 'transform',
              padding: '60px 0'
            }}>
            {triple.map((e, i) => {
              const isActive = i === index;
              return (
                <ExpertCard key={i} e={e} scale={isActive ? 1 : 0.78} animate={animate} width={CARD_W} />);

            })}
          </div>
        </div>
        <div style={{
          display: 'flex', justifyContent: 'center', gap: 16, marginTop: 32,
          position: 'relative', zIndex: 2
        }}>
          <RoundArrow dir="left" onClick={() => scroll(-1)} />
          <RoundArrow dir="right" onClick={() => scroll(1)} />
        </div>
      </div>
    </section>);

}

// ────────── OPINIE (masonry testimonials) ──────────
const OPINIE = [
{ title: 'Jasność po latach', quote: 'Sesja dała mi to, czego nie potrafiłam sobie nazwać przez lata. Wyszłam z uczuciem porządku.', name: 'Olga K.' },
{ title: 'Spokój i kierunek', quote: 'Nie dostałam przepowiedni, a jasny ogląd sytuacji. Po sesji podjęłam decyzję, którą odwlekałam od miesięcy.', name: 'Magdalena R.' },
{ title: 'Głębokie wglądy', quote: 'Rozmowa, która zostaje w głowie na długo. Wracam do niej i każdego dnia znajduję nowe znaczenia.', name: 'Piotr Z.' },
{ title: 'Wartościowa przestrzeń', quote: 'Rzadko spotyka się tyle profesjonalizmu i uważności w jednej rozmowie. Polecam z całego serca.', name: 'Katarzyna W.' },
{ title: 'Nowy początek', quote: 'Astrologia Damiana otworzyła mi oczy na wzorce, których kompletnie nie widziałam. Dziękuję.', name: 'Julia O.' },
{ title: 'Doskonałe wsparcie', quote: 'Numerologia pokazała mi coś, czego szukałam od dawna — strukturę, która ma sens.', name: 'Beata L.' }];


function Opinie() {
  return (
    <section style={{
      background: HC.bg, padding: '80px 24px', overflow: 'hidden', position: 'relative'
    }}>
      <div style={{ maxWidth: 1312, margin: '0 auto', padding: "0px 0px 0px 40px" }}>
        <div style={{ textAlign: 'center', marginBottom: 64 }}>
          <h2 style={{
            margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 48,
            lineHeight: 1.15, letterSpacing: '-0.022em', color: HC.white
          }}>Opinie</h2>
        </div>
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 32,
          alignItems: 'start'
        }}>
          {[0, 1, 2].map((col) =>
          <div key={col} style={{ display: 'flex', flexDirection: 'column', gap: 32,
            marginTop: col === 1 ? 0 : col === 2 ? 40 : 20
          }}>
              {OPINIE.filter((_, i) => i % 3 === col).map((o, i) =>
            <div key={i} style={{
              borderRadius: 16, background: HC.bgDeep,
              padding: 32, display: 'flex', flexDirection: 'column', gap: 24
            }}>
                  <h3 style={{
                margin: 0, fontFamily: 'Nunito', fontSize: 22,
                letterSpacing: '-0.022em', color: HC.white, fontWeight: "400"
              }}>{o.title}</h3>
                  <p style={{
                margin: 0, fontFamily: 'Roboto', fontSize: 16, lineHeight: 1.6,
                color: HC.lavender, fontStyle: 'italic'
              }}>„{o.quote}"</p>
                  <div style={{
                fontFamily: 'Nunito', fontWeight: 400, fontSize: 15,
                color: HC.lavender
              }}>{o.name}</div>
                </div>
            )}
            </div>
          )}
        </div>
      </div>
      {/* fade bottom — opinions visually fade into background */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0, height: 460,
        background: `linear-gradient(180deg, rgba(6,11,24,0) 0%, rgba(6,11,24,0.45) 35%, rgba(6,11,24,0.85) 70%, ${HC.bg} 100%)`,
        pointerEvents: 'none'
      }} />
    </section>);

}

// ────────── BLOG ──────────
function Blog() {
  const posts = typeof window !== 'undefined' && window.getLatestArticles ?
  window.getLatestArticles(3, null) : [];
  return (
    <section style={{
      background: HC.bg,
      borderTop: `1px solid ${HC.muted}`, borderBottom: `1px solid ${HC.muted}`, padding: "80px 24px"
    }}>
      <div style={{ maxWidth: 1312, margin: '0 auto', padding: "0px 0px 0px 40px" }}>
        <div style={{ marginBottom: 64 }}>
          <div style={{
            fontFamily: 'Nunito', fontWeight: 700, fontSize: 14,
            letterSpacing: '0.2em', color: HC.muted, marginBottom: 20
          }}>BLOG</div>
          <h2 style={{
            margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 48,
            lineHeight: 1.15, letterSpacing: '-0.022em', color: HC.white
          }}>Wiedza, która pomaga zrozumieć</h2>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
          {posts.map((p) =>
          <a key={p.slug} href={`${p.slug}.html`} style={{
            borderRadius: 16, border: '1px solid rgb(78, 70, 114)', padding: 32,
            display: 'flex', flexDirection: 'column', gap: 16,
            textDecoration: 'none', transition: 'border-color .3s, transform .3s',
            transform: 'none'
          }}>
              <h3 style={{
              margin: 0, fontFamily: 'Nunito',
              lineHeight: 1.4, color: HC.white, fontWeight: "400", fontSize: "24px"
            }}>{p.title}</h3>
              <div style={{
              fontFamily: 'Nunito',
              letterSpacing: '0.05em', color: HC.muted, fontSize: "14px"
            }}>{p.date}</div>
              <p style={{
              margin: 0, fontFamily: 'Nunito', lineHeight: 1.6,
              color: HC.lavender, fontSize: "16px"
            }}>{p.excerpt}</p>
              <div style={{
              marginTop: 8, fontFamily: 'Nunito', fontWeight: 700,
              color: HC.gold, fontSize: "16px"
            }}>Czytaj artykuł</div>
            </a>
          )}
        </div>
      </div>
    </section>);

}

// ────────── HOME CTA (with dust image) ──────────
function HomeCTA() {
  useHomeData();
  const headline = homeText('cta.headline', 'Nie musisz znać dziś wszystkich odpowiedzi.\nWystarczy że zrobisz pierwszy świadomy krok.');
  return (
    <section style={{
      position: 'relative', background: HC.bg,
      padding: '0 24px 80px', overflow: 'hidden', textAlign: 'center',
      minHeight: 720, display: 'flex', alignItems: 'flex-end', justifyContent: "center"
    }}>
      {/* Full-bleed background image — contain so full sparkle trail is visible */}
      <div aria-hidden style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'url(assets/cta_pyl.jpg)',
        backgroundSize: 'contain',
        backgroundPosition: 'center top',
        backgroundRepeat: 'no-repeat',
        pointerEvents: 'none'
      }} />
      {/* Soft bottom fade for text legibility + seamless blend with section bg */}
      <div aria-hidden style={{
        position: 'absolute', inset: 0,
        background: `linear-gradient(180deg, rgba(6,11,24,0) 0%, rgba(6,11,24,0) 55%, ${HC.bg} 100%)`,
        pointerEvents: 'none'
      }} />
      <div style={{
        position: 'relative', maxWidth: 1156, margin: '0 auto',
        display: 'flex', flexDirection: 'column', gap: 24, alignItems: 'center'
      }}>
        <h2 style={{
          margin: 0, fontFamily: 'Playfair Display', fontWeight: 400, fontSize: 48,
          lineHeight: 1.2, letterSpacing: '-0.022em', color: HC.white,
          whiteSpace: 'pre-line'
        }}>{headline}</h2>
        <p style={{
          margin: '0 0 16px', maxWidth: 786,
          fontFamily: 'Nunito', fontSize: 16, lineHeight: 1.6,
          color: HC.lavender
        }}>{homeText('cta.body', 'Skorzystaj z wiedzy i doświadczenia ekspertów, którzy pomogą Ci przyjrzeć się sobie z uważnością i spokojem.')}</p>
        <div style={{ display: 'flex', gap: 36 }}>
          <BtnSecond href={homeText('cta.btn_primary_href', '#eksperci')}>{homeText('cta.btn_primary_label', 'Wybierz eksperta')}</BtnSecond>
          <BtnSecond href={homeText('cta.btn_secondary_href', '#uslugi')}>{homeText('cta.btn_secondary_label', 'Znajdź usługę')}</BtnSecond>
        </div>
      </div>
    </section>);

}

// ─────────────────────────────────────────────────────────────
// DB-driven content for the Home page. Once /api/public/content?type=pages&key=home
// resolves, window.LUNA_HOME is populated and 'luna-home-loaded' fires. Components
// call useHomeData() to subscribe and homeText('path.to.field', fallback) to read
// individual strings with a fallback to the static defaults below.
// ─────────────────────────────────────────────────────────────
function useHomeData() {
  const [data, setData] = React.useState(() => (typeof window !== 'undefined' ? window.LUNA_HOME : null));
  React.useEffect(() => {
    const f = () => setData(window.LUNA_HOME || null);
    window.addEventListener('luna-home-loaded', f);
    return () => window.removeEventListener('luna-home-loaded', f);
  }, []);
  return data;
}

function homeText(path, fallback) {
  const data = (typeof window !== 'undefined' && window.LUNA_HOME) || null;
  if (!data) return fallback;
  const parts = String(path).split('.');
  let cur = data;
  for (const p of parts) {
    if (cur == null) return fallback;
    cur = cur[p];
  }
  return cur != null && cur !== '' ? cur : fallback;
}

(function loadHomeFromDB() {
  if (typeof window === 'undefined') return;
  const previewMode = (location.search || '').includes('preview=1');
  const url = '/api/public/content?type=pages&key=home' + (previewMode ? '&preview=1' : '');
  fetch(url, { credentials: 'include' })
    .then((r) => r.json())
    .then(({ item }) => {
      if (!item || !item.content) return;
      window.LUNA_HOME = item.content;
      try { window.dispatchEvent(new CustomEvent('luna-home-loaded')); } catch (_) {}
    })
    .catch((err) => { console.error('[home] load failed', err); });
})();

Object.assign(window, {
  HomeHero, HomeStars, Dyscypliny, WstepHome, JakPracujemy,
  UslugiHome, DlaczegoWarto, Eksperci, Opinie, Blog, HomeCTA,
  useHomeData, homeText
});