const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

/* ════════════════════════════════════════════════════════════
   HEADER
   ════════════════════════════════════════════════════════════ */
function Header({ onCta }) {
  const [open, setOpen] = useStateL(false);
  const links = [
    ['Co w środku', '#discover'],
    ['Opinie', '#reviews'],
    ['Pytania', '#faq'],
  ];
  return (
    <header className="sticky top-0 z-50 border-b border-white/[.06] bg-[#0C0820]/70 backdrop-blur-md">
      <div className="mx-auto flex max-w-7xl items-center justify-between px-5 sm:px-8 h-[68px]">
        <a href="#top" style={{ fontFamily: 'Georgia, serif', fontSize: '22px', fontWeight: 'normal', letterSpacing: '0.08em', color: '#d4b896', textDecoration: 'none' }}>{'☯︎ '}Paszport Życia</a>
        <nav className="hidden md:flex items-center gap-9">
          {links.map(([t, h]) => (
            <a key={h} href={h} style={{ textDecoration: 'none' }} className="font-sans text-[14px] text-lavmut hover:text-lav transition-colors">{t}</a>
          ))}
        </nav>
        <div className="hidden md:block">
          <button onClick={onCta}
            style={{ fontFamily: 'Georgia, serif', fontSize: '14px', letterSpacing: '0.04em', color: '#d4b896', background: 'transparent', border: '1px solid rgba(196,149,106,0.4)', borderRadius: '6px', padding: '7px 18px', cursor: 'pointer', transition: 'all 0.2s' }}
            onMouseEnter={e => { e.target.style.background = 'rgba(196,149,106,0.1)'; e.target.style.borderColor = 'rgba(196,149,106,0.7)'; }}
            onMouseLeave={e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'rgba(196,149,106,0.4)'; }}>
            Stwórz paszport
          </button>
        </div>
        <button className="md:hidden text-lav text-[24px] p-1" onClick={() => setOpen(o => !o)} aria-label="Menu">
          <Icon name={open ? 'x' : 'menu'} />
        </button>
      </div>
      {open && (
        <div className="md:hidden border-t border-white/[.06] bg-[#0C0820]/95 px-5 py-4 fade-up">
          <div className="flex flex-col gap-1">
            {links.map(([t, h]) => (
              <a key={h} href={h} onClick={() => setOpen(false)} style={{ textDecoration: 'none' }} className="py-2.5 font-sans text-[15px] text-lavmut hover:text-lav">{t}</a>
            ))}
            <button onClick={() => { setOpen(false); onCta(); }}
              style={{ marginTop: '8px', fontFamily: 'Georgia, serif', fontSize: '15px', color: '#d4b896', background: 'transparent', border: '1px solid rgba(196,149,106,0.4)', borderRadius: '6px', padding: '10px 18px', cursor: 'pointer', width: '100%' }}>
              Stwórz paszport
            </button>
          </div>
        </div>
      )}
    </header>
  );
}

/* ════════════════════════════════════════════════════════════
   HERO + FORM
   ════════════════════════════════════════════════════════════ */
const EVENT_PLACEHOLDERS = ['Ślub', 'Narodziny dziecka', 'Rozpoczęcie studiów', 'Pierwsza praca', 'Przeprowadzka do innego miasta'];

/* ── Miasta do podpowiedzi ───────────────────────────────── */
const CITIES = [
  'Warszawa, Polska', 'Kraków, Polska', 'Łódź, Polska', 'Wrocław, Polska',
  'Poznań, Polska', 'Gdańsk, Polska', 'Szczecin, Polska', 'Bydgoszcz, Polska',
  'Lublin, Polska', 'Białystok, Polska', 'Katowice, Polska', 'Gdynia, Polska',
  'Moskwa, Rosja', 'Sankt Petersburg, Rosja', 'Nowosybirsk, Rosja', 'Jekaterynburg, Rosja',
  'Kazań, Rosja', 'Niżny Nowogród, Rosja', 'Czelabińsk, Rosja', 'Samara, Rosja',
  'Omsk, Rosja', 'Rostów nad Donem, Rosja', 'Ufa, Rosja', 'Krasnojarsk, Rosja',
  'Woroneż, Rosja', 'Perm, Rosja', 'Wołgograd, Rosja', 'Krasnodar, Rosja',
  'Saratów, Rosja', 'Tiumeń, Rosja', 'Togliatti, Rosja', 'Iżewsk, Rosja',
  'Barnauł, Rosja', 'Irkuck, Rosja', 'Chabarowsk, Rosja', 'Władywostok, Rosja',
  'Jarosław, Rosja', 'Machaczkała, Rosja', 'Tomsk, Rosja', 'Orenburg, Rosja',
  'Kemerowo, Rosja', 'Kaliningrad, Rosja', 'Tuła, Rosja', 'Soczi, Rosja',
  'Kijów, Ukraina', 'Charków, Ukraina', 'Odessa, Ukraina', 'Lwów, Ukraina',
  'Mińsk, Białoruś', 'Homel, Białoruś', 'Ałmaty, Kazachstan', 'Astana, Kazachstan',
  'Szymkent, Kazachstan', 'Taszkent, Uzbekistan', 'Samarkanda, Uzbekistan', 'Biszkek, Kirgistan',
  'Duszanbe, Tadżykistan', 'Erywań, Armenia', 'Tbilisi, Gruzja', 'Baku, Azerbejdżan',
  'Kiszyniów, Mołdawia', 'Ryga, Łotwa', 'Wilno, Litwa', 'Tallinn, Estonia',
];

