/* DISC Dubai — App root */
const { useState: useStateA, useEffect: useEffectA } = React;
const { Header: H, Footer: F, BookingModal: BM, WhatsAppFab: WAF, useHashRoute: useRoute, navigate: nav } = window.DISC_UI;
const { HomePage, ServicesHubPage, ServiceDetailPage, TeamPage, PractitionerPage, AboutPage, LocationsPage, ContactPage, BeforeAfterPage, NotFound } = window.DISC_PAGES;

/* tweaks defaults */
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "lime",
  "type": "manrope",
  "density": "comfortable"
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = {
  lime:    { green: "#8DC63F", greenDeep: "#4F7A1F", greenSoft: "oklch(0.96 0.05 130)", greenInk: "#16202B" },
  forest:  { green: "#2E8B57", greenDeep: "#1F5C3A", greenSoft: "oklch(0.96 0.04 155)", greenInk: "#11231A" },
  ocean:   { green: "#22A5A0", greenDeep: "#0E6D6A", greenSoft: "oklch(0.96 0.04 195)", greenInk: "#0E2326" },
  ember:   { green: "#E07A2C", greenDeep: "#A04F0F", greenSoft: "oklch(0.96 0.04 65)",  greenInk: "#231510" }
};

const TYPE_OPTIONS = {
  manrope: { display: "'Manrope', system-ui, sans-serif", body: "'Inter', system-ui, sans-serif" },
  sora:    { display: "'Sora', system-ui, sans-serif",    body: "'Inter', system-ui, sans-serif" },
  fraunces:{ display: "'Fraunces', 'Times New Roman', serif", body: "'Inter', system-ui, sans-serif" }
};

function applyTweaks(t) {
  const root = document.documentElement;
  const a = ACCENT_OPTIONS[t.accent] || ACCENT_OPTIONS.lime;
  root.style.setProperty("--green", a.green);
  root.style.setProperty("--green-deep", a.greenDeep);
  root.style.setProperty("--green-soft", a.greenSoft);
  root.style.setProperty("--ink-tone", a.greenInk);
  const ty = TYPE_OPTIONS[t.type] || TYPE_OPTIONS.manrope;
  root.style.setProperty("--font-display", ty.display);
  root.style.setProperty("--font-body", ty.body);
  root.style.setProperty("--section-pad", t.density === "spacious" ? "120px" : t.density === "compact" ? "64px" : "92px");
}

function App() {
  const { path, parts } = useRoute();
  const [bookOpen, setBookOpen] = useStateA(false);
  const [bookService, setBookService] = useStateA("");
  const [tweaks, setTweaks] = useStateA(TWEAK_DEFAULTS);
  const [tweaksOpen, setTweaksOpen] = useStateA(false);

  useEffectA(() => { applyTweaks(tweaks); }, [tweaks]);

  // Tweaks host wiring
  useEffectA(() => {
    const onMsg = (e) => {
      if (!e.data || typeof e.data !== "object") return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", onMsg);
    try { window.parent.postMessage({type: "__edit_mode_available"}, "*"); } catch(e) {}
    return () => window.removeEventListener("message", onMsg);
  }, []);

  const setTweak = (k, v) => {
    const next = typeof k === "object" ? { ...tweaks, ...k } : { ...tweaks, [k]: v };
    setTweaks(next);
    try { window.parent.postMessage({type: "__edit_mode_set_keys", edits: next}, "*"); } catch(e) {}
  };

  const openBook = () => { setBookService(""); setBookOpen(true); };
  const openBookSvc = (slug) => { setBookService(slug); setBookOpen(true); };

  // hash to #/locations#dhcc — scroll into view after navigation
  useEffectA(() => {
    if (path.includes("#")) {
      const id = path.split("#").pop();
      const el = document.getElementById(id);
      if (el) setTimeout(() => el.scrollIntoView({ behavior: "instant", block: "start" }), 50);
    }
  }, [path]);

  let page;
  if (path === "/" || path === "") page = <HomePage onBook={openBook} onBookService={openBookSvc} />;
  else if (parts[0] === "services" && parts[1]) page = <ServiceDetailPage slug={parts[1]} onBookService={openBookSvc} />;
  else if (parts[0] === "services") page = <ServicesHubPage onBook={openBook} />;
  else if (parts[0] === "team" && parts[1]) page = <PractitionerPage slug={parts[1]} onBookService={openBookSvc} />;
  else if (parts[0] === "team") page = <TeamPage onBook={openBook} />;
  else if (parts[0] === "about") page = <AboutPage onBook={openBook} />;
  else if (parts[0] === "locations") page = <LocationsPage onBook={openBook} />;
  else if (parts[0] === "contact") page = <ContactPage onBook={openBook} />;
  else if (parts[0] === "before-after") page = <BeforeAfterPage onBook={openBook} />;
  else page = <NotFound />;

  return (
    <div style={{display:"contents"}}>
      <H onBook={openBook} />
      <main>{page}</main>
      <F />
      <WAF />
      <BM open={bookOpen} onClose={() => setBookOpen(false)} initialService={bookService} />
      {tweaksOpen && <TweaksUI tweaks={tweaks} setTweak={setTweak} onClose={() => { setTweaksOpen(false); try { window.parent.postMessage({type:"__edit_mode_dismissed"}, "*"); } catch(e){} }}/>}
    </div>
  );
}

function TweaksUI({ tweaks, setTweak, onClose }) {
  return (
    <div className="tweaks-panel">
      <div className="tweaks-head">
        <strong>Tweaks</strong>
        <button onClick={onClose} aria-label="Close"><Icon.close /></button>
      </div>
      <div className="tweaks-body">
        <section>
          <h6>Accent palette</h6>
          <div className="tweak-swatches">
            {Object.entries(ACCENT_OPTIONS).map(([key, val]) => (
              <button key={key}
                className={"swatch " + (tweaks.accent === key ? "is-on" : "")}
                onClick={() => setTweak("accent", key)}
                style={{background: val.green}}
                aria-label={key}>
                <span style={{background: val.greenDeep}} />
              </button>
            ))}
          </div>
          <p className="muted">DISC's orbital mark is lime green — the default. Other accents demo brand range.</p>
        </section>
        <section>
          <h6>Typography</h6>
          <div className="tweak-radio">
            {Object.keys(TYPE_OPTIONS).map(k => (
              <button key={k} className={tweaks.type === k ? "is-on" : ""} onClick={() => setTweak("type", k)}>
                {k === "manrope" ? "Manrope" : k === "sora" ? "Sora" : "Fraunces"}
              </button>
            ))}
          </div>
        </section>
        <section>
          <h6>Section density</h6>
          <div className="tweak-radio">
            {["compact", "comfortable", "spacious"].map(k => (
              <button key={k} className={tweaks.density === k ? "is-on" : ""} onClick={() => setTweak("density", k)}>{k}</button>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
}

const Icon = window.DISC_UI.Icon;
const Fragment = React.Fragment;

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