/* global React, ReactDOM, useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakColor, TweakButton */
const { useState, useEffect, useRef } = React;

// Tweak defaults live in the root HTML (window.TWEAK_DEFAULTS) so the host
// can persist user edits to disk. Fall back to a literal here just in case
// the inline script didn't run.
const TWEAK_DEFAULTS = window.TWEAK_DEFAULTS || {
  "vibe": "editorial",
  "hero": "minimal",
  "typePair": "A",
  "menu": "list",
  "nav": "top"
};

const VIBES = [
  { id: "editorial", label: "Editorial · Beige" },
  { id: "coastal",   label: "Coastal · Dune" },
  { id: "spa",       label: "Spa · Mocha" },
  { id: "wellness",  label: "Wellness · Modern" },
  { id: "sky",       label: "Sky · Light Blue" },
  { id: "white",     label: "Minimal · Pure White" },
  { id: "tide",      label: "Tide · Alternating Blue" },
];
const HEROES = [
  { id: "minimal",   label: "Minimal · centered" },
  { id: "fullbleed", label: "Full-bleed photo" },
  { id: "split",     label: "Split · copy + photo" },
  { id: "editorial", label: "Editorial · magazine" },
];
const TYPE_PAIRS = [
  { id: "A", label: "Cormorant + Manrope" },
  { id: "B", label: "Lora + DM Sans" },
  { id: "C", label: "Playfair + Jost" },
];
const MENUS = [
  { id: "list",     label: "List · newspaper" },
  { id: "cards",    label: "Cards · grid" },
  { id: "magazine", label: "Magazine · alternating" },
];
const NAVS = [
  { id: "top",     label: "Top bar" },
  { id: "side",    label: "Side rail" },
  { id: "minimal", label: "Minimal · floating" },
];

// ─── Preloader ─────────────────────────────────────────────────────────────
// Full-screen overlay that plays the animated logo on first load.
// Auto-dismisses after the logo's "hands-open" choreography completes.
// Persisted in sessionStorage so it doesn't replay on every nav within the session.
function Preloader() {
  const [phase, setPhase] = useState("show");

  useEffect(() => {
    if (phase !== "show") return;
    // Logo enter ≈ 2.05s. Hold a beat, then fade out (~0.7s).
    const fade = setTimeout(() => setPhase("fading"), 2700);
    const done = setTimeout(() => {
      setPhase("hidden");
      try { sessionStorage.setItem("vitalia-preloader-seen-v2", "1"); } catch (e) {}
    }, 4200);
    // Lock body scroll while overlay is up
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      clearTimeout(fade);
      clearTimeout(done);
      document.body.style.overflow = prev;
    };
  }, [phase]);

  if (phase === "hidden") return null;
  return (
    <div
      className={"preloader" + (phase === "fading" ? " is-fading" : "")}
      onClick={() => setPhase("fading")}
      role="presentation"
    >
      <AnimatedHeroLogo
        size={Math.min(520, typeof window !== "undefined" ? window.innerWidth * 0.72 : 480)}
      />
    </div>
  );
}

// ─── Hero variants ─────────────────────────────────────────────────────────
function Hero({ variant }) {
  if (variant === "fullbleed") return <HeroFullbleed />;
  if (variant === "split")     return <HeroSplit />;
  if (variant === "editorial") return <HeroEditorial />;
  return <HeroMinimal />;
}

function HeroMinimal() {
  return (
    <section className="hero hero-minimal hero-minimal-bare" data-screen-label="Hero · Minimal">
      <div className="hero-mark" style={{ display: "flex", justifyContent: "center" }}>
        <AnimatedHeroLogo size={Math.min(560, typeof window !== "undefined" ? window.innerWidth * 0.78 : 520)} />
      </div>
    </section>
  );
}

function HeroFullbleed() {
  return (
    <section className="hero hero-fullbleed" data-screen-label="Hero · Full-bleed">
      <Photo
        label="Hero photo · hands at work"
        src="assets/photos/work-shoulder-energy.webp"
        position="center"
      />
      <div className="hero-content">
        <div className="eyebrow" style={{ justifyContent: "center" }}>Montauk · NY</div>
        <h1 className="serif">VITALIA</h1>
        <div className="hero-sub">Massage Therapy</div>
        <p className="hero-tag">
          The feeling of rejuvenation, kept on a quiet street in Montauk.
        </p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <a className="btn btn-primary" href="https://www.vitaliamassage.com/" target="_blank" rel="noopener">
            Book a Session <span className="btn-arrow">→</span>
          </a>
          <a className="btn" href="#services">The Menu</a>
        </div>
      </div>
      <div className="scroll-cue">
        <span>Scroll</span>
        <span className="scroll-line" />
      </div>
    </section>
  );
}

