// App shell — router + tweaks integration

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "displayFont": "Instrument Serif",
  "showFractionMotif": true,
  "density": "regular",
  "creamShade": "#f1ebdf"
}/*EDITMODE-END*/;

const FONT_OPTIONS = {
  "Instrument Serif": '"Instrument Serif", serif',
  "Cormorant": '"Cormorant Garamond", serif',
  "Newsreader": '"Newsreader", serif',
  "Playfair": '"Playfair Display", serif',
};

function parseRoute() {
  const h = window.location.hash || "#/";
  const path = h.slice(1) || "/";
  if (path === "/" || path === "") return { name: "home", path: "/" };
  if (path === "/products") return { name: "products", path };
  if (path === "/story") return { name: "story", path };
  if (path === "/find") return { name: "find", path };
  if (path.startsWith("/p/")) return { name: "product", path, id: path.slice(3) };
  return { name: "home", path: "/" };
}

const App = () => {
  const [route, setRoute] = React.useState(parseRoute());
  const [dataReady, setDataReady] = React.useState(false);
  const [tweaks, setTweak] = useTweaks ? useTweaks(TWEAK_DEFAULTS) : [TWEAK_DEFAULTS, () => {}];

  React.useEffect(() => {
    Promise.all([
      fetch("/api/products").then((r) => r.json()),
      fetch("/api/stores").then((r) => r.json()),
    ]).then(([products, stores]) => {
      window.PRODUCTS = products;
      window.STORES = stores;
    }).catch(() => {
      // fallback to hardcoded data in data.jsx
    }).finally(() => {
      setDataReady(true);
    });
  }, []);

  React.useEffect(() => {
    const onHash = () => setRoute(parseRoute());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  React.useEffect(() => {
    // scroll to top on navigation
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [route.path]);

  // load extra fonts on demand
  React.useEffect(() => {
    if (tweaks.displayFont !== "Instrument Serif") {
      const id = "extra-font";
      let link = document.getElementById(id);
      if (!link) {
        link = document.createElement("link");
        link.id = id;
        link.rel = "stylesheet";
        document.head.appendChild(link);
      }
      const families = {
        "Cormorant": "Cormorant+Garamond:ital,wght@0,400;0,500;1,400;1,500",
        "Newsreader": "Newsreader:ital,wght@0,400;0,500;1,400;1,500",
        "Playfair": "Playfair+Display:ital,wght@0,400;0,500;1,400;1,500",
      };
      const fam = families[tweaks.displayFont];
      if (fam) link.href = "https://fonts.googleapis.com/css2?family=" + fam + "&display=swap";
    }
  }, [tweaks.displayFont]);

  const cssOverride = {
    "--serif": FONT_OPTIONS[tweaks.displayFont] || FONT_OPTIONS["Instrument Serif"],
    "--cream": tweaks.creamShade,
    "--pad-x": tweaks.density === "tight" ? "clamp(20px, 3vw, 40px)" : tweaks.density === "loose" ? "clamp(24px, 5vw, 80px)" : "clamp(20px, 4vw, 56px)",
  };

  const navigate = (to) => { window.location.hash = to; };
  const inverse = false;

  if (!dataReady) return (
    <div style={{ height: "100vh", display: "flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
      Loading
    </div>
  );

  let page = null;
  if (route.name === "home") page = <Home navigate={navigate} />;
  if (route.name === "products") page = <Products navigate={navigate} />;
  if (route.name === "product") page = <Product id={route.id} navigate={navigate} />;
  if (route.name === "story") page = <Story navigate={navigate} />;
  if (route.name === "find") page = <Find navigate={navigate} />;

  // map routes to active path tag for nav
  const navCurrent =
    route.name === "home" ? "/" :
    route.name === "products" || route.name === "product" ? "/products" :
    route.name === "story" ? "/story" :
    route.name === "find" ? "/find" : "/";

  return (
    <div style={cssOverride}>
      <Nav current={navCurrent} navigate={navigate} inverse={inverse} />
      {page}
      <Footer navigate={navigate} />

      {/* floating fraction motif */}
      {tweaks.showFractionMotif && (
        <FloatingFraction />
      )}

      {/* tweaks panel */}
      {typeof TweaksPanel !== "undefined" && (
        <TweaksPanel title="Tweaks">
          <TweakSection label="Type">
            <TweakRadio
              label="Display font"
              value={tweaks.displayFont}
              onChange={(v) => setTweak("displayFont", v)}
              options={[
                { label: "Instrument", value: "Instrument Serif" },
                { label: "Cormorant", value: "Cormorant" },
                { label: "Newsreader", value: "Newsreader" },
                { label: "Playfair", value: "Playfair" },
              ]}
            />
          </TweakSection>

          <TweakSection label="Layout">
            <TweakRadio
              label="Density"
              value={tweaks.density}
              onChange={(v) => setTweak("density", v)}
              options={[
                { label: "Tight", value: "tight" },
                { label: "Regular", value: "regular" },
                { label: "Loose", value: "loose" },
              ]}
            />
            <TweakToggle
              label="Floating 1/3 motif"
              value={tweaks.showFractionMotif}
              onChange={(v) => setTweak("showFractionMotif", v)}
            />
          </TweakSection>

          <TweakSection label="Color">
            <TweakColor
              label="Cream shade"
              value={tweaks.creamShade}
              onChange={(v) => setTweak("creamShade", v)}
              options={["#f1ebdf", "#efe7d3", "#f5efe5", "#e8e0cd"]}
            />
          </TweakSection>
        </TweaksPanel>
      )}
    </div>
  );
};

// Floating 1/3 motif — small, fixed, page-aware
const FloatingFraction = () => {
  const [scrolled, setScrolled] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const h = document.body.scrollHeight - window.innerHeight;
      setScrolled(Math.min(1, Math.max(0, window.scrollY / Math.max(1, h))));
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const pct = Math.round(scrolled * 100);
  const third = scrolled < 0.33 ? "1/3" : scrolled < 0.66 ? "2/3" : "3/3";
  const label = scrolled < 0.33 ? "Top" : scrolled < 0.66 ? "Middle" : "Base";

  return (
    <div style={{
      position: "fixed",
      right: 24,
      bottom: 24,
      zIndex: 40,
      pointerEvents: "none",
      mixBlendMode: "difference",
      color: "#f1ebdf",
      fontFamily: "var(--mono)",
      fontSize: 10,
      letterSpacing: ".18em",
      textTransform: "uppercase",
      textAlign: "right",
      lineHeight: 1.5,
    }}>
      <div style={{ fontFamily: "var(--serif)", fontStyle: "italic", fontSize: 32, letterSpacing: 0, lineHeight: 1, textTransform: "none" }}>{third}</div>
      <div style={{ marginTop: 6, opacity: 0.7 }}>{label} · {pct}%</div>
    </div>
  );
};

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