/* ============================================================
 app.jsx - App shell: nav, footer, router, reveal, tweaks
 ============================================================ */
const { useState, useEffect, useRef, useCallback } = React;
const { Arw, Eyebrow, Btn, Brandmark, Wordmark } = window.C;
const { ROUTES, LINKS } = window;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
 "direction": "editorial",
 "accent": "#2C4636",
 "heroMotion": true
}/*EDITMODE-END*/;

/* ---------------- ROUTING ---------------- */
// Real paths (e.g. /space) instead of hash fragments, so each page is an
// independently indexable/citable URL rather than one client-only SPA state.
const ROUTE_META = {
 home: { title: "Ariki Lake House — Built for Teams · Lake Karapiro, Cambridge NZ", description: "A lake house built for teams. Corporate offsites and sports training camps on the shores of Lake Karapiro, Cambridge, New Zealand. Sleeps 32+." },
 space: { title: "The Space — Group Accommodation for 32+ | Ariki Lake House", description: "Rent the entire property for your group. Open the doors between Rangitira and Hydro, add the apartment if you need it - the whole place is yours. Lake Karapiro, Cambridge NZ." },
 gatherings: { title: "Family & Friends Gatherings | Ariki Lake House", description: "Milestone birthdays, anniversaries, reunions and long-overdue weekends - take over the whole house and gather everyone around one table." },
 teams: { title: "Team Training Camps | Ariki Lake House", description: "Sleep the whole team under one roof, recover well, and train on world-class water and roads minutes from the door. Lake Karapiro, Cambridge NZ." },
 corporate: { title: "Corporate Offsites | Ariki Lake House", description: "Leadership resets, strategy days and board retreats on Lake Karapiro. A private whole-house offsite venue for teams, near Cambridge, New Zealand." },
 about: { title: "Our Story | Ariki Lake House", description: "Ariki Lake House was at the heart of the Karapiro Dam build. Today it's a home for teams - same bones, a lot more light." },
 decks: { title: "Team Decks | Ariki Lake House", description: "Plan the whole trip in one place - everything a leader or coach needs to propose and run a trip to Ariki Lake House." },
 enquire: { title: "Enquire | Ariki Lake House", description: "Email us about your group and we'll come back within 24 hours with a tailored package for your stay at Ariki Lake House." },
};

function routePath(id) { return id === "home" ? "/" : "/" + id; }
function routeFromPath(pathname) {
 const id = pathname.replace(/^\/+|\/+$/g, "");
 return id && window.Pages && window.Pages[id] ? id : "home";
}

/* ---------------- NAV ---------------- */
function Nav({ page, go, scrolled, onBurger }) {
 return (
 <header className={`nav ${scrolled ? "scrolled" : ""}`}>
 <a className="nav__brand" href="/" onClick={(e) => { e.preventDefault(); go("home"); }} aria-label="Ariki Lake House - home">
 <Brandmark className="mark" />
 <Wordmark className="word" />
 </a>
 <nav className="nav__links">
 {ROUTES.filter(r => r.id !== "home" && r.id !== "enquire").map(r => (
 <a key={r.id} href={routePath(r.id)} className={page === r.id ? "active" : ""}
 onClick={(e) => { e.preventDefault(); go(r.id); }}>{r.label}</a>
 ))}
 </nav>
 <div className="nav__right">
 <a className="nav__phone" href={`mailto:${LINKS.email}`}>{LINKS.email}</a>
 <a className="btn btn--light" href={LINKS.book} target="_blank" rel="noopener noreferrer">Book Now</a>
 <button className="nav__burger" aria-label="Menu" onClick={onBurger}><span></span><span></span><span></span></button>
 </div>
 </header>
 );
}

function MobileMenu({ open, go, close }) {
 return (
 <div className={`mobilemenu ${open ? "open" : ""}`}>
 <button className="close" onClick={close} aria-label="Close">×</button>
 <nav>
 {ROUTES.map(r => (
 <a key={r.id} href={routePath(r.id)} onClick={(e) => { e.preventDefault(); go(r.id); close(); }}>
 {r.label}<span className="arw">→</span>
 </a>
 ))}
 </nav>
 <div className="mm-foot">
 <a href={LINKS.book} target="_blank" rel="noopener noreferrer">Book Direct</a> · <a href={`mailto:${LINKS.email}`}>{LINKS.email}</a>
 </div>
 </div>
 );
}

