/* ===========================================================
   RealListener — shared helpers + top sections
   =========================================================== */
const { useState, useEffect, useRef, useCallback } = React;

/* ---- scroll reveal ---- */
function Reveal({ children, delay = 0, as = "div", className = "", style = {}, ...rest }) {
  const ref = useRef(null);
  const [seen, setSeen] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => { if (e.isIntersecting) { setSeen(true); io.disconnect(); } });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);
  const Tag = as;
  return (
    <Tag
      ref={ref}
      className={`reveal ${seen ? "in" : ""} ${className}`}
      style={{ transitionDelay: seen ? `${delay}ms` : "0ms", ...style }}
      {...rest}
    >
      {children}
    </Tag>
  );
}

/* ---- crescent moon mark ---- */
function Moon({ size = 22, id = "m" }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true" style={{ display: "block" }}>
      <defs>
        <mask id={`moonmask-${id}`}>
          <rect width="24" height="24" fill="white" />
          <circle cx="16.5" cy="9" r="9.4" fill="black" />
        </mask>
      </defs>
      <circle cx="11" cy="12" r="9.4" fill="currentColor" mask={`url(#moonmask-${id})`} />
    </svg>
  );
}

/* ---- smooth scroll to id ---- */
function scrollToId(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.scrollY - 76;
  window.scrollTo({ top: y, behavior: "smooth" });
}

/* ---- section heading block ---- */
function SectionHead({ eyebrow, title, intro, align = "left", maxIntro = 560 }) {
  const center = align === "center";
  return (
    <div style={{ maxWidth: center ? 720 : "none", margin: center ? "0 auto" : 0, textAlign: center ? "center" : "left" }}>
      {eyebrow && <Reveal as="p" className="eyebrow" style={{ marginBottom: 18 }}>{eyebrow}</Reveal>}
      <Reveal as="h2" delay={60} style={{ fontSize: "clamp(2rem, 4.2vw, 3rem)", maxWidth: 720, marginInline: center ? "auto" : 0 }}>
        {title}
      </Reveal>
      {intro && (
        <Reveal as="p" delay={120} style={{ marginTop: 18, color: "var(--text-mut)", fontSize: "1.08rem", maxWidth: maxIntro, marginInline: center ? "auto" : 0 }}>
          {intro}
        </Reveal>
      )}
    </div>
  );
}

/* ===========================================================
   NAV
   =========================================================== */
