/* global React, ReactDOM, useRoute, nav,
   Nav, Footer,
   HomePage, EstimatePage, PartnersPage, LandingPage,
   ProofGalleryPage, ServicesPage, HowItWorksPage, PricingPage,
   useTweaks, TweaksPanel, TweakSection, TweakRadio, TweakSelect, TweakToggle, TweakButton, LANDING_CONTENT */
const { useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroHeadline": "A",
  "primaryCta": "A",
  "situationQuestion": "A",
  "pricingPlacement": "section",
  "showStickyMobileCta": true
}/*EDITMODE-END*/;

function Router({ tweaks }) {
  const route = useRoute();

  // /repair/<slug>
  const repairMatch = route.match(/^\/repair\/([a-z0-9-]+)\/?$/i);
  if (repairMatch) return <LandingPage slug={repairMatch[1]} />;

  switch (route) {
    case "/":
    case "":
      return <HomePage tweaks={tweaks} />;
    case "/send-photos":
      return <EstimatePage />;
    case "/partners":
      return <PartnersPage />;
    case "/proof":
      return <ProofGalleryPage />;
    case "/services":
      return <ServicesPage />;
    case "/how-it-works":
      return <HowItWorksPage />;
    case "/pricing":
      return <PricingPage />;
    default:
      return (
        <div style={{ padding: "120px 24px", textAlign: "center" }}>
          <h1>Page not found</h1>
          <p style={{ color: "var(--fg-muted)", marginTop: 12 }}>The link <code>{route}</code> isn't part of the site yet.</p>
          <p style={{ marginTop: 20 }}>
            <a href="#/" onClick={(e) => { e.preventDefault(); nav("/"); }} style={{ color: "var(--pmu-teal)", fontWeight: 700 }}>← Back to home</a>
          </p>
        </div>
      );
  }
}