function HeroSplit() {
  return (
    <section className="hero hero-split" data-screen-label="Hero · Split">
      <div className="hero-split-copy">
        <Logo className="hero-mark" />
        <div className="eyebrow">Massage Therapy · Est. 2021</div>
        <h1 className="serif">
          A nurturing <em>environment</em> for relaxation, recovery, and the quiet work of healing.
        </h1>
        <p className="hero-tag">
          Personalized bodywork from a calm studio in downtown Montauk — Swedish, deep tissue, custom, prenatal,
          sports, and offsite.
        </p>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
          <a className="btn btn-primary" href="https://www.vitaliamassage.com/" target="_blank" rel="noopener">
            Book on Square <span className="btn-arrow">→</span>
          </a>
          <a className="btn" href="#about">About Sophia</a>
        </div>
        <div className="hero-meta">
          <div>Studio<b>Carl Fisher Plaza</b></div>
          <div>Hours<b>Mon — Sat</b></div>
          <div>Reach<b>631·599·8092</b></div>
        </div>
      </div>
      <div className="hero-split-photo">
        <Photo
          label="Studio · hands at work"
          src="assets/photos/work-leaning-lover.webp"
          position="center"
        />
        <div className="photo-tag">Studio · 37 Carl Fisher Plaza</div>
      </div>
    </section>
  );
}

function HeroEditorial() {
  return (
    <section className="hero hero-editorial" data-screen-label="Hero · Editorial">
      <Logo className="hero-mark" />
      <div className="hero-side">
        <div className="eyebrow">Issue Nº 01 · Spring 2026</div>
        <h1 className="serif">
          Massage as a <em>practice</em>, not an appointment.
        </h1>
        <p>
          From a quiet studio in Carl Fisher Plaza, Sophia Foglia, LMT, builds sessions intuitively — Swedish,
          deep tissue, hot stone, cupping, and aromatherapy, drawn from the same toolkit and remixed for the body
          on the table that day.
        </p>
        <div className="hero-actions">
          <a className="btn btn-primary" href="https://www.vitaliamassage.com/" target="_blank" rel="noopener">
            Book a Session <span className="btn-arrow">→</span>
          </a>
          <a className="btn" href="#services">The Menu</a>
        </div>
        <div className="hero-credits">
          <span>Est. 2021</span><span>Montauk · NY</span><span>By Appointment</span>
        </div>
      </div>
    </section>
  );
}

// ─── Nav ───────────────────────────────────────────────────────────────────
function Nav({ navStyle, onMenuOpen }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener("scroll", onScroll);
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  return (
    <nav className={`nav ${scrolled ? "is-scrolled" : ""}`} data-screen-label="Nav">
      <a href="#top" className="nav-brand">
        VITALIA
      </a>

      <div className="nav-links">
        <a href="#about">About</a>
        <a href="#services">Services</a>
        <a href="#modalities">Approach</a>
        <a href="#testimonials">Words</a>
        <a href="#offsite">Offsite</a>
        <a href="#contact">Visit</a>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <button
          className="nav-menu-btn"
          onClick={onMenuOpen}
          aria-label="Open menu"
        >
          <svg width="16" height="12" viewBox="0 0 16 12" fill="none" stroke="currentColor" strokeWidth="1.4">
            <line x1="0" x2="16" y1="2" y2="2" />
            <line x1="0" x2="16" y1="10" y2="10" />
          </svg>
        </button>
        <a className="btn nav-cta" href="https://www.vitaliamassage.com/" target="_blank" rel="noopener">
          Book <span className="btn-arrow">→</span>
        </a>
      </div>
    </nav>
  );
}