function Nav({ theme, onToggleTheme }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const links = [
    ["How it works", "how"],
    ["Who it's for", "who"],
    ["Pricing", "pricing"],
    ["Trust", "trust"],
    ["FAQ", "faq"],
  ];

  return (
    <header
      style={{
        position: "fixed", top: 0, left: 0, right: 0, zIndex: 50,
        transition: "background-color .4s ease, border-color .4s ease, backdrop-filter .4s ease, box-shadow .4s ease",
        background: scrolled ? "color-mix(in oklab, var(--bg) 80%, transparent)" : "transparent",
        backdropFilter: scrolled ? "blur(16px) saturate(1.2)" : "none",
        WebkitBackdropFilter: scrolled ? "blur(16px) saturate(1.2)" : "none",
        borderBottom: `1px solid ${scrolled ? "var(--border)" : "transparent"}`,
      }}
    >
      <div className="wrap" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", height: 70 }}>
        <a href="#top" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: "smooth" }); }}
           style={{ display: "flex", alignItems: "center", gap: 10, fontFamily: "var(--serif)", fontSize: "1.32rem", letterSpacing: "-0.02em", color: "var(--text)" }}>
          <span style={{ color: "var(--accent)" }}><Moon size={21} id="nav" /></span>
          <span>Real<span style={{ color: "var(--text-soft)" }}>Listener</span></span>
        </a>

        <nav className="nav-links" style={{ display: "flex", alignItems: "center", gap: 30 }}>
          {links.map(([label, id]) => (
            <a key={id} href={`#${id}`} onClick={(e) => { e.preventDefault(); scrollToId(id); }}
               className="navlink"
               style={{ fontSize: "0.92rem", color: "var(--text-mut)", fontWeight: 500, transition: "color .25s ease" }}
               onMouseEnter={(e) => (e.currentTarget.style.color = "var(--text)")}
               onMouseLeave={(e) => (e.currentTarget.style.color = "var(--text-mut)")}>
              {label}
            </a>
          ))}
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <ThemeToggle theme={theme} onToggle={onToggleTheme} />
          <button className="btn btn-primary btn-sm cta-nav" onClick={() => scrollToId("pricing")}>
            Book a trial
          </button>
          <button className="menu-btn" aria-label="Menu" onClick={() => setOpen((v) => !v)}
            style={{ display: "none", background: "transparent", border: "1px solid var(--border-hi)", borderRadius: 10, width: 40, height: 38, color: "var(--text)", flexDirection: "column", gap: 4, alignItems: "center", justifyContent: "center" }}>
            <span style={{ width: 16, height: 1.5, background: "currentColor", borderRadius: 2 }}></span>
            <span style={{ width: 16, height: 1.5, background: "currentColor", borderRadius: 2 }}></span>
          </button>
        </div>
      </div>

      {open && (
        <div className="wrap" style={{ paddingBottom: 18, display: "flex", flexDirection: "column", gap: 4 }}>
          {links.map(([label, id]) => (
            <a key={id} href={`#${id}`} onClick={(e) => { e.preventDefault(); setOpen(false); scrollToId(id); }}
               style={{ padding: "10px 4px", color: "var(--text-soft)", borderBottom: "1px solid var(--border)" }}>{label}</a>
          ))}
        </div>
      )}
    </header>
  );
}