/* ─────────── Sticky mobile CTA ─────────── */
function StickyMobileCta() {
  const route = useRoute();
  if (route === "/send-photos") return null;
  return (
    <div style={{
      position: "fixed", left: 12, right: 12, bottom: 12, zIndex: 40,
      display: "none",
      gap: 8,
      padding: 8,
      background: "rgba(247,243,234,0.96)",
      backdropFilter: "blur(10px)",
      WebkitBackdropFilter: "blur(10px)",
      border: "1px solid var(--border)",
      borderRadius: 999,
      boxShadow: "var(--shadow-card)",
    }} className="sticky-mobile-cta">
      <a href="tel:6025550148" className="btn btn-secondary btn-sm" style={{ flex: 1, justifyContent: "center" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
          📞 Call
        </span>
      </a>
      <button className="btn btn-action btn-sm" style={{ flex: 1.4, justifyContent: "center" }} onClick={() => nav("/send-photos")}>
        Send Photos
      </button>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Standalone deploy: when not embedded in the editor host, surface a
  // floating "Variants" button that opens the same Tweaks panel.
  const [standalone, setStandalone] = React.useState(false);
  const [panelOn, setPanelOn] = React.useState(false);
  useEffectApp(() => {
    const isStandalone = window.parent === window;
    setStandalone(isStandalone);
    if (isStandalone) {
      // Auto-open on first visit so partners see the variants are toggleable.
      const firstVisit = !sessionStorage.getItem("pmu_variants_seen");
      if (firstVisit) {
        sessionStorage.setItem("pmu_variants_seen", "1");
        setTimeout(() => {
          window.postMessage({ type: "__activate_edit_mode" }, "*");
          setPanelOn(true);
        }, 400);
      }
      // Track panel state by listening for the dismiss message we send.
      const onMsg = (e) => {
        if (e?.data?.type === "__edit_mode_dismissed") setPanelOn(false);
      };
      window.addEventListener("message", onMsg);
      return () => window.removeEventListener("message", onMsg);
    }
  }, []);

  const toggleVariants = () => {
    const next = !panelOn;
    setPanelOn(next);
    window.postMessage({ type: next ? "__activate_edit_mode" : "__deactivate_edit_mode" }, "*");
  };

  // SEO-ish title swap per route
  const route = useRoute();
  useEffectApp(() => {
    const titles = {
      "/":             "Patch Me Up — Wall & Ceiling Repair · Phoenix",
      "/send-photos":  "Send Photos · Patch Me Up",
      "/partners":     "Trade Partners · Patch Me Up",
      "/proof":        "Proof Gallery · Patch Me Up",
      "/services":     "Services · Patch Me Up",
      "/how-it-works": "How It Works · Patch Me Up",
      "/pricing":      "Pricing · Patch Me Up",
    };
    const repairMatch = route.match(/^\/repair\/([a-z0-9-]+)\/?$/i);
    if (repairMatch) {
      const c = LANDING_CONTENT[repairMatch[1]];
      document.title = c ? `${c.eyebrow} · Patch Me Up` : "Repair · Patch Me Up";
    } else {
      document.title = titles[route] || "Patch Me Up";
    }
  }, [route]);

  return (
    <div className="pmu-app" data-screen-label={"PMU Site · " + route}>
      <style>{`
        @media (max-width: 720px) {
          .sticky-mobile-cta { display: ${t.showStickyMobileCta ? "flex" : "none"} !important; }
          body { padding-bottom: ${t.showStickyMobileCta ? "72px" : "0"}; }
        }
      `}</style>

      <Nav />
      <Router tweaks={t} />
      <Footer />
      <StickyMobileCta />

      {/* Standalone-deploy floating "Variants" toggle */}
      {standalone && (
        <button
          type="button"
          onClick={toggleVariants}
          aria-label="Toggle variants panel"
          style={{
            position: "fixed",
            right: 16, bottom: 16,
            zIndex: 2147483645,
            display: panelOn ? "none" : "inline-flex",
            alignItems: "center", gap: 8,
            padding: "10px 16px",
            background: "var(--pmu-graphite)",
            color: "var(--pmu-wall)",
            border: 0, borderRadius: 999,
            fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 13,
            letterSpacing: "-0.01em",
            boxShadow: "0 6px 22px rgba(31,45,51,0.28), 0 1px 0 rgba(255,255,255,0.06) inset",
            cursor: "pointer",
          }}
        >
          <span style={{
            width: 8, height: 8, borderRadius: 999, background: "var(--pmu-gold)",
            boxShadow: "0 0 0 3px rgba(235,203,102,0.22)"
          }} />
          Variants
          <span style={{
            fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.14em",
            color: "var(--pmu-sand-soft)", marginLeft: 4
          }}>A/B/C</span>
        </button>
      )}

      <TweaksPanel title="Variants · for partner review">
        <div style={{
          fontSize: 11, lineHeight: 1.5, color: "rgba(41,38,27,.7)",
          padding: "8px 10px", marginBottom: 4, borderRadius: 8,
          background: "rgba(23,78,93,0.07)", border: "1px solid rgba(23,78,93,0.15)"
        }}>
          We're comparing a few directions. Toggle the variants and tell us which
          combination feels most like Patch Me Up to your customers.
        </div>

        <TweakSection label="Hero" />
        <TweakRadio
          label="Headline"
          value={t.heroHeadline}
          options={["A", "B", "C"]}
          onChange={(v) => setTweak("heroHeadline", v)}
        />
        <div style={{ fontSize: 10.5, color: "rgba(41,38,27,.55)", marginTop: -4, lineHeight: 1.4 }}>
          A · Wall repair that closes the loop.<br/>
          B · From damage to done.<br/>
          C · Small wall repair without the contractor chase.
        </div>
        <TweakRadio
          label="Primary CTA"
          value={t.primaryCta}
          options={["A", "B", "C"]}
          onChange={(v) => setTweak("primaryCta", v)}
        />
        <div style={{ fontSize: 10.5, color: "rgba(41,38,27,.55)", marginTop: -4, lineHeight: 1.4 }}>
          A · Send Photos for an Estimate<br/>
          B · Get a Repair Estimate<br/>
          C · Start with Photos
        </div>

        <TweakSection label="Situation selector" />
        <TweakRadio
          label="Question"
          value={t.situationQuestion}
          options={["A", "B", "C"]}
          onChange={(v) => setTweak("situationQuestion", v)}
        />
        <div style={{ fontSize: 10.5, color: "rgba(41,38,27,.55)", marginTop: -4, lineHeight: 1.4 }}>
          A · What happened?<br/>
          B · What do you need fixed?<br/>
          C · Who are you booking for?
        </div>

        <TweakSection label="Pricing placement" />
        <TweakSelect
          label="On homepage"
          value={t.pricingPlacement}
          options={[
            { value: "section", label: "Show as section" },
            { value: "hidden",  label: "Only on /pricing" },
          ]}
          onChange={(v) => setTweak("pricingPlacement", v)}
        />

        <TweakSection label="Mobile" />
        <TweakToggle
          label="Sticky CTA bar"
          value={t.showStickyMobileCta}
          onChange={(v) => setTweak("showStickyMobileCta", v)}
        />

        <TweakSection label="Jump to page" />
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 6 }}>
          <TweakButton onClick={() => nav("/")}>Home</TweakButton>
          <TweakButton onClick={() => nav("/send-photos")}>Estimate flow</TweakButton>
          <TweakButton onClick={() => nav("/partners")}>Partners</TweakButton>
          <TweakButton onClick={() => nav("/repair/post-trade")}>Landing · Post‑trade</TweakButton>
          <TweakButton onClick={() => nav("/repair/pre-listing")}>Landing · Pre‑listing</TweakButton>
          <TweakButton onClick={() => nav("/repair/rental-turn")}>Landing · Rental turn</TweakButton>
          <TweakButton onClick={() => nav("/repair/ceiling")}>Landing · Ceiling</TweakButton>
          <TweakButton onClick={() => nav("/repair/failed-diy")}>Landing · DIY rescue</TweakButton>
          <TweakButton onClick={() => nav("/proof")}>Proof gallery</TweakButton>
          <TweakButton onClick={() => nav("/services")}>Services</TweakButton>
          <TweakButton onClick={() => nav("/how-it-works")}>How it works</TweakButton>
          <TweakButton onClick={() => nav("/pricing")}>Pricing</TweakButton>
        </div>
      </TweaksPanel>
    </div>
  );
}

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