function MenuOverlay({ open, onClose }) {
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);
  const links = [
    ["#about", "About", "01"],
    ["#services", "Services", "02"],
    ["#modalities", "Approach", "03"],
    ["#testimonials", "Words", "04"],
    ["#offsite", "Offsite", "05"],
    ["#faq", "FAQ", "06"],
    ["#contact", "Visit", "07"],
  ];
  return (
    <div className={`menu-overlay ${open ? "is-open" : ""}`} onClick={(e) => {
      if (e.target.tagName === "A") onClose();
    }}>
      <button className="menu-close" onClick={onClose} aria-label="Close menu">
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4">
          <line x1="2" y1="2" x2="12" y2="12" /><line x1="12" y1="2" x2="2" y2="12" />
        </svg>
      </button>
      <div className="menu-overlay-grid">
        <div className="menu-overlay-links">
          {links.map(([href, name, n]) => (
            <a key={href} href={href}>
              <span className="serif">{name}</span>
              <span>— {n}</span>
            </a>
          ))}
        </div>
        <div className="menu-overlay-info">
          <div>
            <h4>Studio</h4>
            37 Carl Fisher Plaza<br />Montauk, NY 11954
          </div>
          <div>
            <h4>Reach</h4>
            <a href="tel:6315998092">631·599·8092</a><br />
            <a href="mailto:sophiafoglialmt@gmail.com">sophiafoglialmt@gmail.com</a>
          </div>
          <div>
            <h4>Hours</h4>
            Mon — Sat · By appointment<br />Sunday · Reach out
          </div>
          <a className="btn btn-primary" href="https://www.vitaliamassage.com/" target="_blank" rel="noopener" style={{ marginTop: 8 }}>
            Book on Square <span className="btn-arrow">→</span>
          </a>
        </div>
      </div>
    </div>
  );
}

// ─── Reveal-on-scroll ───────────────────────────────────────────────────────
function useScrollReveal() {
  useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    if (!("IntersectionObserver" in window)) {
      els.forEach((el) => el.classList.add("is-in"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("is-in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

// ─── App ────────────────────────────────────────────────────────────────────
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [menuOpen, setMenuOpen] = useState(false);
  useScrollReveal();

  // Re-run reveal observer when content changes (e.g. menu layout swap)
  useEffect(() => {
    const els = document.querySelectorAll(".reveal:not(.is-in)");
    if (!els.length) return;
    const io = new IntersectionObserver(
      (entries) => entries.forEach((e) => e.isIntersecting && (e.target.classList.add("is-in"), io.unobserve(e.target))),
      { threshold: 0.1 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, [t.menu, t.hero, t.vibe]);

  // Sync vibe + tweak attrs onto <html> so :root-defined CSS vars are properly
  // overridden across the whole document (including body background).
  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute("data-vibe", t.vibe);
    r.setAttribute("data-type-pair", t.typePair);
    r.setAttribute("data-menu", t.menu);
    r.setAttribute("data-nav", t.nav);
  }, [t.vibe, t.typePair, t.menu, t.nav]);

  return (
    <div
      className="page"
      id="top"
      data-vibe={t.vibe}
      data-type-pair={t.typePair}
      data-menu={t.menu}
      data-nav={t.nav}
    >
      <Preloader />
      <Nav navStyle={t.nav} onMenuOpen={() => setMenuOpen(true)} />
      <MenuOverlay open={menuOpen} onClose={() => setMenuOpen(false)} />

      <About />
      <Services />
      <Modalities />
      <Testimonials />
      <Offsite />
      <FAQSection />
      <Contact />
      <Footer />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Vibe" />
        <TweakSelect
          label="Aesthetic"
          value={t.vibe}
          options={VIBES.map((v) => ({ value: v.id, label: v.label }))}
          onChange={(v) => setTweak("vibe", v)}
        />
        <TweakSection label="Layout" />
        <TweakSelect
          label="Hero"
          value={t.hero}
          options={HEROES.map((v) => ({ value: v.id, label: v.label }))}
          onChange={(v) => setTweak("hero", v)}
        />
        <TweakSelect
          label="Services menu"
          value={t.menu}
          options={MENUS.map((v) => ({ value: v.id, label: v.label }))}
          onChange={(v) => setTweak("menu", v)}
        />
        <TweakRadio
          label="Navigation"
          value={t.nav}
          options={NAVS.map((v) => v.id)}
          onChange={(v) => setTweak("nav", v)}
        />
        <TweakSection label="Type" />
        <TweakSelect
          label="Pairing"
          value={t.typePair}
          options={TYPE_PAIRS.map((v) => ({ value: v.id, label: v.label }))}
          onChange={(v) => setTweak("typePair", v)}
        />
      </TweaksPanel>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