function ThemeToggle({ theme, onToggle }) {
  const dark = theme === "dark";
  return (
    <button
      onClick={onToggle}
      aria-label={dark ? "Switch to light mode" : "Switch to dark mode"}
      title={dark ? "Switch to light" : "Switch to dark"}
      style={{
        width: 42, height: 38, borderRadius: 11, background: "transparent",
        border: "1px solid var(--border-hi)", color: "var(--text-soft)",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        transition: "color .25s, border-color .25s, background-color .25s",
      }}
      onMouseEnter={(e) => { e.currentTarget.style.color = "var(--accent)"; e.currentTarget.style.borderColor = "var(--accent-line)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.color = "var(--text-soft)"; e.currentTarget.style.borderColor = "var(--border-hi)"; }}
    >
      {dark ? <Moon size={16} id="toggle" /> : (
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">
          <circle cx="12" cy="12" r="4.2" />
          <path d="M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6L17 7M7 17l-1.4 1.4" />
        </svg>
      )}
    </button>
  );
}

/* ===========================================================
   HERO
   =========================================================== */
function Hero() {
  const bullets = ["No account needed", "Book in under 2 minutes", "Real person, not AI"];
  return (
    <section id="top" style={{ paddingTop: "clamp(130px, 18vh, 200px)", paddingBottom: "var(--sect)" }}>
      <div className="wrap" style={{ textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center" }}>
        <Reveal as="p" className="eyebrow" style={{ marginBottom: 24 }}>No app. No AI. No awkwardness.</Reveal>

        <Reveal as="h1" delay={70}
          style={{ fontSize: "clamp(2.6rem, 6.6vw, 5rem)", lineHeight: 1.08, letterSpacing: "-0.022em" }}>
          Talk to a real person <br className="hide-sm" /><em style={{ color: "var(--accent)" }}>tonight.</em>
        </Reveal>

        <Reveal as="p" delay={150}
          style={{ marginTop: 26, fontSize: "clamp(1.05rem, 1.7vw, 1.28rem)", color: "var(--text-soft)", maxWidth: 600, lineHeight: 1.62 }}>
          Sometimes you don't want to burden the people you know. That's what we're here for.
        </Reveal>

        <Reveal delay={230} style={{ marginTop: 38, display: "flex", gap: 14, flexWrap: "wrap", justifyContent: "center" }}>
          <button className="btn btn-primary" onClick={() => scrollToId("pricing")} style={{ fontSize: "1.02rem", padding: "1em 1.7em" }}>
            Talk to someone tonight — $15 <span className="arrow">→</span>
          </button>
          <button className="btn btn-ghost" onClick={() => scrollToId("pricing")} style={{ fontSize: "1.02rem", padding: "1em 1.7em" }}>
            See pricing
          </button>
        </Reveal>

        <Reveal delay={360} style={{ marginTop: 28, display: "flex", gap: "10px 30px", flexWrap: "wrap", justifyContent: "center" }}>
          {bullets.map((b) => (
            <span key={b} style={{ display: "inline-flex", alignItems: "center", gap: 9, color: "var(--text-mut)", fontSize: "0.92rem", fontWeight: 500 }}>
              <span style={{ width: 5, height: 5, borderRadius: 99, background: "var(--accent)", boxShadow: "0 0 10px var(--accent-line)" }}></span>
              {b}
            </span>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

/* ===========================================================
   HOW IT WORKS
   =========================================================== */
function HowItWorks() {
  const steps = [
    ["Choose your preferences", "Tell us who you want to talk to and how — voice or text, man or woman, your style. Takes 30 seconds."],
    ["Book in minutes", "Pick a session length and a time that works for tonight."],
    ["Talk. Actually talk.", "A real person picks up. No script, no AI. Just a calm, present human on the other end."],
  ];
  return (
    <section id="how" style={{ paddingTop: "var(--sect)", paddingBottom: "var(--sect)" }}>
      <div className="wrap">
        <SectionHead eyebrow="How it works" title={<>Three steps. That's it.</>} intro="No account. No friction." />
        <div style={{ marginTop: 64, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(250px, 1fr))", gap: 26 }}>
          {steps.map(([t, d], i) => (
            <Reveal key={i} delay={i * 110} className="card" style={{ padding: "34px 30px 32px" }}>
              <div style={{ display: "flex", alignItems: "baseline", gap: 14, marginBottom: 18 }}>
                <span style={{ fontFamily: "var(--serif)", fontSize: "2.2rem", color: "var(--accent)", lineHeight: 1, fontWeight: 500 }}>
                  0{i + 1}
                </span>
                <span style={{ flex: 1, height: 1, background: "var(--border)", transform: "translateY(-6px)" }}></span>
              </div>
              <h3 style={{ fontSize: "1.4rem", marginBottom: 12 }}>{t}</h3>
              <p style={{ color: "var(--text-mut)", fontSize: "1rem" }}>{d}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ===========================================================
   WHO IT'S FOR
   =========================================================== */
function WhoItsFor() {
  const cards = [
    ["Lonely evenings", "When the silence gets loud and you'd rather talk than scroll."],
    ["Stress after work", "When you need to offload the day to someone who actually listens."],
    ["Breakups and rough days", "When you need presence, not pressure."],
    ["Living alone", "When your day ends and there's no one to tell it to."],
    ["Remote work fatigue", "Busy inbox, zero real conversation. You know the feeling."],
    ["Big life transitions", "Change, uncertainty, a new city — sometimes you just need a steady voice."],
  ];
  return (
    <section id="who" style={{ paddingTop: "var(--sect)", paddingBottom: "var(--sect)" }}>
      <div className="wrap">
        <SectionHead eyebrow="Who it's for" title={<>You don't have to <em>explain why</em></>} />
        <div style={{ marginTop: 56, display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))", gap: 20 }}>
          {cards.map(([t, d], i) => (
            <Reveal key={i} delay={(i % 3) * 90} className="card moment-card" style={{ padding: "30px 28px" }}>
              <span className="moment-bar" style={{ display: "block", width: 26, height: 2, background: "var(--accent-line)", marginBottom: 20, transition: "width .4s cubic-bezier(.2,.7,.3,1), background-color .4s" }}></span>
              <h3 style={{ fontSize: "1.28rem", marginBottom: 11 }}>{t}</h3>
              <p style={{ color: "var(--text-mut)", fontSize: "0.98rem" }}>{d}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ===========================================================
   MATCHING / PREFERENCES  (interactive)
   =========================================================== */
const MATCH_GROUPS = [
  { key: "gender", label: "Prefer to talk to", options: ["Woman", "Man", "No preference"] },
  { key: "age", label: "Age range", options: ["20s", "30s", "40+"] },
  { key: "style", label: "Conversation style", options: ["Calm listener", "Friendly and upbeat", "Mature and grounded", "Motivating"] },
  { key: "format", label: "Format", options: ["Voice call", "Text chat"] },
  { key: "language", label: "Language", options: ["English", "Spanish"] },
];

function Matching() {
  const [sel, setSel] = useState({ gender: "No preference", age: "30s", style: "Calm listener", format: "Voice call", language: "English" });
  const pick = (k, v) => setSel((s) => ({ ...s, [k]: v }));

  const fmt = sel.format === "Voice call" ? "a voice call" : "a text chat";
  const who = sel.gender === "No preference" ? "a listener" : `a ${sel.gender.toLowerCase()}`;

  return (
    <section id="matching" style={{ paddingTop: "var(--sect)", paddingBottom: "var(--sect)" }}>
      <div className="wrap">
        <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr)", gap: 48 }}>
          <SectionHead
            eyebrow="Your preferences"
            title={<>You're in control of <em>how it feels</em></>}
            intro="Voice or text. Man or woman. Your pace, your style."
          />

          <Reveal className="card" style={{ padding: "clamp(24px, 3vw, 40px)" }}>
            <div style={{ display: "grid", gap: 28 }}>
              {MATCH_GROUPS.map((g) => (
                <div key={g.key}>
                  <p style={{ fontSize: "0.78rem", fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-faint)", marginBottom: 13 }}>
                    {g.label}
                  </p>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
                    {g.options.map((opt) => {
                      const active = sel[g.key] === opt;
                      return (
                        <button key={opt} onClick={() => pick(g.key, opt)} className="chip" data-active={active}
                          style={{
                            fontFamily: "var(--sans)", fontSize: "0.95rem", fontWeight: 500,
                            padding: "0.62em 1.1em", borderRadius: 999,
                            border: `1px solid ${active ? "var(--accent)" : "var(--border-hi)"}`,
                            background: active ? "var(--accent-tint)" : "transparent",
                            color: active ? "var(--text)" : "var(--text-mut)",
                            boxShadow: active ? "inset 0 0 0 1px var(--accent-line)" : "none",
                            whiteSpace: "nowrap",
                            transition: "all .25s cubic-bezier(.2,.7,.3,1)",
                          }}>
                          {opt}
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>

            <hr className="hair" style={{ margin: "30px 0 24px" }} />

            <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: 18 }}>
              <p style={{ color: "var(--text-soft)", fontSize: "1.02rem", maxWidth: 460, lineHeight: 1.5 }}>
                You'd be matched with <strong style={{ color: "var(--text)", fontWeight: 600 }}>{who}</strong> in their{" "}
                <strong style={{ color: "var(--text)", fontWeight: 600 }}>{sel.age}</strong>, a{" "}
                <strong style={{ color: "var(--text)", fontWeight: 600 }}>{sel.style.toLowerCase()}</strong>, over{" "}
                <strong style={{ color: "var(--text)", fontWeight: 600 }}>{fmt}</strong>.
              </p>
              <button className="btn btn-primary" onClick={() => scrollToId("pricing")}>
                Continue to pricing <span className="arrow">→</span>
              </button>
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}

window.NT = Object.assign(window.NT || {}, {
  Reveal, Moon, scrollToId, SectionHead, Nav, Hero, HowItWorks, WhoItsFor, Matching,
});
