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

/* ════════════════════════════════════════════════════════════
   HEADER
   ════════════════════════════════════════════════════════════ */
function Header({ onCta }) {
  const [open, setOpen] = useStateL(false);
  const links = [
    ['Что внутри', '#discover'],
    ['Отзывы', '#reviews'],
    ['Вопросы', '#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' }}>{'☯︎ '}Паспорт Жизни</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)'; }}>
            Создать паспорт
          </button>
        </div>
        <button className="md:hidden text-lav text-[24px] p-1" onClick={() => setOpen(o => !o)} aria-label="Меню">
          <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%' }}>
              Создать паспорт
            </button>
          </div>
        </div>
      )}
    </header>
  );
}

/* ════════════════════════════════════════════════════════════
   HERO + FORM
   ════════════════════════════════════════════════════════════ */
const EVENT_PLACEHOLDERS = ['Свадьба', 'Рождение ребёнка', 'Поступление в университет', 'Первое место работы', 'Переезд в другой город'];

/* ── Города для автоподсказок ───────────────────────────────── */
const CITIES = [
  'Москва, Россия', 'Санкт-Петербург, Россия', 'Новосибирск, Россия', 'Екатеринбург, Россия',
  'Казань, Россия', 'Нижний Новгород, Россия', 'Челябинск, Россия', 'Самара, Россия',
  'Омск, Россия', 'Ростов-на-Дону, Россия', 'Уфа, Россия', 'Красноярск, Россия',
  'Воронеж, Россия', 'Пермь, Россия', 'Волгоград, Россия', 'Краснодар, Россия',
  'Саратов, Россия', 'Тюмень, Россия', 'Тольятти, Россия', 'Ижевск, Россия',
  'Барнаул, Россия', 'Иркутск, Россия', 'Хабаровск, Россия', 'Владивосток, Россия',
  'Ярославль, Россия', 'Махачкала, Россия', 'Томск, Россия', 'Оренбург, Россия',
  'Кемерово, Россия', 'Калининград, Россия', 'Тула, Россия', 'Сочи, Россия',
  'Киев, Украина', 'Харьков, Украина', 'Одесса, Украина', 'Львов, Украина',
  'Минск, Беларусь', 'Гомель, Беларусь', 'Алматы, Казахстан', 'Астана, Казахстан',
  'Шымкент, Казахстан', 'Ташкент, Узбекистан', 'Самарканд, Узбекистан', 'Бишкек, Киргизия',
  'Душанбе, Таджикистан', 'Ереван, Армения', 'Тбилиси, Грузия', 'Баку, Азербайджан',
  'Кишинёв, Молдова', 'Рига, Латвия', 'Вильнюс, Литва', 'Таллин, Эстония',
];

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 delayDebounceFn = setTimeout(() => {
      const controller = new AbortController();
      fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&addressdetails=1&limit=6&accept-language=ru`, {
        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));
          }
        });

      return () => controller.abort();
    }, 450);

    return () => clearTimeout(delayDebounceFn);
  }, [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="Начните вводить город..." />
        <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' }}>
              Поиск населённого пункта...
            </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="дд.мм.гггг"
    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="чч:мм"
    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 = 'Введите имя';
    if (!bdate) next.bdate = 'Укажите дату рождения';
    if (!place.trim()) next.place = 'Укажите место рождения';
    if (!btime) next.btime = 'Укажите время рождения';
    if (!gender) next.gender = 'Выберите пол';
    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' }}>
            Паспорт Жизни
          </h1>
          <p style={{ fontSize: '14px', color: '#8a7f72', fontStyle: 'italic', margin: 0, fontFamily: 'Georgia, serif' }}>
            Личный анализ · Путь · Предназначение
          </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="Имя" 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="Введите имя" />
              </FormField>

              <FormField label="Место рождения" 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="Дата рождения" 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="Время рождения" hint={<InfoHint text="Допустима погрешность до 2 часов. Без точного времени часть данных паспорта может быть неточной." />} 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="Пол" 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>Выберите ваш пол</option>
                  <option value="female">Женский</option>
                  <option value="male">Мужской</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' }}>
              Создать Паспорт Жизни · 49 Br
            </button>
            <p style={{ marginTop: "12px", textAlign: "center", fontFamily: "Georgia, serif", fontSize: "13px", color: "#9b8e80" }}>Стоимость — 49 бел. руб. · оплата банковской картой через bePaid</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',     'Твоя суть',             'Кто ты есть на самом деле — за пределами ролей, ожиданий и того, каким ты привык себя видеть.'],
  ['user',    'Портрет личности',      'Сильные стороны, слепые пятна и повторяющиеся сценарии — полная карта твоего характера.'],
  ['heart',   'Любовь и отношения',    'Как ты любишь, что ищешь в близости и почему одни отношения питают, а другие — истощают.'],
  ['briefcase','Карьера и деньги',     'Природное направление твоей реализации, твои карьерные пики и личная стратегия дохода.'],
  ['calendar','Карта жизни',          'Твои 7-летние циклы: какой период ты сейчас проживаешь и что он открывает.'],
  ['star',    'Предназначение',        'Для чего ты здесь, какие дары несёшь и по какому пути разворачивается твоя судьба.'],
];
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">Что ты откроешь</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' }}>
          Некоторые вещи о себе ты узнаёшь только когда кто-то их называет.
        </h2>
        <p style={{ fontFamily: 'Georgia, serif', fontSize: '16px', color: '#9b8e80', fontStyle: 'italic', margin: 0 }}>
          Здесь нет предсказаний — только честный разговор о том, кто ты есть на самом деле.
        </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 = ['Портрет личности', 'Любовь и отношения', 'Путь и предназначение', 'Ключевые периоды и даты', 'Скрытые силы и зоны роста', 'Персональные рекомендации'];
function Included() {
  return (
    <Section id="included" eyebrow="Что внутри" title="Что входит в твой *Паспорт жизни*.">
      <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 = [
  'Построено по моменту твоего рождения',
  'Несколько глубоких глав о твоей жизни',
  'Красивый PDF, который ты сохранишь навсегда',
  'Написано простым и близким языком — без сложных терминов',
];
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>
            <div className="relative scale-[.8] sm:scale-95 lg:scale-100" style={{ width: '340px', height: '430px' }}>
              {[
                { src: '/assets/pdf-5.jpg', rot: -21, x: -96, y: 6,  s: .94 },
                { src: '/assets/pdf-3.jpg', rot: -13, x: -58, y: 0,  s: .96 },
                { src: '/assets/pdf-4.jpg', rot: -5,  x: -20, y: -4, s: .98 },
                { src: '/assets/pdf-2.jpg', rot: 4,   x: 24,  y: -2, s: .99 },
                { src: '/assets/pdf-1.jpg', rot: 12,  x: 66,  y: 6,  s: 1  },
              ].map((p, i) => (
                <img key={i} src={p.src} alt="Страница Паспорта жизни" loading="lazy"
                  className="absolute left-1/2 top-1/2 w-[210px] rounded-[10px] border border-gold/25"
                  style={{
                    zIndex: i + 1,
                    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">Заглянуть внутрь</Eyebrow>
          <SerifTitle text="Создано с *точностью* и заботой." className="text-[clamp(1.6rem,3.5vw,2.4rem)]" />
          <p className="mt-5 font-sans text-[16px] sm:text-[17px] leading-relaxed text-lavmut">
            Каждый Паспорт — это больше, чем расчёт. Это нарратив, написанный на твоём языке: астрономическая точность встречается с настоящим вниманием к тебе.
          </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: "Этот документ перевернул мое представление о себе. Все ключевые периоды моей жизни совпали с точностью до месяца! Анализ помог принять важное решение о переезде.", author: "Мария, 29 лет" },
  { text: "Качество оформления на высоте. Скачал файл и распечатал как книгу. Читается на одном дыхании, без сложной терминологии, очень глубокий психологический анализ.", author: "Артем, 34 года" },
  { text: "Удивило, как точно 5 событий, которые я указала, связались с натальной картой. Получился очень личный и поддерживающий путеводитель. Огромная благодарность!", author: "Елена, 42 года" },
  { text: "Сначала скептически относился, но глубина анализа поражает. Раздел про скрытые силы и зоны роста заставил о многом задуматься. Отличный инструмент для самопознания.", author: "Михаил, 27 лет" }
];
function Reviews() {
  return (
    <Section id="reviews" eyebrow="Отзывы" title="Слова тех, кто уже *прошёл*.">
      <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', 'Глубоко и персонально', 'Разбор строится именно по твоим данным, а не по общим шаблонам.'],
  ['gem', 'Премиум,\nа не масс-маркет', 'PDF коллекционного качества, оформленный как книга.'],
  ['lock', 'Приватно и безопасно', 'Твои данные принадлежат только тебе, зашифрованы и не передаются третьим лицам.'],
];
function Why() {
  return (
    <Section id="why" eyebrow="Почему Паспорт жизни" title="Это не обычный *гороскоп*.">
      <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">Космос ждёт</Eyebrow>
        <SerifTitle text="Встреться с тем, *о ком* писали звёзды." 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">
          Несколько минут — и в твоих руках документ, который написан только для тебя.
        </p>
        <div className="mt-9 flex justify-center">
          <GoldButton onClick={onCta} icon="sparkles" className="text-[16px] px-9 py-4">Создать мой Паспорт жизни</GoldButton>
        </div>
      </Reveal>
    </section>
  );
}

/* ── 9. FAQ ──────────────────────────────────────────────────── */
const FAQS = [
  ['А если я не знаю точное время рождения?', 'Точность до минуты не нужна — допустима погрешность около 2 часов, для верного разбора этого достаточно. А вот совсем без времени рождения картина получится неточной: этот момент влияет на многие детали твоего паспорта.'],
  ['Сколько стоит Паспорт жизни?', 'Это единый платный продукт без скрытых подписок. Точную стоимость ты видишь на шаге оплаты — платишь один раз и получаешь документ навсегда.'],
  ['Мои данные в безопасности?', 'Да. Твои данные принадлежат только тебе, передаются по защищённому соединению, не продаются и не передаются третьим лицам.'],
  ['Можно ли подарить Паспорт?', 'Конечно. Паспорт жизни — продуманный персональный подарок: достаточно ввести данные того, кому он предназначен.'],
  ['Чем это отличается от бесплатных приложений?', 'Это не общий шаблон по знаку зодиака, а цельный документ, собранный по твоим данным и событиям — глубокий, премиальный и сохранённый в красивом 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="Вопросы" title="Ты не первый, кто *спрашивает*.">
      <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' }}>{'☯︎ '}Паспорт Жизни</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' }}>Публичная оферта</a>
          <a href="/privacy.html" style={{ fontFamily: 'Georgia, serif', fontSize: '13.5px', color: '#9b8e80', textDecoration: 'none' }}>Политика конфиденциальности</a>
          <a href="/cookie-policy.html" style={{ fontFamily: 'Georgia, serif', fontSize: '13.5px', color: '#9b8e80', textDecoration: 'none' }}>Файлы cookie</a>
        </div>
        <span style={{ fontFamily: 'Georgia, serif', fontSize: '13px', color: '#6a6058' }}>© 2026 Паспорт жизни. Все права защищены.</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;
