// app.jsx — Router + App + Tweaks
const { useState: useStateApp, useEffect: useEffectApp, useMemo: useMemoApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": "ivory",
  "fontset": "classic",
  "accent": "jade",
  "density": "regular",
  "showSeals": true
}/*EDITMODE-END*/;

function parsePath() {
  const path = window.location.pathname || "/";
  const queryPart = window.location.search.slice(1);
  const query = {};
  if (queryPart) {
    queryPart.split("&").forEach(kv => {
      const [k, v] = kv.split("=");
      query[decodeURIComponent(k)] = decodeURIComponent(v || "");
    });
  }
  return { path, query };
}

function App() {
  const [{ path, query }, setRoute] = useStateApp(parsePath());
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffectApp(() => {
    const on = () => {
      setRoute(parsePath());
      window.scrollTo({ top: 0, behavior: "instant" });
    };
    window.addEventListener("popstate", on);
    return () => window.removeEventListener("popstate", on);
  }, []);

  // Apply tweaks to body
  useEffectApp(() => {
    document.body.dataset.layout = t.palette;
    document.body.dataset.fontset = t.fontset;
    document.body.dataset.accent = t.accent;
    document.body.dataset.density = t.density;
  }, [t]);

  // Dynamic page title
  useEffectApp(() => {
    const base = "Healing Pearl Massage";
    const LOCS = window.HP_LOCATIONS;
    const segs = path.split("/").filter(Boolean);
    const here = LOCS.find(l => l.id === segs[0]);
    const cityTag = { woodcreek: "Katy, TX", crosscreek: "Fulshear, TX" };
    let title = base;
    if (here) {
      const city = cityTag[here.id] || here.city;
      const sub = segs[1], sub2 = segs[2];
      if (!sub) {
        title = here.id === "woodcreek"
          ? `Deep Tissue & Chinese Massage in Katy TX | ${base}`
          : `Massage Therapy in Fulshear TX | ${base}`;
      } else if (sub === "services" && sub2) {
        const svc = (window.HP_SERVICES || []).find(s => s.id === sub2);
        title = svc ? `${svc.name} in ${city} | ${base}` : `Services | ${base}`;
      } else if (sub === "services") {
        title = `Massage Services in ${city} | ${base}`;
      } else if (sub === "reviews") {
        title = `Reviews — ${here.name} | ${base}`;
      } else if (sub === "about" || sub === "studio") {
        title = `Our Studio — ${here.name} | ${base}`;
      } else if (sub === "visit" || sub === "contact") {
        title = `Visit — ${here.name} in ${city} | ${base}`;
      } else if (sub === "book") {
        title = `Book a Massage in ${city} | ${base}`;
      }
    } else {
      const top = segs[0];
      if (top === "services") title = `Massage Services — Katy & Fulshear TX | ${base}`;
      else if (top === "about") title = `About | ${base}`;
      else if (top === "contact") title = `Contact | ${base}`;
      else if (!top) title = `Chinese Massage in Katy & Fulshear TX | ${base}`;
    }
    document.title = title;
  }, [path]);

  // Dynamic meta description
  useEffectApp(() => {
    const LOCS = window.HP_LOCATIONS;
    const segs = path.split("/").filter(Boolean);
    const here = LOCS.find(l => l.id === segs[0]);
    let desc = "Authentic Chinese massage in Katy & Fulshear, TX. Swedish, deep tissue, prenatal, couples & foot reflexology. Hot stones always included. Book same-day.";
    if (here) {
      const sub = segs[1], sub2 = segs[2];
      const city = here.city;
      const addr = here.streetLine1 + ", " + here.streetLine2;
      if (!sub) {
        desc = here.id === "woodcreek"
          ? `Deep tissue & Chinese massage in Katy, TX. Swedish, prenatal, couples & foot reflexology at ${addr}. Hot stones included. Call ${here.phone} or book online.`
          : `Massage therapy in Fulshear, TX — Cross Creek Ranch. Deep tissue, prenatal, couples & foot reflexology at ${addr}. Hot stones included. Call ${here.phone}.`;
      } else if (sub === "services" && sub2) {
        const svc = (window.HP_SERVICES || []).find(s => s.id === sub2);
        if (svc) desc = `${svc.tagline} Book ${svc.name} at Healing Pearl Massage in ${city} — from $${svc.fromPrice}. ${svc.minDuration}–${svc.maxDuration} min sessions available.`;
      } else if (sub === "services") {
        desc = `Massage services in ${city}: Swedish, deep tissue, prenatal, couples & foot reflexology. Same prices at both studios. Hot stones always included. Book same-day.`;
      } else if (sub === "reviews") {
        desc = `Read what clients say about Healing Pearl Massage in ${city}. ${here.reviewCount > 0 ? here.reviewCount + " Google reviews · " + here.rating + " stars." : "Be one of our first reviewers."}`;
      } else if (sub === "about" || sub === "studio") {
        desc = `Meet the team at Healing Pearl Massage ${here.name} in ${city}. Family-owned, authentic Chinese massage techniques. ${here.rooms} treatment rooms, ${here.couplesSuites} couples suites.`;
      } else if (sub === "visit" || sub === "contact") {
        desc = `Visit Healing Pearl Massage in ${city}. Located at ${addr}. Hours: Mon–Sat 9:30 AM–8 PM, Sun 10 AM–7:30 PM. Call ${here.phone}.`;
      } else if (sub === "book") {
        desc = `Book a massage at Healing Pearl Massage in ${city}. Same-day appointments usually available. Deep tissue, couples, prenatal & more. Call ${here.phone}.`;
      }
    }
    const tag = document.querySelector('meta[name="description"]');
    if (tag) tag.setAttribute("content", desc);

    // Mirror description into OG + Twitter
    const ogDesc = document.querySelector('meta[property="og:description"]');
    if (ogDesc) ogDesc.setAttribute("content", desc);
    const twDesc = document.querySelector('meta[name="twitter:description"]');
    if (twDesc) twDesc.setAttribute("content", desc);
  }, [path]);

  // Dynamic canonical + OG url/title — every route gets its own
  useEffectApp(() => {
    const origin = location.origin || "https://healingpearlmassage.net";
    const canonicalPath = path === "/" ? "/" : path.replace(/\/+$/, "");
    const url = origin + canonicalPath;
    const cTag = document.querySelector('link[rel="canonical"]');
    if (cTag) cTag.setAttribute("href", url);
    const ogUrl = document.querySelector('meta[property="og:url"]');
    if (ogUrl) ogUrl.setAttribute("content", url);
    const ogTitle = document.querySelector('meta[property="og:title"]');
    if (ogTitle) ogTitle.setAttribute("content", document.title);
    const twTitle = document.querySelector('meta[name="twitter:title"]');
    if (twTitle) twTitle.setAttribute("content", document.title);
  }, [path]);

  // Noindex booking pages — they're conversion pages, not ranking pages
  useEffectApp(() => {
    const segs = path.split("/").filter(Boolean);
    const isBooking = segs[1] === "book";
    let robots = document.querySelector('meta[name="robots"]');
    if (isBooking) {
      if (!robots) {
        robots = document.createElement("meta");
        robots.setAttribute("name", "robots");
        document.head.appendChild(robots);
      }
      robots.setAttribute("content", "noindex, follow");
    } else if (robots) {
      robots.remove();
    }
  }, [path]);

  // Service JSON-LD schema on service detail pages
  useEffectApp(() => {
    const existing = document.getElementById("svc-schema");
    if (existing) existing.remove();
    const segs = path.split("/").filter(Boolean);
    const LOCS = window.HP_LOCATIONS;
    const here = LOCS.find(l => l.id === segs[0]);
    if (!here || segs[1] !== "services" || !segs[2]) return;
    const svc = (window.HP_SERVICES || []).find(s => s.id === segs[2]);
    if (!svc) return;
    const tag = document.createElement("script");
    tag.type = "application/ld+json";
    tag.id = "svc-schema";
    tag.textContent = JSON.stringify({
      "@context": "https://schema.org",
      "@type": "Service",
      "name": svc.name,
      "serviceType": svc.shortName,
      "description": svc.tagline,
      "provider": {
        "@type": "MassageTherapist",
        "name": `Healing Pearl Massage — ${here.name}`,
        "telephone": "+1" + here.phoneTel.replace(/\D/g, ""),
        "address": {
          "@type": "PostalAddress",
          "streetAddress": here.streetLine1,
          "addressLocality": here.city,
          "addressRegion": "TX",
          "postalCode": here.streetLine2.match(/\d{5}/)?.[0] || "",
          "addressCountry": "US",
        },
      },
      "areaServed": { "@type": "City", "name": here.city },
      "offers": (svc.durations || []).map(d => ({
        "@type": "Offer",
        "name": `${svc.shortName} — ${d.min} min`,
        "price": String(d.price),
        "priceCurrency": "USD",
      })),
    });
    document.head.appendChild(tag);
  }, [path]);

  // FAQ JSON-LD schema — inject on location home pages only
  useEffectApp(() => {
    const existing = document.getElementById("faq-schema");
    if (existing) existing.remove();
    const segs = path.split("/").filter(Boolean);
    const LOCS = window.HP_LOCATIONS;
    const here = LOCS.find(l => l.id === segs[0]);
    const faqs = window.HP_FAQ || [];
    if (here && segs.length === 1 && faqs.length) {
      const tag = document.createElement("script");
      tag.type = "application/ld+json";
      tag.id = "faq-schema";
      tag.textContent = JSON.stringify({
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": faqs.map(f => ({
          "@type": "Question",
          "name": f.q,
          "acceptedAnswer": { "@type": "Answer", "text": f.a },
        })),
      });
      document.head.appendChild(tag);
    }
  }, [path]);

  // Apply per-location accent (overrides brand accent on shop pages)
  useEffectApp(() => {
    const LOCS = window.HP_LOCATIONS;
    const segs = path.split("/").filter(Boolean);
    const here = LOCS.find(l => l.id === segs[0]);
    if (here) {
      document.body.dataset.locAccent = here.accent;
      try { localStorage.setItem("hp_last_loc", here.id); } catch {}
    } else {
      delete document.body.dataset.locAccent;
    }
  }, [path]);

  const go = (to) => {
    if (!to) return;
    window.history.pushState({}, "", to);
    setRoute(parsePath());
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  // Parse route → which page + props
  const LOCS = window.HP_LOCATIONS;
  const segments = path.split("/").filter(Boolean);

  let loc = null;
  let pageEl = null;

  if (segments.length === 0) {
    pageEl = <LocatorHome />;
  } else {
    // segment[0] could be a location id OR a global page name
    const maybeLoc = LOCS.find(l => l.id === segments[0]);
    if (maybeLoc) {
      loc = maybeLoc;
      const sub = segments[1];
      const sub2 = segments[2];
      if (!sub) pageEl = <LocationHome />;
      else if (sub === "services" && sub2) pageEl = <ServiceDetail serviceId={sub2} />;
      else if (sub === "services") pageEl = <ServicesIndex />;
      else if (sub === "reviews") pageEl = <Reviews />;
      else if (sub === "about" || sub === "studio") pageEl = <OurStudio />;
      else if (sub === "visit" || sub === "contact" || sub === "area") pageEl = <Visit />;
      else if (sub === "book") pageEl = <Booking key={`${loc.id}-${query.svc||''}-${query.dur||''}`} initialServiceId={query.svc} initialDuration={query.dur} />;
      else pageEl = <LocationHome />;
    } else {
      // global pages without a location context
      const top = segments[0];
      const sub = segments[1];
      if (top === "services" && sub) pageEl = <ServiceDetail serviceId={sub} />;
      else if (top === "services") pageEl = <ServicesIndex />;
      else if (top === "about") pageEl = <About />;
      else if (top === "contact") pageEl = <Contact />;
      else if (top === "area") pageEl = <ServiceArea />;
      else if (top === "privacy") pageEl = <LegalPage kind="privacy" />;
      else if (top === "terms") pageEl = <LegalPage kind="terms" />;
      else pageEl = <LocatorHome />;
    }
  }

  const ctx = useMemoApp(() => ({ path, query, go, loc }), [path, query, loc]);

  const isBookingPage = loc && segments[1] === "book";

  return (
    <RouterCtx.Provider value={ctx}>
      <Header />
      {pageEl}
      <Footer />

      {loc && !isBookingPage && (
        <div className="mobile-sticky-cta">
          <button className="btn btn-primary" style={{ flex: 1, justifyContent: "center" }} onClick={() => go(`/${loc.id}/book`)}>
            Book Now
          </button>
          <a className="btn btn-secondary" style={{ flex: 1, justifyContent: "center" }} href={`tel:${loc.phoneTel}`}>
            Call Us
          </a>
        </div>
      )}

      <TweaksPanel>
        <TweakSection label="Palette" />
        <TweakRadio label="Background" value={t.palette} options={[
          { value: "ivory", label: "Ivory" },
          { value: "warm", label: "Warm" },
          { value: "stone", label: "Stone" },
        ]} onChange={(v) => setTweak("palette", v)} />

        <TweakSection label="Typography" />
        <TweakRadio label="Font Set" value={t.fontset} options={[
          { value: "classic", label: "Classic" },
          { value: "editorial", label: "Editorial" },
          { value: "modern", label: "Modern" },
        ]} onChange={(v) => setTweak("fontset", v)} />

        <TweakSection label="Layout" />
        <TweakRadio label="Density" value={t.density} options={[
          { value: "compact", label: "Compact" },
          { value: "regular", label: "Regular" },
          { value: "airy", label: "Airy" },
        ]} onChange={(v) => setTweak("density", v)} />
        <TweakToggle label="Show Chinese seals" value={t.showSeals} onChange={(v) => setTweak("showSeals", v)} />

        <TweakSection label="Brand pages" />
        <TweakButton label="Locator (home)" onClick={() => go("/")} />
        <TweakButton label="Brand · Services" onClick={() => go("/services")} />
        <TweakButton label="Brand · About" onClick={() => go("/about")} />

        <TweakSection label="Woodcreek (jade)" />
        <TweakButton label="Studio home" onClick={() => go("/woodcreek")} />
        <TweakButton label="Services" onClick={() => go("/woodcreek/services")} />
        <TweakButton label="Reviews" onClick={() => go("/woodcreek/reviews")} />
        <TweakButton label="Our Studio" onClick={() => go("/woodcreek/about")} />
        <TweakButton label="Visit" onClick={() => go("/woodcreek/visit")} />
        <TweakButton label="Book" onClick={() => go("/woodcreek/book")} />

        <TweakSection label="Cross Creek (clay)" />
        <TweakButton label="Studio home" onClick={() => go("/crosscreek")} />
        <TweakButton label="Services" onClick={() => go("/crosscreek/services")} />
        <TweakButton label="Reviews" onClick={() => go("/crosscreek/reviews")} />
        <TweakButton label="Our Studio" onClick={() => go("/crosscreek/about")} />
        <TweakButton label="Visit" onClick={() => go("/crosscreek/visit")} />
      </TweaksPanel>
    </RouterCtx.Provider>
  );
}

// Apply showSeals tweak globally
const sealStyle = document.createElement("style");
sealStyle.id = "seal-toggle";
document.head.appendChild(sealStyle);
const obs = new MutationObserver(() => {
  const show = document.body.dataset.showSeals !== "false";
  sealStyle.textContent = show ? "" : ".seal{display:none !important}";
});
obs.observe(document.body, { attributes: true, attributeFilter: ["data-show-seals"] });

// React to TweaksPanel writes via the useEffect on t
// (we'll just listen to body changes via observer above)

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