// NumerologistSite — enhanced with scroll animations, hover effects, floating symbols

const NURIA_PHOTO = "https://images.unsplash.com/photo-1573496359142-b8d87734a5a2?w=1400&q=80&auto=format&fit=crop";

const SERVICES = [
  {
    id: "consult",
    title: "Нумерологическая консультация",
    price: "5 000 сом",
    meta: "Созвон или аудио · 40–50 минут",
    points: [
      "Анализ личности",
      "Предназначение",
      "Кармические задачи и уроки",
      "Базовая прогностика",
      "Тенденции на текущий год",
      "Социальные задачи",
    ],
  },
  {
    id: "forecast",
    title: "Детальная прогностика на год",
    price: "5 000 сом",
    meta: "PDF-файл",
    points: [
      "Детальный разбор 12 месяцев",
      "Ключевые события",
      "Периоды силы и отдыха",
    ],
  },
  {
    id: "child",
    title: "Детский разбор",
    price: "2 000 сом",
    meta: "Консультация для родителей",
    points: [
      "Врождённый потенциал ребёнка",
      "Тенденции детства и их влияние на будущее",
      "Сильные и слабые стороны",
      "Рекомендации по коммуникации, здоровью и кружкам",
    ],
  },
];

// ── Scroll reveal hook ──────────────────────────────────────────────────────
function useReveal() {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => e.isIntersecting && e.target.classList.add("visible")),
      { threshold: 0.12 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ── Parallax hero hook ──────────────────────────────────────────────────────
function useParallax(ref, factor = 0.25) {
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onScroll = () => {
      el.style.backgroundPositionY = `calc(30% + ${window.scrollY * factor}px)`;
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [ref, factor]);
}

// ── Utilities ───────────────────────────────────────────────────────────────
function maskKgPhone(raw) {
  const digits = raw.replace(/\D/g, "").replace(/^996/, "").slice(0, 9);
  let out = "+996";
  if (digits.length > 0) out += " (" + digits.slice(0, 3);
  if (digits.length >= 3) out += ")";
  if (digits.length > 3) out += " " + digits.slice(3, 5);
  if (digits.length > 5) out += "-" + digits.slice(5, 7);
  if (digits.length > 7) out += "-" + digits.slice(7, 9);
  return out;
}

async function sendToTelegram({ token, chatId, name, phone, service }) {
  const text =
    `🔔 Новая заявка\n\n` +
    `👤 Имя: ${name}\n` +
    `📱 Телефон: ${phone}\n` +
    `🔮 Услуга: ${service}`;
  const res = await fetch(`https://api.telegram.org/bot${token}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ chat_id: chatId, text }),
  });
  const data = await res.json();
  if (!data.ok) throw new Error(data.description || "Telegram error");
}

// ── Icons ───────────────────────────────────────────────────────────────────
const IconInstagram = ({ size = 20, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8">
    <rect x="3" y="3" width="18" height="18" rx="5"/>
    <circle cx="12" cy="12" r="4"/>
    <circle cx="17.5" cy="6.5" r="1" fill={color} stroke="none"/>
  </svg>
);
const IconWhatsApp = ({ size = 20, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
    <path d="M12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.3c1.4.8 3.1 1.2 4.8 1.2 5.5 0 10-4.5 10-10S17.5 2 12 2zm5.5 14.2c-.2.7-1.4 1.3-1.9 1.4-.5.1-1.2.1-1.9-.1-.4-.1-1-.3-1.7-.6-3-1.3-5-4.4-5.1-4.6-.2-.2-1.3-1.7-1.3-3.2s.8-2.3 1.1-2.6c.3-.3.6-.4.8-.4h.6c.2 0 .5 0 .7.5.2.6.8 2.1.9 2.2.1.1.1.3 0 .5l-.4.5c-.1.2-.3.3-.1.6.2.3.7 1.1 1.5 1.8 1 .9 1.9 1.2 2.2 1.3.3.1.4.1.6-.1.2-.2.7-.8.9-1.1.2-.3.3-.2.6-.1.3.1 1.7.8 2 1 .3.1.5.2.5.3.1.2.1.7-.1 1.3z"/>
  </svg>
);
const IconTelegram = ({ size = 20, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={color}>
    <path d="M21.5 4.5L2.5 11.8c-.7.3-.7 1.3 0 1.6l4.6 1.6 1.8 5.7c.2.6.9.7 1.3.3l2.5-2.4 4.7 3.4c.5.4 1.3.1 1.5-.5l3.4-15.6c.2-.7-.5-1.3-1.2-1zm-3.4 4.4l-7.6 6.9-.3 3.2-1.3-4 8.6-6.9c.4-.3.9.2.6.5z"/>
  </svg>
);

// ── Navbar ───────────────────────────────────────────────────────────────────
function Navbar({ theme }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [menuOpen, setMenuOpen] = React.useState(false);
  const isDesktop = useIsDesktop();

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 40);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  
  React.useEffect(() => {
    if (menuOpen) {
      document.body.style.overflow = "hidden";
    } else {
      document.body.style.overflow = "auto";
    }
    return () => { document.body.style.overflow = "auto"; };
  }, [menuOpen]);

  const scrollTo = (id) => {
    setMenuOpen(false);
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  const LINKS = [
    { label: "Услуги",     id: "services"     },
    { label: "Обо мне",   id: "about"         },
    { label: "Записаться", id: "form-section" },
  ];

  const NAV_SOCIALS = [
    { href: "https://instagram.com/NURIA_IG", icon: <IconInstagram size={17} />, label: "Instagram" },
    { href: "https://wa.me/996700000000",     icon: <IconWhatsApp  size={17} />, label: "WhatsApp"  },
  ];

  const textColor = scrolled ? theme.heading : "#fff";

  return (
    <>
      <nav className={`navbar${scrolled ? " scrolled" : ""}`} style={{
        background: scrolled ? undefined : "transparent",
        padding: scrolled ? "0" : "0",
      }}>
      <div style={{
        maxWidth: CONTENT_MAX + 48, margin: "0 auto",
        padding: "0 24px",
        height: scrolled ? 60 : 72,
        display: "flex", alignItems: "center", justifyContent: "space-between",
        transition: "height 0.3s ease",
      }}>
        {/* Logo */}
        <div onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })} style={{
          fontFamily: theme.fontDisplay, fontSize: 20,
          fontWeight: theme.headingWeight, color: textColor,
          letterSpacing: theme.headingTracking, cursor: "pointer",
          transition: "color 0.3s ease",
        }}>
          Нурия
        </div>

        {/* Desktop links */}
        <div className="nav-desktop" style={{ display: "flex", alignItems: "center", gap: 32 }}>
          {LINKS.map((l) => (
            <span key={l.id} className="nav-link" onClick={() => scrollTo(l.id)} style={{
              fontFamily: theme.fontBody, fontSize: 13.5, fontWeight: 500,
              color: textColor, letterSpacing: "0.02em",
              transition: "color 0.3s ease",
            }}>
              {l.label}
            </span>
          ))}
          <div style={{ display: "flex", gap: 14, marginLeft: 8 }}>
            {NAV_SOCIALS.map((s) => (
              <a key={s.label} href={s.href} target="_blank" rel="noopener"
                aria-label={s.label} className="nav-social"
                style={{ color: textColor, transition: "color 0.3s ease" }}>
                {s.icon}
              </a>
            ))}
          </div>
        </div>
        
        {/* Mobile hamburger button */}
        <button 
          className={`nav-hamburger${menuOpen ? " open" : ""}`}
          onClick={() => setMenuOpen(!menuOpen)}
          style={{ color: textColor }}
          aria-label="Меню"
        >
          <span></span>
          <span></span>
          <span></span>
        </button>
      </div>
    </nav>
    
    {/* Mobile menu overlay */}
    <div 
      className={`nav-mobile-menu${menuOpen ? " open" : ""}`}
      onClick={() => setMenuOpen(false)}
    >
      <div className="nav-mobile-content" onClick={(e) => e.stopPropagation()}>
        <div style={{ display: "flex", flexDirection: "column" }}>
          {LINKS.map((l) => (
            <a 
              key={l.id}
              className="nav-mobile-link"
              onClick={() => scrollTo(l.id)}
            >
              {l.label}
            </a>
          ))}
        </div>
        
        <div className="nav-mobile-socials">
          {NAV_SOCIALS.map((s) => (
            <a 
              key={s.label} 
              href={s.href} 
              target="_blank" 
              rel="noopener"
              aria-label={s.label}
              style={{ 
                color: theme.heading,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                transition: "transform 0.2s ease"
              }}
              onMouseEnter={(e) => e.currentTarget.style.transform = "scale(1.15)"}
              onMouseLeave={(e) => e.currentTarget.style.transform = "scale(1)"}
            >
              {s.icon}
            </a>
          ))}
        </div>
      </div>
    </div>
    </>
  );
}

// ── Checkbox ─────────────────────────────────────────────────────────────────
function Checkbox({ checked, onChange, children }) {
  return (
    <label className="custom-checkbox" onClick={() => onChange(!checked)}>
      <input type="checkbox" checked={checked} onChange={() => {}} />
      <div className={`checkbox-box${checked ? " checked" : ""}`}>
        {checked && (
          <svg width="11" height="9" viewBox="0 0 11 9" fill="none">
            <path d="M1 4l3 3 6-6" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        )}
      </div>
      <span style={{ fontSize: 13, lineHeight: 1.5 }}>{children}</span>
    </label>
  );
}

// ── Custom select ────────────────────────────────────────────────────────────
function CustomSelect({ value, onChange, options, theme, inputStyle }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

  React.useEffect(() => {
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const selected = options.find((o) => o.value === value);

  return (
    <div ref={ref} style={{ position: "relative", userSelect: "none" }}>
      <div
        onClick={() => setOpen((v) => !v)}
        className="form-input"
        style={{
          ...inputStyle,
          display: "flex", alignItems: "center", justifyContent: "space-between",
          cursor: "pointer",
          borderColor: open ? theme.eyebrow : undefined,
          boxShadow: open ? `0 0 0 3px rgba(63,113,80,0.18)` : undefined,
        }}
      >
        <span className="select-value">
          {selected?.label}
        </span>
        <svg width="12" height="8" viewBox="0 0 12 8" style={{
          flexShrink: 0, marginLeft: 10,
          transition: "transform 0.2s ease",
          transform: open ? "rotate(180deg)" : "rotate(0deg)",
        }}>
          <path d="M1 1l5 5 5-5" stroke={theme.heading} strokeWidth="1.5" fill="none" strokeLinecap="round"/>
        </svg>
      </div>

      {open && (
        <div className="custom-dropdown-list" style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0,
          background: theme.inputBg,
          border: `1.5px solid ${theme.eyebrow}`,
          borderRadius: theme.inputRadius,
          overflow: "hidden",
          zIndex: 100,
          boxShadow: "0 8px 24px rgba(26,38,32,0.12)",
        }}>
          {options.map((o) => (
            <div
              key={o.value}
              className={`custom-dropdown-option${o.value === value ? " selected" : ""}`}
              onClick={() => { onChange(o.value); setOpen(false); }}
              style={{
                padding: "13px 16px",
                fontFamily: theme.fontBody, fontSize: 14,
                color: o.value === value ? theme.eyebrow : theme.body,
                fontWeight: o.value === value ? 600 : 400,
                borderBottom: `1px solid ${theme.divider}`,
                cursor: "pointer",
              }}
            >
              <div style={{ fontWeight: "inherit" }}>{o.title}</div>
              <div style={{
                fontSize: 12, marginTop: 2, opacity: 0.7,
                fontWeight: 400, color: theme.muted,
              }}>{o.meta} · {o.price}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Floating symbols in hero ─────────────────────────────────────────────────
const SYMBOLS = [
  { ch: "✦", cls: "sym-a", x: "12%", y: "22%", size: 28 },
  { ch: "∞", cls: "sym-b", x: "82%", y: "18%", size: 32 },
  { ch: "◈", cls: "sym-c", x: "72%", y: "58%", size: 22 },
  { ch: "✦", cls: "sym-d", x: "28%", y: "68%", size: 18 },
  { ch: "⬡", cls: "sym-e", x: "90%", y: "42%", size: 26 },
];

function FloatingSymbols() {
  return (
    <div style={{ position: "absolute", inset: 0, pointerEvents: "none", overflow: "hidden" }}>
      {SYMBOLS.map((s, i) => (
        <div key={i} className={s.cls} style={{
          position: "absolute",
          left: s.x, top: s.y,
          fontSize: s.size,
          color: "rgba(220,235,224,0.7)",
          fontFamily: "Georgia, serif",
          userSelect: "none",
          willChange: "transform",
        }}>
          {s.ch}
        </div>
      ))}
    </div>
  );
}

const CONTENT_MAX = 1100;

function useIsDesktop() {
  const [desktop, setDesktop] = React.useState(
    typeof window !== "undefined" ? window.innerWidth >= 768 : false
  );
  React.useEffect(() => {
    const h = () => setDesktop(window.innerWidth >= 768);
    window.addEventListener("resize", h, { passive: true });
    return () => window.removeEventListener("resize", h);
  }, []);
  return desktop;
}

// ── Hero ────────────────────────────────────────────────────────────────────
function Hero({ theme }) {
  const heroRef = React.useRef(null);
  useParallax(heroRef, 0.22);

  const scrollToForm = () => {
    document.getElementById("form-section")?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <section ref={heroRef} style={{
      position: "relative",
      height: "min(720px, 90vh)",
      width: "100%",
      overflow: "hidden",
      backgroundImage: `url(${NURIA_PHOTO})`,
      backgroundSize: "cover",
      backgroundPosition: "center 30%",
    }}>
      <div style={{ position: "absolute", inset: 0, background: theme.heroOverlay }} />
      <div className="hero-grain" />
      <FloatingSymbols />

      <div style={{
        position: "absolute", inset: 0,
        display: "flex", flexDirection: "column", justifyContent: "flex-end",
      }}>
        <div style={{ maxWidth: CONTENT_MAX, margin: "0 auto", width: "100%", padding: "0 28px 56px" }}>
          <div className="hero-eyebrow" style={{
            fontFamily: theme.fontMono || theme.fontBody,
            fontSize: 11, letterSpacing: "0.22em", textTransform: "uppercase",
            color: theme.heroEyebrow, marginBottom: 18,
          }}>
            Нумеролог · Бишкек
          </div>
          <h1 className="hero-title" style={{
            margin: 0,
            fontFamily: theme.fontDisplay,
            fontSize: "clamp(38px, 5vw, 64px)",
            lineHeight: 1.05,
            letterSpacing: theme.headingTracking,
            fontWeight: theme.headingWeight,
            color: theme.heroTitle,
            fontStyle: theme.headingStyle || "normal",
            textShadow: "0 2px 20px rgba(44,24,16,0.3)",
          }}>
            Нурия<br/>
            <span style={{ fontStyle: "italic", fontWeight: 400 }}>нумеролог</span>
          </h1>
          <p className="hero-sub" style={{
            marginTop: 20, marginBottom: 28,
            fontFamily: theme.fontBody,
            fontSize: 16, lineHeight: 1.6,
            color: theme.heroSubtitle, maxWidth: 440,
          }}>
            Помогаю понять себя, своё предназначение и жизненный путь через числа.
          </p>
          <div className="hero-btn">
            <button onClick={scrollToForm} className="btn-primary" style={{
              padding: "16px 36px",
              background: theme.btnBg, color: theme.btnFg,
              border: "none", borderRadius: theme.btnRadius,
              fontFamily: theme.fontBody, fontSize: 14, fontWeight: 600,
              letterSpacing: "0.05em", cursor: "pointer",
            }}>
              Записаться
            </button>
          </div>
        </div>
      </div>

      {/* bottom fade */}
      <div style={{
        position: "absolute", bottom: 0, left: 0, right: 0,
        height: 80,
        background: "linear-gradient(to bottom, transparent, rgba(251,253,251,0.28))",
        pointerEvents: "none",
      }} />
    </section>
  );
}

// ── Gold shimmer divider ─────────────────────────────────────────────────────
function GoldDivider() {
  return <div className="gold-divider" />;
}

// ── Services ─────────────────────────────────────────────────────────────────
function ServiceCard({ s, theme, onPickService, delay }) {
  return (
    <div className={`service-card reveal reveal-delay-${delay}`} style={{
      background: theme.cardBg,
      border: theme.cardBorder,
      borderRadius: theme.cardRadius,
      padding: "28px 24px",
      display: "flex", flexDirection: "column",
      cursor: "default",
    }}>
      <div style={{
        fontFamily: theme.fontMono || theme.fontBody,
        fontSize: 10.5, letterSpacing: "0.18em", textTransform: "uppercase",
        color: theme.eyebrow, marginBottom: 10,
      }}>
        {s.meta}
      </div>
      <h3 style={{
        margin: 0, marginBottom: 16,
        fontFamily: theme.fontDisplay,
        fontSize: 22, lineHeight: 1.2,
        letterSpacing: theme.headingTracking,
        fontWeight: theme.headingWeight, color: theme.heading,
      }}>
        {s.title}
      </h3>
      <ul style={{
        margin: 0, padding: 0, listStyle: "none",
        display: "flex", flexDirection: "column", gap: 8,
        marginBottom: 22, flex: 1,
      }}>
        {s.points.map((p, i) => (
          <li key={i} className="point-item" style={{
            fontFamily: theme.fontBody, fontSize: 13.5, lineHeight: 1.5,
            fontWeight: 500,
            color: theme.body, paddingLeft: 16, position: "relative",
          }}>
            <span className="point-dash" style={{
              position: "absolute", left: 0, top: "0.65em",
              width: 6, height: 1, background: theme.bullet,
              transition: "width 0.2s ease",
            }} />
            {p}
          </li>
        ))}
      </ul>
      <div style={{
        display: "flex", alignItems: "baseline", justifyContent: "space-between",
        paddingTop: 18, borderTop: `1px solid ${theme.divider}`,
      }}>
        <div style={{
          fontFamily: theme.fontDisplay, fontSize: 22,
          fontWeight: theme.headingWeight, color: theme.heading,
          letterSpacing: theme.headingTracking,
        }}>
          {s.price}
        </div>
        <button onClick={() => onPickService(s.id)} className="btn-primary" style={{
          padding: "10px 20px",
          background: theme.btnBg, color: theme.btnFg,
          border: "none", borderRadius: theme.btnRadius,
          fontFamily: theme.fontBody, fontSize: 13, fontWeight: 600,
          letterSpacing: "0.04em", cursor: "pointer",
        }}>
          Записаться
        </button>
      </div>
    </div>
  );
}

function ServicesSection({ theme, onPickService }) {
  const desktop = useIsDesktop();
  return (
    <section id="services" style={{ padding: desktop ? "96px 0 80px" : "72px 0 60px", background: theme.sectionBg }}>
      <div style={{ maxWidth: CONTENT_MAX, margin: "0 auto", padding: "0 24px" }}>
        <div className="reveal" style={{
          fontFamily: theme.fontMono || theme.fontBody,
          fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
          color: theme.eyebrow, marginBottom: 14,
        }}>
          <span className="eyebrow-line">Услуги</span>
        </div>
        <h2 className="reveal reveal-delay-1" style={{
          margin: 0, marginBottom: 36,
          fontFamily: theme.fontDisplay,
          fontSize: desktop ? "clamp(28px, 2.8vw, 42px)" : "clamp(26px, 3.5vw, 36px)",
          lineHeight: 1.1, letterSpacing: theme.headingTracking,
          fontWeight: theme.headingWeight, color: theme.heading,
        }}>
          Что я предлагаю
        </h2>
        <div style={{
          display: "grid",
          gridTemplateColumns: desktop ? "repeat(3, 1fr)" : "repeat(auto-fit, minmax(240px, 1fr))",
          gap: desktop ? 24 : 18,
        }}>
          {SERVICES.map((s, i) => (
            <ServiceCard key={s.id} s={s} theme={theme} onPickService={onPickService} delay={i + 1} />
          ))}
        </div>
      </div>
    </section>
  );
}

// ── About ────────────────────────────────────────────────────────────────────
function AboutSection({ theme }) {
  const desktop = useIsDesktop();
  const NUMS = ["7", "11", "22", "3", "9"];
  return (
    <>
      <GoldDivider />
      <section id="about" style={{ padding: desktop ? "88px 0" : "64px 0", background: theme.aboutBg }}>
        <div style={{ maxWidth: CONTENT_MAX, margin: "0 auto", padding: "0 24px" }}>
          <div className="about-grid" style={{
            display: "grid",
            gridTemplateColumns: desktop ? "1fr 1fr" : "1fr",
            gap: desktop ? "0 64px" : 0,
            alignItems: "center",
          }}>
            {/* Текст */}
            <div>
              <div className="reveal" style={{
                fontFamily: theme.fontMono || theme.fontBody,
                fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
                color: theme.eyebrow, marginBottom: 14,
              }}>
                <span className="eyebrow-line">Обо мне</span>
              </div>
              <h2 className="reveal reveal-delay-1" style={{
                margin: 0, marginBottom: 24,
                fontFamily: theme.fontDisplay,
                fontSize: desktop ? "clamp(28px, 2.8vw, 40px)" : "clamp(24px, 3vw, 32px)",
                lineHeight: 1.15, letterSpacing: theme.headingTracking,
                fontWeight: theme.headingWeight, color: theme.heading,
              }}>
                Я — Нурия
              </h2>
              <p className="reveal reveal-delay-2" style={{
                margin: 0, fontFamily: theme.fontBody,
                fontSize: 16, lineHeight: 1.8,
                color: theme.body,
              }}>
                Практикующий нумеролог и специалист по символизму. Провожу консультации,
                которые помогают улучшить качество жизни. Работаю исключительно по запросу
                клиента — индивидуально, онлайн, без шаблонов.
              </p>
            </div>

            {/* Декоративные числа — только десктоп */}
            {desktop && (
              <div className="reveal reveal-delay-2 desktop-only" style={{
                display: "flex", flexWrap: "wrap", gap: 16,
                justifyContent: "center", alignItems: "center",
                padding: "24px 0",
              }}>
                {NUMS.map((n, i) => (
                  <div key={i} style={{
                    fontFamily: theme.fontDisplay,
                    fontSize: i % 2 === 0 ? 88 : 64,
                    fontWeight: 600,
                    lineHeight: 1,
                    color: i === 0 ? "rgba(63,113,80,0.18)"
                         : i === 1 ? "rgba(63,113,80,0.12)"
                         : i === 2 ? "rgba(63,113,80,0.22)"
                         : "rgba(63,113,80,0.10)",
                    userSelect: "none",
                    letterSpacing: "-0.04em",
                  }}>
                    {n}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </section>
      <GoldDivider />
    </>
  );
}

// ── Form ─────────────────────────────────────────────────────────────────────
const labelStyle = (theme) => ({
  display: "block", marginBottom: 8,
  fontFamily: theme.fontMono || theme.fontBody,
  fontSize: 11, letterSpacing: "0.15em", textTransform: "uppercase",
  color: theme.eyebrow,
});

function FormSection({ theme, selectedService, setSelectedService }) {
  const desktop = useIsDesktop();
  const [name, setName]         = React.useState("");
  const [phone, setPhone]       = React.useState("");
  const [consentData, setConsentData]   = React.useState(false);
  const [consentMail, setConsentMail]   = React.useState(false);
  const [status, setStatus]     = React.useState("idle");
  const [errMsg, setErrMsg]     = React.useState("");

  const TG_TOKEN   = window.NURIA_TG_TOKEN   || "";
  const TG_CHAT_ID = window.NURIA_TG_CHAT_ID || "";

  const onSubmit = async (e) => {
    e.preventDefault();
    const digits = phone.replace(/\D/g, "");
    if (!name.trim() || digits.length < 11) {
      setStatus("error");
      setErrMsg("Заполните имя и телефон");
      return;
    }
    if (!consentData) {
      setStatus("error");
      setErrMsg("Необходимо согласие на обработку персональных данных");
      return;
    }
    setStatus("sending");
    setErrMsg("");
    try {
      const serviceLabel = SERVICES.find((s) => s.id === selectedService)?.title || selectedService;
      if (TG_TOKEN && TG_CHAT_ID) {
        await sendToTelegram({ token: TG_TOKEN, chatId: TG_CHAT_ID, name: name.trim(), phone: "+996 " + phone, service: serviceLabel });
      } else {
        await new Promise((r) => setTimeout(r, 800));
      }
      setStatus("sent");
    } catch (err) {
      setStatus("error");
      setErrMsg(err.message || "Не удалось отправить");
    }
  };

  const inputStyle = {
    width: "100%", padding: "14px 16px",
    fontFamily: theme.fontBody, fontSize: 15,
    color: theme.heading, background: theme.inputBg,
    border: `1px solid ${theme.inputBorder}`,
    borderRadius: theme.inputRadius,
    transition: "border-color 0.2s ease, box-shadow 0.2s ease",
    boxSizing: "border-box",
  };

  return (
    <section id="form-section" style={{ padding: desktop ? "96px 0" : "72px 0", background: theme.formBg }}>
      <div style={{ maxWidth: CONTENT_MAX, margin: "0 auto", padding: "0 24px" }}>
        <div className="form-grid" style={{
          display: "grid",
          gridTemplateColumns: desktop ? "1fr 1fr" : "1fr",
          gap: desktop ? "0 72px" : 0,
          alignItems: "start",
        }}>

        {/* Левая колонка — заголовок + описание */}
        <div style={{ paddingTop: desktop ? 8 : 0 }}>
          <div className="reveal" style={{
            fontFamily: theme.fontMono || theme.fontBody,
            fontSize: 11, letterSpacing: "0.2em", textTransform: "uppercase",
            color: theme.eyebrow, marginBottom: 14,
          }}>
            <span className="eyebrow-line">Консультация</span>
          </div>
          <h2 className="reveal reveal-delay-1" style={{
            margin: 0, marginBottom: 20,
            fontFamily: theme.fontDisplay,
            fontSize: desktop ? "clamp(28px, 2.8vw, 42px)" : "clamp(24px, 3vw, 32px)",
            lineHeight: 1.1, letterSpacing: theme.headingTracking,
            fontWeight: theme.headingWeight, color: theme.heading,
          }}>
            Записаться на консультацию
          </h2>
          <div>
              <p style={{
                margin: "0 0 32px", fontFamily: theme.fontBody,
                fontSize: 15, lineHeight: 1.75, color: theme.body,
              }}>
                Оставьте имя и номер телефона — я свяжусь с вами в ближайшее время и согласую удобный формат.
              </p>
              <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                {["Индивидуальный подход", "Онлайн или аудио", "Ответ в течение дня"].map((item) => (
                  <div key={item} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                    <div style={{
                      width: 24, height: 24, borderRadius: "50%",
                      background: theme.aboutBg, flexShrink: 0,
                      display: "flex", alignItems: "center", justifyContent: "center",
                    }}>
                      <svg width="12" height="10" viewBox="0 0 12 10" fill="none">
                        <path d="M1 5l3.5 3.5L11 1" stroke={theme.eyebrow} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                      </svg>
                    </div>
                    <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.body }}>{item}</span>
                  </div>
                ))}
              </div>
          </div>
        </div>

        {/* Правая колонка — форма */}
        <div>
        {status === "sent" ? (
          <div className="reveal visible" style={{
            padding: "32px 26px", maxWidth: 480,
            background: theme.cardBg, border: theme.cardBorder,
            borderRadius: theme.cardRadius, textAlign: "center",
            boxShadow: "0 8px 32px rgba(63,113,80,0.12)",
          }}>
            <div style={{
              width: 52, height: 52, borderRadius: "50%",
              margin: "0 auto 18px",
              display: "flex", alignItems: "center", justifyContent: "center",
              background: theme.successBg, color: theme.successFg,
              boxShadow: "0 4px 16px rgba(63,113,80,0.32)",
            }}>
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 13l4 4L19 7"/>
              </svg>
            </div>
            <h3 style={{
              margin: 0, marginBottom: 8,
              fontFamily: theme.fontDisplay, fontSize: 22,
              color: theme.heading, fontWeight: theme.headingWeight,
              letterSpacing: theme.headingTracking,
            }}>
              Заявка отправлена
            </h3>
            <p style={{ margin: 0, fontFamily: theme.fontBody, fontSize: 14, lineHeight: 1.6, color: theme.body }}>
              Я свяжусь с вами в ближайшее время.
            </p>
          </div>
        ) : (
          <form className="consult-form-card reveal reveal-delay-2" onSubmit={onSubmit}
            style={{ display: "flex", flexDirection: "column", gap: 16, maxWidth: 480, padding: desktop ? "30px 28px" : "22px 18px" }}>

            {/* Имя */}
            <div>
              <label style={labelStyle(theme)}>Имя</label>
              <input type="text" value={name} onChange={(e) => setName(e.target.value)}
                placeholder="Ваше имя" className="form-input" style={inputStyle} />
            </div>

            {/* Телефон */}
            <div>
              <label style={labelStyle(theme)}>Телефон</label>
              <input
                type="tel"
                value={phone}
                onChange={(e) => setPhone(e.target.value)}
                placeholder="+996 700 000 000"
                className="form-input"
                style={inputStyle}
              />
            </div>

            {/* Услуга */}
            <div>
              <label style={labelStyle(theme)}>Услуга</label>
              <CustomSelect
                value={selectedService}
                onChange={setSelectedService}
                theme={theme}
                inputStyle={inputStyle}
                options={SERVICES.map((s) => ({
                  value: s.id,
                  label: `${s.title} — ${s.price}`,
                  title: s.title,
                  meta: s.meta,
                  price: s.price,
                }))}
              />
            </div>

            {/* Чекбоксы согласия */}
            <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 4,
              fontFamily: theme.fontBody, color: theme.body }}>
              <Checkbox checked={consentData} onChange={setConsentData}>
                Я даю согласие на обработку персональных данных в соответствии с{" "}
                <a href="#" className="checkbox-link">политикой конфиденциальности</a>
              </Checkbox>
              <Checkbox checked={consentMail} onChange={setConsentMail}>
                Я даю согласие на получение рассылок и рекламных материалов
              </Checkbox>
            </div>

            {status === "error" && errMsg && (
              <div style={{
                padding: "10px 14px", fontFamily: theme.fontBody, fontSize: 13,
                color: "#b91c1c", background: "#fef2f2",
                borderRadius: 8, border: "1px solid #fecaca",
              }}>
                {errMsg}
              </div>
            )}

            <button type="submit" disabled={status === "sending"} className="btn-primary" style={{
              marginTop: 4, padding: "16px 24px",
              background: theme.btnBg, color: theme.btnFg,
              border: "none", borderRadius: theme.btnRadius,
              fontFamily: theme.fontBody, fontSize: 14, fontWeight: 600,
              letterSpacing: "0.05em",
              cursor: status === "sending" ? "wait" : "pointer",
              opacity: status === "sending" ? 0.6 : 1,
            }}>
              {status === "sending" ? "Отправка..." : "Отправить"}
            </button>
          </form>
        )}
        </div> {/* /right col */}
        </div> {/* /form-grid */}
      </div>
    </section>
  );
}

// ── Footer ───────────────────────────────────────────────────────────────────
function Footer({ theme }) {
  const DARK_BG   = "#1a2e22";
  const DARK_TEXT = "rgba(255,255,255,0.9)";
  const DARK_MUTED = "rgba(255,255,255,0.5)";
  const DARK_ICON  = "rgba(255,255,255,0.85)";
  const DARK_BORDER = "rgba(255,255,255,0.15)";

  const SOCIALS = [
    { href: "https://instagram.com/NURIA_IG", icon: <IconInstagram size={19} color={DARK_ICON} />, label: "Instagram" },
    { href: "https://wa.me/996700000000",     icon: <IconWhatsApp  size={19} color={DARK_ICON} />, label: "WhatsApp"  },
  ];

  const LEGAL = [
    { label: "Публичная оферта",                      href: "#" },
    { label: "Политика конфиденциальности",           href: "#" },
    { label: "Согласие на обработку данных",          href: "#" },
    { label: "Согласие на получение рассылок",        href: "#" },
  ];

  return (
    <footer style={{ background: DARK_BG, padding: "56px 0 40px" }}>
      <div style={{ maxWidth: CONTENT_MAX, margin: "0 auto", padding: "0 24px" }}>
        <div style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: "40px 48px",
          marginBottom: 40,
          paddingBottom: 40,
          borderBottom: `1px solid ${DARK_BORDER}`,
        }}>
          {/* Левая колонка — контакты */}
          <div>
            <div style={{
              fontFamily: theme.fontDisplay, fontSize: 22,
              fontWeight: theme.headingWeight, color: DARK_TEXT,
              marginBottom: 20, letterSpacing: theme.headingTracking,
            }}>
              Контакты
            </div>
            <div style={{ fontFamily: theme.fontBody, fontSize: 15, color: DARK_TEXT, marginBottom: 6 }}>
              + 996 700 000 000
            </div>
            <div style={{ fontFamily: theme.fontBody, fontSize: 14, color: DARK_MUTED, marginBottom: 24 }}>
              nuria@numerolog.kg
            </div>
            <div style={{ display: "flex", gap: 12 }}>
              {SOCIALS.map((s) => (
                <a key={s.label} href={s.href} target="_blank" rel="noopener"
                  aria-label={s.label} className="social-icon"
                  style={{
                    width: 42, height: 42, borderRadius: "50%",
                    border: `1.5px solid ${DARK_BORDER}`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                    color: DARK_ICON, textDecoration: "none",
                    transition: "border-color 0.2s ease, background 0.2s ease",
                  }}>
                  {s.icon}
                </a>
              ))}
            </div>
          </div>

          {/* Правая колонка — юридические ссылки */}
          <div>
            <div style={{
              fontFamily: theme.fontBody, fontSize: 11,
              letterSpacing: "0.2em", textTransform: "uppercase",
              color: DARK_MUTED, marginBottom: 18,
            }}>
              Документы
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {LEGAL.map((l) => (
                <a key={l.label} href={l.href}
                  style={{
                    fontFamily: theme.fontBody, fontSize: 13.5,
                    color: DARK_MUTED, textDecoration: "underline",
                    textUnderlineOffset: "3px",
                    textDecorationColor: "rgba(255,255,255,0.2)",
                    transition: "color 0.2s ease",
                  }}
                  onMouseEnter={(e) => e.target.style.color = DARK_TEXT}
                  onMouseLeave={(e) => e.target.style.color = DARK_MUTED}
                >
                  {l.label}
                </a>
              ))}
            </div>
          </div>
        </div>

        {/* Низ футера */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          flexWrap: "wrap", gap: 12,
        }}>
          <div style={{ fontFamily: "Georgia, serif", fontSize: 18, color: "rgba(255,255,255,0.2)" }}>
            ✦
          </div>
          <div style={{ fontFamily: theme.fontBody, fontSize: 12, color: DARK_MUTED }}>
            Нурия — нумеролог © 2026
          </div>
        </div>
      </div>
    </footer>
  );
}

// ── Root ─────────────────────────────────────────────────────────────────────
function NumerologistSite({ theme }) {
  const [selectedService, setSelectedService] = React.useState("consult");

  useReveal();

  const onPickService = (id) => {
    setSelectedService(id);
    document.getElementById("form-section")?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <div style={{ background: theme.pageBg, color: theme.body, fontFamily: theme.fontBody }}>
      <Navbar theme={theme} />
      <Hero theme={theme} />
      <ServicesSection theme={theme} onPickService={onPickService} />
      <AboutSection theme={theme} />
      <FormSection theme={theme} selectedService={selectedService} setSelectedService={setSelectedService} />
      <Footer theme={theme} />
    </div>
  );
}

Object.assign(window, { NumerologistSite, SERVICES });