function CityAutocomplete({ value, onChange, error }) {
  const [suggestions, setSuggestions] = useStateL([]);
  const [loading, setLoading] = useStateL(false);
  const [open, setOpen] = useStateL(false);
  const [active, setActive] = useStateL(0);
  const boxRef = useRefL(null);

  // Track if search should run (true on user typing, false on city selection)
  const shouldSearchRef = useRefL(false);

  // Local state to track what the user actually typed
  const [inputValue, setInputValue] = useStateL(value || '');

  // Keep local state in sync if parent changes it directly
  useEffectL(() => {
    if (value !== inputValue) {
      setInputValue(value || '');
    }
  }, [value]);

  useEffectL(() => {
    const onDoc = (e) => { if (boxRef.current && !boxRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, []);

  // Debounced search effect
  useEffectL(() => {
    const query = inputValue.trim();
    if (query.length < 3) {
      setSuggestions([]);
      return;
    }

    // Skip search if flag is false (programmatic update or pick)
    if (!shouldSearchRef.current) {
      return;
    }

    setLoading(true);
    const controller = new AbortController();
    const delayDebounceFn = setTimeout(() => {
      fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&addressdetails=1&limit=6&accept-language=pl`, {
        signal: controller.signal,
        headers: {
          'User-Agent': 'PassportOfLifeApp/1.0'
        }
      })
        .then(res => res.json())
        .then(data => {
          if (Array.isArray(data)) {
            const formatted = data.map(item => {
              // Extract postal codes, double commas, and format nicely
              const cleanName = item.display_name
                .replace(/\d{6},?\s*/g, '') // Remove zip codes
                .replace(/,\s*\d+-\d+,?\s*/g, '') // Remove house ranges
                .replace(/\s*,\s*,/g, ',') // Fix duplicate commas
                .trim();
              return cleanName;
            });
            const unique = Array.from(new Set(formatted));
            setSuggestions(unique);
          }
          setLoading(false);
        })
        .catch(err => {
          if (err.name !== 'AbortError') {
            console.error(err);
            setLoading(false);
            // Fallback to local static filtering
            const q = query.toLowerCase();
            const starts = [], contains = [];
            for (const c of CITIES) {
              const city = c.split(',')[0].toLowerCase();
              if (city.startsWith(q)) starts.push(c);
              else if (city.includes(q)) contains.push(c);
            }
            setSuggestions([...starts, ...contains].slice(0, 6));
          }
        });
    }, 450);

    return () => { clearTimeout(delayDebounceFn); controller.abort(); };
  }, [inputValue]);

  const handleInputChange = (e) => {
    const val = e.target.value;
    shouldSearchRef.current = true;
    setInputValue(val);
    onChange(val); // Update parent immediately for validation
    setOpen(true);
    setActive(0);
  };

  const pick = (city) => {
    shouldSearchRef.current = false;
    setInputValue(city);
    onChange(city);
    setOpen(false);
    setSuggestions([]);
  };

  const onKey = (e) => {
    const items = suggestions;
    if (!open || items.length === 0) return;
    if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => (a + 1) % items.length); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => (a - 1 + items.length) % items.length); }
    else if (e.key === 'Enter') { e.preventDefault(); pick(items[active]); }
    else if (e.key === 'Escape') { setOpen(false); }
  };

  // highlight query letters in suggestion
  const renderCity = (c) => {
    const q = inputValue.trim().toLowerCase();
    const lc = c.toLowerCase();
    const idx = lc.indexOf(q);
    if (q.length === 0 || idx === -1) return <span>{c}</span>;
    return (
      <span>
        {c.slice(0, idx)}
        <span className="text-gold font-medium">{c.slice(idx, idx + q.length)}</span>
        {c.slice(idx + q.length)}
      </span>
    );
  };

  const cityInputStyle = {
    width: '100%',
    boxSizing: 'border-box',
    background: 'rgba(255,255,255,0.06)',
    border: error ? '1px solid rgba(220,80,80,0.6)' : '1px solid rgba(255,255,255,0.12)',
    borderRadius: '8px',
    padding: '12px 14px',
    color: '#e8e0d0',
    fontSize: '15px',
    fontFamily: 'Georgia, serif',
    outline: 'none',
  };

  return (
    <div ref={boxRef} className="relative">
      <div className="relative">
        <input
          value={inputValue}
          onChange={handleInputChange}
          onFocus={() => inputValue.trim() && setOpen(true)}
          onKeyDown={onKey}
          autoComplete="off"
          className={`field w-full rounded-xl pl-10 pr-4 py-3 font-sans text-[15px] ${error ? 'err' : ''}`}
          placeholder="Zacznij wpisywać miasto..." />
        <span className="pointer-events-none absolute left-3.5 top-1/2 -translate-y-1/2 text-lavmut text-[16px]">
          <Icon name="map-pin" />
        </span>
      </div>
      {open && (loading || suggestions.length > 0) && (
        <ul style={{ position: 'absolute', zIndex: 30, marginTop: '4px', width: '100%', overflow: 'hidden', borderRadius: '8px', border: '1px solid rgba(196,149,106,0.2)', background: 'rgba(18,18,32,0.97)', backdropFilter: 'blur(12px)', boxShadow: '0 24px 50px -18px rgba(0,0,0,0.85)', maxHeight: '280px', overflowY: 'auto', listStyle: 'none', padding: 0, margin: 0 }}>
          {loading && (
            <li style={{ padding: '12px 16px', color: '#9b8e80', fontFamily: 'Georgia, serif', fontSize: '13px' }}>
              Wyszukiwanie miejscowości...
            </li>
          )}
          {!loading && suggestions.map((c, i) => (
            <li key={c}>
              <button
                type="button"
                onMouseEnter={() => setActive(i)}
                onClick={() => pick(c)}
                style={{ display: 'block', width: '100%', padding: '10px 16px', textAlign: 'left', fontFamily: 'Georgia, serif', fontSize: '14px', background: i === active ? 'rgba(196,149,106,0.12)' : 'transparent', color: i === active ? '#e8e0d0' : '#9b8e80', border: 'none', cursor: 'pointer' }}>
                {renderCity(c)}
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function FormField({ label, hint, children, error }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
      <div style={{ lineHeight: 1.2 }}>
        <span style={{ fontSize: '12px', letterSpacing: '0.1em', textTransform: 'uppercase', color: '#9b8e80', fontFamily: 'Georgia, serif', fontWeight: 'normal' }}>
          {label}
        </span>
        {hint && <span style={{ fontSize: '11px', fontWeight: 'normal', color: '#7a7068', letterSpacing: 0, textTransform: 'none', marginLeft: '5px', fontFamily: 'Georgia, serif' }}>{hint}</span>}
      </div>
      {children}
      {error && (
        <div style={{ fontSize: '12px', color: '#E89B9B', marginTop: '4px', fontFamily: 'Georgia, serif' }}>
          {error}
        </div>
      )}
    </div>
  );
}

/* ── Инфо-иконка с тултипом по наведению ── */
function InfoHint({ text }) {
  return (
    <span className="info-hint" tabIndex={0}>
      <span className="info-hint-icon">i</span>
      <span className="info-hint-bubble">{text}</span>
    </span>
  );
}

/* ── Кастомное поле даты с маской «дд.мм.гггг» (без системного календаря) ──
   value/onChange работают в ISO-формате YYYY-MM-DD (как ждёт бэкенд). */
function MaskedDateInput({ value, onChange, style }) {
  const toDisplay = (iso) => {
    if (!iso) return '';
    const p = iso.split('-');
    return p.length === 3 ? `${p[2]}.${p[1]}.${p[0]}` : '';
  };
  const [text, setText] = useStateL(toDisplay(value));
  const handle = (e) => {
    const digits = e.target.value.replace(/\D/g, '').slice(0, 8); // ддммгггг
    let out = digits;
    if (digits.length > 4) out = digits.slice(0, 2) + '.' + digits.slice(2, 4) + '.' + digits.slice(4);
    else if (digits.length > 2) out = digits.slice(0, 2) + '.' + digits.slice(2);
    setText(out);
    if (digits.length === 8) {
      const d = +digits.slice(0, 2), m = +digits.slice(2, 4), y = +digits.slice(4, 8);
      const dt = new Date(y, m - 1, d);
      const ok = m >= 1 && m <= 12 && d >= 1 && d <= 31 && y >= 1900 && y <= new Date().getFullYear()
        && dt.getDate() === d && dt.getMonth() === m - 1;
      onChange(ok ? `${digits.slice(4, 8)}-${digits.slice(2, 4)}-${digits.slice(0, 2)}` : '');
    } else {
      onChange('');
    }
  };
  return <input type="text" inputMode="numeric" autoComplete="off" placeholder="dd.mm.rrrr"
    value={text} onChange={handle} style={style} />;
}

/* ── Кастомное поле времени с маской «чч:мм» (value/onChange в формате HH:mm) ── */
function MaskedTimeInput({ value, onChange, style }) {
  const [text, setText] = useStateL(value || '');
  const handle = (e) => {
    const digits = e.target.value.replace(/\D/g, '').slice(0, 4); // ччмм
    let out = digits;
    if (digits.length > 2) out = digits.slice(0, 2) + ':' + digits.slice(2);
    setText(out);
    if (digits.length === 4) {
      const h = +digits.slice(0, 2), mi = +digits.slice(2, 4);
      onChange(h <= 23 && mi <= 59 ? `${digits.slice(0, 2)}:${digits.slice(2, 4)}` : '');
    } else {
      onChange('');
    }
  };
  return <input type="text" inputMode="numeric" autoComplete="off" placeholder="gg:mm"
    value={text} onChange={handle} style={style} />;
}

function Hero({ onStart, error }) {
  const [name, setName] = useStateL('');
  const [email, setEmail] = useStateL('');
  const [bdate, setBdate] = useStateL('');
  const [btime, setBtime] = useStateL('');
  const [place, setPlace] = useStateL('');
  const [gender, setGender] = useStateL('');
  const [err, setErr] = useStateL({});

  const submit = (e) => {
    e.preventDefault();
    const next = {};
    if (!name.trim()) next.name = 'Podaj imię';
    if (!bdate) next.bdate = 'Podaj datę urodzenia';
    if (!place.trim()) next.place = 'Podaj miejsce urodzenia';
    if (!btime) next.btime = 'Podaj godzinę urodzenia';
    if (!gender) next.gender = 'Wybierz płeć';
    setErr(next);
    if (Object.keys(next).length === 0) {
      onStart({ name, email, bdate, btime, place, unknown: false, events: [], gender });
    }
  };

  const inputStyle = {
    width: '100%',
    boxSizing: 'border-box',
    background: 'rgba(255,255,255,0.06)',
    border: '1px solid rgba(255,255,255,0.12)',
    borderRadius: '8px',
    padding: '12px 14px',
    color: '#e8e0d0',
    fontSize: '15px',
    fontFamily: 'Georgia, serif',
    outline: 'none',
    colorScheme: 'dark',
  };

  return (
    <section id="top" style={{ position: 'relative', overflow: 'hidden' }}>
      <StarField count={80} />

      <div style={{ position: 'relative', zIndex: 10, maxWidth: '780px', margin: '0 auto', padding: '48px 24px 80px' }}>

        {/* Header — exact match to local */}
        <header style={{ textAlign: 'center', marginBottom: '48px' }}>
          <div style={{ fontSize: '48px', marginBottom: '12px', opacity: 0.85, lineHeight: 1 }}>{'☯︎'}</div>
          <h1 style={{ fontSize: '28px', fontWeight: 'normal', letterSpacing: '0.08em', color: '#d4b896', margin: '0 0 8px', fontFamily: 'Georgia, serif' }}>
            Paszport Życia — Twoja osobista analiza z daty urodzenia
          </h1>
          <p style={{ fontSize: '14px', color: '#8a7f72', fontStyle: 'italic', margin: 0, fontFamily: 'Georgia, serif' }}>
            Analiza osobista · Droga · Przeznaczenie
          </p>
        </header>

        {/* Form card — exact match to local */}
        <div style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', borderRadius: '16px', padding: '36px', backdropFilter: 'blur(10px)' }}>
          <form id="form-hero" onSubmit={submit}>

            {error && (
              <div style={{ marginBottom: '20px', padding: '12px', border: '1px solid rgba(220,80,80,0.3)', borderRadius: '8px', background: 'rgba(220,80,80,0.07)', color: '#E89B9B', fontSize: '13px' }}>
                {error}
              </div>
            )}

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-5 mb-5">
              <FormField label="Imię" error={err.name}>
                <input value={name} onChange={e => setName(e.target.value)}
                  style={{ ...inputStyle, borderColor: err.name ? 'rgba(220,80,80,0.6)' : 'rgba(255,255,255,0.12)' }}
                  placeholder="Podaj imię" />
              </FormField>

              <FormField label="Miejsce urodzenia" error={err.place}>
                <CityAutocomplete value={place} onChange={setPlace} error={err.place} />
              </FormField>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-5 mb-5">
              <FormField label="Data urodzenia" error={err.bdate}>
                <MaskedDateInput value={bdate} onChange={setBdate}
                  style={{ ...inputStyle, borderColor: err.bdate ? 'rgba(220,80,80,0.6)' : 'rgba(255,255,255,0.12)' }} />
              </FormField>
              <FormField label="Godzina urodzenia" hint={<InfoHint text="Dopuszczalna niedokładność do 2 godzin. Bez dokładnej godziny część danych paszportu może być niedokładna." />} error={err.btime}>
                <MaskedTimeInput value={btime} onChange={setBtime}
                  style={{ ...inputStyle, borderColor: err.btime ? 'rgba(220,80,80,0.6)' : 'rgba(255,255,255,0.12)' }} />
              </FormField>
            </div>

            <div>
              <FormField label="Płeć" error={err.gender}>
                <select value={gender} onChange={e => setGender(e.target.value)}
                  style={{ ...inputStyle, color: gender ? '#e8e0d0' : '#7a7068', borderColor: err.gender ? 'rgba(220,80,80,0.6)' : 'rgba(255,255,255,0.12)', appearance: 'none', WebkitAppearance: 'none', backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\' viewBox=\'0 0 12 8\'%3E%3Cpath d=\'M1 1l5 5 5-5\' stroke=\'%239b8e80\' stroke-width=\'1.5\' fill=\'none\' stroke-linecap=\'round\'/%3E%3C/svg%3E")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center', paddingRight: '36px' }}>
                  <option value="" disabled>Wybierz swoją płeć</option>
                  <option value="female">Kobieta</option>
                  <option value="male">Mężczyzna</option>
                </select>
              </FormField>
            </div>

            <button type="submit"
              style={{ width: '100%', marginTop: '28px', padding: '16px', background: 'linear-gradient(135deg, #8b5e3c, #c4956a)', border: 'none', borderRadius: '10px', color: '#fff', fontSize: '16px', fontFamily: 'Georgia, serif', letterSpacing: '0.05em', cursor: 'pointer' }}>
              Stwórz Paszport Życia · 49 zł
            </button>
            <p style={{ marginTop: "12px", textAlign: "center", fontFamily: "Georgia, serif", fontSize: "13px", color: "#9b8e80" }}>Koszt — 49 zł · płatność kartą online</p>
          </form>
        </div>
      </div>
    </section>
  );
}

/* ════════════════════════════════════════════════════════════
   SECTION shell
   ════════════════════════════════════════════════════════════ */
function Section({ id, eyebrow, title, sub, children, className = '', center = true }) {
  return (
    <section id={id} className={`relative mx-auto max-w-7xl px-5 sm:px-8 py-20 lg:py-28 ${className}`}>
      <Reveal className={center ? 'text-center mx-auto max-w-3xl' : 'max-w-3xl'}>
        {eyebrow && <Eyebrow className="mb-4">{eyebrow}</Eyebrow>}
        <SerifTitle text={title} className="text-[clamp(1.6rem,3.5vw,2.4rem)]" />
        {sub && <p className={`mt-5 font-sans text-[16px] sm:text-[17px] leading-relaxed text-lavmut ${center ? 'mx-auto max-w-2xl' : ''}`}>{sub}</p>}
      </Reveal>
      {children}
    </section>
  );
}

/* ── 2. WHAT YOU'LL DISCOVER ─────────────────────────────────── */
const DISCOVER = [
  ['sun',     'Twoja istota',          'Kim naprawdę jesteś — poza rolami, oczekiwaniami i tym, jak przywykłeś siebie postrzegać.'],
  ['user',    'Portret osobowości',    'Mocne strony, martwe punkty i powtarzające się scenariusze — pełna mapa twojego charakteru.'],
  ['heart',   'Miłość i relacje',      'Jak kochasz, czego szukasz w bliskości i dlaczego jedne relacje dają energię, a inne ją odbierają.'],
  ['briefcase','Kariera i pieniądze',  'Naturalny kierunek twojej samorealizacji, szczyty kariery i osobista strategia dochodu.'],
  ['calendar','Mapa życia',            'Twoje cykle życiowe: w jakim okresie jesteś teraz i co on odsłania.'],
  ['star',    'Przeznaczenie',         'Po co tu jesteś, jakie dary niesiesz i jaką drogą rozwija się twój los.'],
];
function Discover() {
  return (
    <section id="discover" className="relative mx-auto max-w-7xl px-5 sm:px-8 py-20 lg:py-28">
      <Reveal className="text-center mx-auto max-w-3xl">
        <Eyebrow className="mb-4">Co odkryjesz</Eyebrow>
        <h2 style={{ fontFamily: 'Georgia, serif', fontWeight: 'normal', letterSpacing: '0', color: '#d4b896', fontSize: 'clamp(1.6rem, 3.5vw, 2.4rem)', lineHeight: 1.25, margin: '0 0 20px' }}>
          Niektóre rzeczy o sobie poznajesz dopiero, gdy ktoś je nazwie.
        </h2>
        <p style={{ fontFamily: 'Georgia, serif', fontSize: '16px', color: '#9b8e80', fontStyle: 'italic', margin: 0 }}>
          Nie znajdziesz tu przepowiedni — tylko szczerą rozmowę o tym, kim naprawdę jesteś.
        </p>
      </Reveal>
      <div className="mt-14 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5">
        {DISCOVER.map(([ic, t, d], i) => (
          <Reveal key={t} delay={i * 70} className="glass-card lift rounded-[20px] p-7 text-center">
            <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full border border-gold/30 bg-gold/[.08] text-gold text-[20px]">
              <Icon name={ic} />
            </div>
            <h3 style={{ fontFamily: 'Georgia, serif', fontWeight: 'normal', letterSpacing: '0.04em', color: '#d4b896', fontSize: '20px', margin: '16px 0 8px' }}>{t}</h3>
            <p style={{ fontFamily: 'Georgia, serif', fontSize: '14px', lineHeight: 1.65, color: '#9b8e80', margin: 0 }}>{d}</p>
          </Reveal>
        ))}
      </div>
    </section>
  );
}

function How() { return null; }

/* ── 4. WHAT'S INCLUDED ──────────────────────────────────────── */
const INCLUDED = ['Portret osobowości', 'Miłość i relacje', 'Droga i przeznaczenie', 'Kluczowe okresy i daty', 'Ukryte siły i strefy rozwoju', 'Rekomendacje osobiste'];
function Included() {
  return (
    <Section id="included" eyebrow="Co w środku" title="Co zawiera twój *Paszport Życia*.">
      <div className="mt-12 mx-auto max-w-2xl">
        <div className="flex flex-col gap-3">
          {INCLUDED.map((t, i) => (
            <Reveal key={t} delay={i * 60} className="glass-card lift flex items-center gap-4 rounded-2xl px-6 py-4 text-left">
              <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gold/15 text-gold text-[16px]">
                <Icon name="check" />
              </span>
              <span className="font-sans text-[16px] text-lav">{t}</span>
            </Reveal>
          ))}
        </div>
      </div>
    </Section>
  );
}

/* ── 5. LOOK INSIDE ──────────────────────────────────────────── */
const INSIDE_POINTS = [
  'Zbudowany na podstawie momentu twoich narodzin',
  'Kilka głębokich rozdziałów o twoim życiu',
  'Piękny PDF, który zachowasz na zawsze',
  'Napisany prostym i bliskim językiem — bez skomplikowanych terminów',
];
function LookInside() {
  return (
    <section id="inside" className="relative mx-auto max-w-7xl px-5 sm:px-8 py-20 lg:py-28">
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-12 lg:gap-16 items-center">
        <Reveal>
          <div className="relative flex items-center justify-center min-h-[420px] sm:min-h-[470px]">
            <StarField count={28} />
            <div className="pointer-events-none absolute left-1/2 top-1/2 h-[320px] w-[320px] -translate-x-1/2 -translate-y-1/2 rounded-full"
                 style={{ background: 'radial-gradient(circle, rgba(120,70,160,.32), transparent 66%)' }}></div>
            {/* Symmetric fan: x / rot / y / scale mirror around index 2, so the deck
                self-centres on the container centre at any viewport (the whole unit
                is scaled by the responsive scale-* classes above — no per-width tuning).
                Cover (pdf-1) sits in the centre and is the front card (highest z).
                NOTE: Tailwind preflight is disabled (see index.html), so an <img> needs
                an explicit height:auto — otherwise a stray height attr / UA hint makes
                the picture a full-height strip and the fan explodes sideways. */}
            <div className="relative scale-[.8] sm:scale-95 lg:scale-100" style={{ width: '340px', height: '430px' }}>
              {[
                { src: '/assets/pdf-2.jpg', alt: 'Przykładowa strona Paszportu Życia — Rozdział 2: portret osobowości i mocne strony',      rot: -13, x: -64, y: 14, s: .90 },
                { src: '/assets/pdf-4.jpg', alt: 'Przykładowa strona Paszportu Życia — Rozdział 3: sfery życia, miłość i relacje',          rot: -6,  x: -32, y: 4,  s: .95 },
                { src: '/assets/pdf-1.jpg', alt: 'Przykładowa strona Paszportu Życia — okładka dokumentu',                                 rot: 0,   x: 0,   y: 0,  s: 1   },
                { src: '/assets/pdf-3.jpg', alt: 'Przykładowa strona Paszportu Życia — Rozdział 4: mapa życia i cykle życiowe',             rot: 6,   x: 32,  y: 4,  s: .95 },
                { src: '/assets/pdf-5.jpg', alt: 'Przykładowa strona Paszportu Życia — Rozdział 5: los i przeznaczenie',                      rot: 13,  x: 64,  y: 14, s: .90 },
              ].map((p, i) => (
                <img key={i} src={p.src} alt={p.alt} loading="lazy"
                  className="absolute left-1/2 top-1/2 w-[210px] rounded-[10px] border border-gold/25"
                  style={{
                    height: 'auto',
                    zIndex: 3 - Math.abs(i - 2),
                    transformOrigin: 'bottom center',
                    transform: `translate(-50%,-50%) translate(${p.x}px,${p.y}px) rotate(${p.rot}deg) scale(${p.s})`,
                    boxShadow: '0 28px 60px -18px rgba(0,0,0,.85), 0 6px 20px -8px rgba(0,0,0,.6)',
                    background: '#0d0d18',
                  }} />
              ))}
            </div>
          </div>
        </Reveal>
        <Reveal delay={120}>
          <Eyebrow className="mb-4">Zajrzyj do środka</Eyebrow>
          <SerifTitle text="Stworzone z *precyzją* i troską." className="text-[clamp(1.6rem,3.5vw,2.4rem)]" />
          <p className="mt-5 font-sans text-[16px] sm:text-[17px] leading-relaxed text-lavmut">
            Każdy Paszport to więcej niż obliczenie. To narracja napisana w twoim języku: astronomiczna precyzja spotyka się z prawdziwą uwagą poświęconą tobie.
          </p>
          <ul className="mt-7 flex flex-col gap-4">
            {INSIDE_POINTS.map((p) => (
              <li key={p} className="flex items-start gap-3.5">
                <span className="mt-1.5 h-2 w-2 shrink-0 rounded-full bg-gold shadow-[0_0_8px_1px_rgba(196,149,106,.55)]"></span>
                <span className="font-sans text-[15.5px] leading-relaxed text-lav">{p}</span>
              </li>
            ))}
          </ul>
        </Reveal>
      </div>
    </section>
  );
}

/* ── 6. REVIEWS ──────────────────────────────────────────────── */
function Stars() {
  return (
    <div className="flex gap-1 text-gold text-[15px]">
      {[0,1,2,3,4].map(i => <Icon key={i} name="star" style={{ fill: 'currentColor' }} />)}
    </div>
  );
}
const REVIEWS_DATA = [
  { text: "Ten dokument odmienił moje spojrzenie na siebie. Wszystkie kluczowe okresy mojego życia zgadzały się co do miesiąca! Analiza pomogła mi podjąć ważną decyzję o przeprowadzce.", author: "Maria, 29 lat" },
  { text: "Jakość wykonania na najwyższym poziomie. Pobrałem plik i wydrukowałem jak książkę. Czyta się jednym tchem, bez skomplikowanej terminologii, bardzo głęboka analiza psychologiczna.", author: "Artem, 34 lata" },
  { text: "Zaskoczyło mnie, jak dokładnie 5 wydarzeń, które podałam, powiązało się z kartą natalną. Powstał bardzo osobisty i wspierający przewodnik. Ogromnie dziękuję!", author: "Elena, 42 lata" },
  { text: "Na początku byłem sceptyczny, ale głębia analizy zadziwia. Sekcja o ukrytych siłach i strefach rozwoju skłoniła mnie do wielu przemyśleń. Świetne narzędzie do samopoznania.", author: "Michał, 27 lat" }
];
function Reviews() {
  return (
    <Section id="reviews" eyebrow="Opinie" title="Słowa tych, którzy już *przeszli*.">
      <div className="mt-14 grid grid-cols-1 sm:grid-cols-2 gap-5 max-w-4xl mx-auto">
        {REVIEWS_DATA.map((rev, i) => (
          <Reveal key={i} delay={(i % 2) * 90} className="glass-card lift rounded-[24px] p-7 text-left">
            <Stars />
            <p className="mt-4 font-serif italic text-[18px] leading-relaxed text-lav/90">«{rev.text}»</p>
            <p className="mt-5 font-sans text-[13.5px] uppercase tracking-[0.16em] text-lavmut">{rev.author}</p>
          </Reveal>
        ))}
      </div>
    </Section>
  );
}

/* ── 7. WHY US ───────────────────────────────────────────────── */
const WHY = [
  ['fingerprint', 'Głęboko i osobiście', 'Analiza opiera się na twoich danych, a nie na ogólnych szablonach.'],
  ['gem', 'Premium,\na nie masowy produkt', 'PDF w jakości kolekcjonerskiej, opracowany jak książka.'],
  ['lock', 'Prywatnie i bezpiecznie', 'Twoje dane należą tylko do ciebie, są szyfrowane i nie są przekazywane osobom trzecim.'],
];
function Why() {
  return (
    <Section id="why" eyebrow="Dlaczego Paszport Życia" title="To nie zwykły *horoskop*.">
      <div className="mt-14 grid grid-cols-1 md:grid-cols-3 gap-5">
        {WHY.map(([ic, t, d], i) => (
          <Reveal key={t} delay={i * 90} className="glass-card lift rounded-[24px] p-8 text-center">
            <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full border border-gold/30 bg-gold/[.08] text-gold text-[24px]">
              <Icon name={ic} />
            </div>
            <h3 className="mt-5 font-serif font-normal text-[21px] text-goldlt whitespace-pre-line">{t}</h3>
            <p className="mt-2.5 font-sans text-[14.5px] leading-relaxed text-lavmut">{d}</p>
          </Reveal>
        ))}
      </div>
    </Section>
  );
}

/* ── 8. FINAL CTA ────────────────────────────────────────────── */
function FinalCTA({ onCta }) {
  return (
    <section className="relative overflow-hidden py-24 lg:py-32">
      <StarField count={60} />
      <div className="pointer-events-none absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 h-[520px] w-[520px] rounded-full bg-[radial-gradient(circle,rgba(124,82,200,.35),transparent_65%)]"></div>
      <Reveal className="relative mx-auto max-w-3xl px-5 sm:px-8 text-center">
        <Eyebrow className="mb-5">Kosmos czeka</Eyebrow>
        <SerifTitle text="Poznaj tego, *o kim* pisały gwiazdy." className="text-[clamp(1.6rem,3.5vw,2.4rem)]" />
        <p className="mt-6 mx-auto max-w-xl font-sans text-[16px] sm:text-[17px] leading-relaxed text-lavmut">
          Kilka minut — i w twoich rękach dokument napisany tylko dla ciebie.
        </p>
        <div className="mt-9 flex justify-center">
          <GoldButton onClick={onCta} icon="sparkles" className="text-[16px] px-9 py-4">Stwórz mój Paszport Życia</GoldButton>
        </div>
      </Reveal>
    </section>
  );
}

/* ── 9. FAQ ──────────────────────────────────────────────────── */
const FAQS = [
  ['A jeśli nie znam dokładnej godziny urodzenia?', 'Dokładność co do minuty nie jest potrzebna — dopuszczalna jest niedokładność około 2 godzin, to wystarczy do trafnej analizy. Ale zupełnie bez godziny urodzenia obraz będzie niedokładny: ten moment wpływa na wiele szczegółów twojego paszportu.'],
  ['Ile kosztuje Paszport Życia?', 'To jednorazowy płatny produkt bez ukrytych subskrypcji. Dokładny koszt widzisz na etapie płatności — płacisz raz i otrzymujesz dokument na zawsze.'],
  ['Czy moje dane są bezpieczne?', 'Tak. Twoje dane należą tylko do ciebie, są przesyłane przez bezpieczne połączenie, nie są sprzedawane ani przekazywane osobom trzecim.'],
  ['Czy mogę podarować Paszport?', 'Oczywiście. Paszport Życia to przemyślany, osobisty prezent: wystarczy podać dane osoby, dla której jest przeznaczony.'],
  ['Czym różni się to od darmowych aplikacji?', 'To nie ogólny szablon według znaku zodiaku, lecz spójny dokument stworzony na podstawie twoich danych i wydarzeń — głęboki, premium i zapisany w pięknym PDF.'],
];
function FAQItem({ q, a, open, onClick }) {
  const ref = useRefL(null);
  return (
    <div className={`glass-card rounded-2xl overflow-hidden transition-colors ${open ? 'border-gold/35' : ''}`}>
      <button onClick={onClick} className="flex w-full items-center justify-between gap-4 px-6 py-5 text-left">
        <span className="font-serif text-[18px] sm:text-[19px] text-lav">{q}</span>
        <span className={`shrink-0 text-gold text-[20px] transition-transform duration-300 ${open ? 'rotate-180' : ''}`}>
          <Icon name="chevron-down" />
        </span>
      </button>
      <div style={{ maxHeight: open ? (ref.current ? ref.current.scrollHeight + 'px' : '300px') : '0px' }}
        className="overflow-hidden transition-[max-height] duration-400 ease-out">
        <div ref={ref} className="px-6 pb-6 -mt-1">
          <p className="font-sans text-[15px] leading-relaxed text-lavmut">{a}</p>
        </div>
      </div>
    </div>
  );
}
function FAQ() {
  const [open, setOpen] = useStateL(0);
  return (
    <Section id="faq" eyebrow="Pytania" title="Nie jesteś pierwszym, kto *pyta*.">
      <div className="mt-12 mx-auto max-w-3xl flex flex-col gap-3.5">
        {FAQS.map(([q, a], i) => (
          <Reveal key={q} delay={i * 50}>
            <FAQItem q={q} a={a} open={open === i} onClick={() => setOpen(open === i ? -1 : i)} />
          </Reveal>
        ))}
      </div>
    </Section>
  );
}

/* ── 10. FOOTER ──────────────────────────────────────────────── */
function Footer() {
  return (
    <footer style={{ borderTop: '1px solid rgba(255,255,255,0.06)', background: 'rgba(12,8,32,0.7)', backdropFilter: 'blur(12px)' }}>
      <div style={{ maxWidth: '1280px', margin: '0 auto', padding: '18px 32px', display: 'flex', flexWrap: 'wrap', alignItems: 'center', justifyContent: 'space-between', gap: '12px 24px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
          <span style={{ fontFamily: 'Georgia, serif', fontSize: '20px', fontWeight: 'normal', letterSpacing: '0.08em', color: '#d4b896' }}>{'☯︎ '}Paszport Życia</span>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '18px' }}>
          <a href="/oferta.html" style={{ fontFamily: 'Georgia, serif', fontSize: '13.5px', color: '#9b8e80', textDecoration: 'none' }}>Oferta publiczna</a>
          <a href="/privacy.html" style={{ fontFamily: 'Georgia, serif', fontSize: '13.5px', color: '#9b8e80', textDecoration: 'none' }}>Polityka prywatności</a>
          <a href="/cookie-policy.html" style={{ fontFamily: 'Georgia, serif', fontSize: '13.5px', color: '#9b8e80', textDecoration: 'none' }}>Pliki cookie</a>
        </div>
        <span style={{ fontFamily: 'Georgia, serif', fontSize: '13px', color: '#6a6058' }}>© 2026 Paszport Życia. Wszelkie prawa zastrzeżone.</span>
      </div>
    </footer>
  );
}

/* ════════════════════════════════════════════════════════════
   LANDING
   ════════════════════════════════════════════════════════════ */
function Landing({ onStart, error }) {
  const scrollToForm = () => {
    const f = document.getElementById('top');
    if (f) window.scrollTo({ top: 0, behavior: 'smooth' });
  };
  return (
    <div className="cosmic-bg min-h-screen">
      <Header onCta={scrollToForm} />
      <Hero onStart={onStart} error={error} />
      <Discover />
      <How />
      <Included />
      <LookInside />
      <Reviews />
      <Why />
      <FinalCTA onCta={scrollToForm} />
      <FAQ />
      <Footer />
    </div>
  );
}

window.Landing = Landing;