/* ---------------- FOOTER ---------------- */
function Footer({ go }) {
 return (
 <footer className="footer">
 <div className="wrap">
 <div className="footer__top">
 <div className="footer__brand">
 <span className="mark mark--footer" aria-hidden="true"></span>
 <p>A lake house built for teams - on the shores of Lake Karapiro, Cambridge, Aotearoa New Zealand.</p>
 </div>
 <div className="footer__col">
 <h5>Explore</h5>
 {ROUTES.filter(r => r.id !== "home").map(r => (
 <a key={r.id} href={routePath(r.id)} onClick={(e) => { e.preventDefault(); go(r.id); }}>{r.label}</a>
 ))}
 </div>
 <div className="footer__col">
 <h5>Visit</h5>
 <p>401 Ariki Street, Karapiro</p>
 <p>Cambridge, New Zealand</p>
 <a href={LINKS.ig} target="_blank" rel="noopener noreferrer">Instagram ↗</a>
 <a href={LINKS.book} target="_blank" rel="noopener noreferrer">Book Direct ↗</a>
 </div>
 <div className="footer__col">
 <h5>Get in touch</h5>
 <a href={`mailto:${LINKS.email}`}>{LINKS.email}</a>
 <a href={LINKS.book} target="_blank" rel="noopener noreferrer">Book Direct ↗</a>
 <Btn onClick={() => go("enquire")} variant="solid" style={{ marginTop: "10px" }}>Enquire <Arw /></Btn>
 </div>
 </div>
 <div className="footer__bottom">
 <span>© {new Date().getFullYear()} Ariki Lake House</span>
 <span><a href={`mailto:${LINKS.email}`}>{LINKS.email}</a></span>
 </div>
 </div>
 </footer>
 );
}

/* ---------------- TWEAKS ---------------- */
function Tweaks({ t, setTweak }) {
 const {
 TweaksPanel, TweakSection, TweakRadio, TweakColor, TweakToggle,
 } = window;
 if (!TweaksPanel) return null;
 return (
 <TweaksPanel>
 <TweakSection label="Visual direction" />
 <TweakRadio label="Direction" value={t.direction}
 options={["editorial", "cinematic", "natural"]}
 onChange={(v) => setTweak("direction", v)} />
 <TweakSection label="Accent" />
 <TweakColor label="Accent colour" value={t.accent}
 options={["#2C4636", "#7EB89A", "#1B2E22", "#B4825C"]}
 onChange={(v) => setTweak("accent", v)} />
 <TweakSection label="Motion" />
 <TweakToggle label="Hero pan (Ken Burns)" value={t.heroMotion}
 onChange={(v) => setTweak("heroMotion", v)} />
 </TweaksPanel>
 );
}

/* ---------------- APP ---------------- */
function App() {
 const useTweaks = window.useTweaks || (() => [TWEAK_DEFAULTS, () => {}]);
 const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
 const [page, setPage] = useState(() => routeFromPath(location.pathname));
 const [scrolled, setScrolled] = useState(false);
 const [menu, setMenu] = useState(false);

 const go = useCallback((id) => {
 setPage(id);
 const path = routePath(id);
 if (location.pathname !== path) history.pushState(null, "", path);
 window.scrollTo({ top: 0, behavior: "auto" });
 }, []);

  // back/forward-button sync
 useEffect(() => {
 const onPop = () => setPage(routeFromPath(location.pathname));
 window.addEventListener("popstate", onPop);
 return () => window.removeEventListener("popstate", onPop);
 }, []);

  // per-route title, meta description & canonical
 useEffect(() => {
 const meta = ROUTE_META[page] || ROUTE_META.home;
 document.title = meta.title;
 const descTag = document.querySelector('meta[name="description"]');
 if (descTag) descTag.setAttribute("content", meta.description);
 const canonicalTag = document.querySelector('link[rel="canonical"]');
 if (canonicalTag) canonicalTag.setAttribute("href", "https://arikilakehouse.co.nz" + routePath(page));
 }, [page]);

  // nav scrolled state
 useEffect(() => {
 const onScroll = () => setScrolled(window.scrollY > 40);
 onScroll();
 window.addEventListener("scroll", onScroll, { passive: true });
 return () => window.removeEventListener("scroll", onScroll);
 }, []);

  // apply theme + accent + motion to <html>
 useEffect(() => {
 const r = document.documentElement;
 r.setAttribute("data-theme", t.direction || "editorial");
 if (t.accent) { r.style.setProperty("--accent", t.accent); }
 else { r.style.removeProperty("--accent"); }
 r.classList.toggle("no-heromotion", !t.heroMotion);
 }, [t.direction, t.accent, t.heroMotion]);

  // scroll reveal — reveal above-the-fold instantly, observe the rest
 useEffect(() => {
 const els = Array.from(document.querySelectorAll(".reveal:not(.in)"));
 if (!("IntersectionObserver" in window)) { els.forEach(e => e.classList.add("in")); return; }
 const io = new IntersectionObserver((entries) => {
 entries.forEach(en => { if (en.isIntersecting) { en.target.classList.add("in"); io.unobserve(en.target); } });
 }, { rootMargin: "0px 0px -8% 0px", threshold: 0.08 });
 const vh = window.innerHeight;
 els.forEach(e => {
 if (e.getBoundingClientRect().top < vh * 0.92) e.classList.add("in", "snap");
 else io.observe(e);
 });
 return () => io.disconnect();
 }, [page]);

 const Page = page === "home" ? window.HomePage : (window.Pages[page] || window.HomePage);

 return (
 <React.Fragment>
 <Nav page={page} go={go} scrolled={scrolled} onBurger={() => setMenu(true)} />
 <MobileMenu open={menu} go={go} close={() => setMenu(false)} />
 <div key={page} className="page-fade">
 <Page go={go} />
 </div>
 <Footer go={go} />
 <Tweaks t={t} setTweak={setTweak} />
 </React.Fragment>
 );
}

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