// app.jsx — root + router + cart + tweaks

const { useState: useStateApp, useEffect: useEffectApp } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#2d6a5f",
  "density": "regular",
  "dark": false,
  "bgAnim": false
}/*EDITMODE-END*/;

const ACCENT_OPTIONS = [
  "#2d6a5f",  // muted teal-green (default)
  "#1f3a5f",  // deep blue
  "#3b8a8a",  // turquoise
  "#1a1a1a",  // monochrome (no accent color)
  "#a8702c",  // warm umber
];

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

  // Products loading state — listens for the "products-loaded" event from data.jsx
  const [productsState, setProductsState] = useStateApp(window.PRODUCTS_STATE || "loading");
  useEffectApp(() => {
    if (window.PRODUCTS_STATE === "ready")  { setProductsState("ready"); return; }
    if (window.PRODUCTS_STATE === "error")  { setProductsState("error"); return; }
    const onLoaded = () => setProductsState("ready");
    const onError  = () => setProductsState("error");
    window.addEventListener("products-loaded", onLoaded);
    window.addEventListener("products-error",  onError);
    return () => {
      window.removeEventListener("products-loaded", onLoaded);
      window.removeEventListener("products-error",  onError);
    };
  }, []);

  // Routing
  const [route, setRoute] = useStateApp(() => {
    const h = window.location.hash.replace("#", "");
    if (h.startsWith("product/")) return "product";
    return ["home", "shop", "product", "about", "contact", "cart"].includes(h) ? h : "home";
  });
  const [productId, setProductId] = useStateApp(() => {
    const h = window.location.hash.replace("#", "");
    if (h.startsWith("product/")) return h.replace("product/", "");
    return window.PRODUCTS[0]?.id || null;
  });
  // After products load, if no productId selected yet, pick the first product
  useEffectApp(() => {
    if (productsState === "ready" && !productId && window.PRODUCTS.length > 0) {
      setProductId(window.PRODUCTS[0].id);
    }
  }, [productsState, productId]);

  const navigate = (r, params = {}) => {
    setRoute(r);
    if (r === "product" && params.id) {
      setProductId(params.id);
      window.location.hash = "product/" + params.id;
    } else {
      window.location.hash = r;
    }
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  useEffectApp(() => {
    const onHash = () => {
      const h = window.location.hash.replace("#", "");
      if (h.startsWith("product/")) {
        setRoute("product");
        setProductId(h.replace("product/", ""));
      } else if (["home", "shop", "about", "contact", "cart"].includes(h)) {
        setRoute(h);
      }
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // Cart — starts empty (was demo data before Supabase integration)
  const [cart, setCart] = useStateApp([]);
  const addToCart = (product, qty) => {
    setCart((c) => {
      const existing = c.find((l) => l.product.id === product.id);
      if (existing) return c.map((l) => l.product.id === product.id ? { ...l, qty: l.qty + qty } : l);
      return [...c, { product, qty }];
    });
    navigate("cart");
  };
  const updateQty = (id, qty) => setCart((c) => c.map((l) => l.product.id === id ? { ...l, qty } : l));
  const removeItem = (id) => setCart((c) => c.filter((l) => l.product.id !== id));
  const cartCount = cart.reduce((s, l) => s + l.qty, 0);

  // Apply tweaks via CSS variables
  const isDark = t.dark;
  const accent = t.accent;
  const density = t.density;

  // Density scale
  const densityScale = density === "compact" ? 0.86 : density === "comfy" ? 1.12 : 1;

  const themeVars = isDark ? {
    "--bg": "#0e0f10",
    "--surface": "#161819",
    "--surface-2": "#1c1f20",
    "--fg": "#f4f3ef",
    "--fg-hover": "#dad7d0",
    "--muted": "#8c8a85",
    "--border": "#26292a",
    "--stripe": "rgba(255,255,255,0.025)",
    "--accent": accent,
    "--accent-hover": accent + "dd",
    "--accent-soft": accent + "55",
  } : {
    "--bg": "#fafaf8",
    "--surface": "#f3f2ee",
    "--surface-2": "#ebeae5",
    "--fg": "#161616",
    "--fg-hover": "#2a2a2a",
    "--muted": "#7a7872",
    "--border": "#e3e1dc",
    "--stripe": "rgba(0,0,0,0.04)",
    "--accent": accent,
    "--accent-hover": accent + "dd",
    "--accent-soft": accent + "44",
  };

  useEffectApp(() => {
    const root = document.documentElement;
    Object.entries(themeVars).forEach(([k, v]) => root.style.setProperty(k, v));
    root.style.setProperty("--density-scale", String(densityScale));
    root.style.background = themeVars["--bg"];
    document.body.style.background = "transparent";
    document.body.style.color = themeVars["--fg"];
  }, [isDark, accent, density]);

  // Detect whether the header is currently overlapping the dark 3D hero,
  // so its chrome can switch styling without route hacks.
  const [darkChrome, setDarkChrome] = useStateApp(() => {
    // Initial state: if landing on home, we're sitting on top of the dark
    // hero from the first frame — avoid a flash of white chrome.
    const h = window.location.hash.replace("#", "");
    const initRoute = h.startsWith("product/")
      ? "product"
      : (["home", "shop", "product", "about", "contact", "cart"].includes(h) ? h : "home");
    return initRoute === "home";
  });
  useEffectApp(() => {
    if (route !== "home") { setDarkChrome(false); return; }
    const check = () => {
      // Hero is 400vh tall; while we're still scrolled within it, keep dark chrome.
      // Scroll-only check (no DOM query) prevents flash of white before hero mounts.
      const heroEnd = window.innerHeight * 4 - 64;
      setDarkChrome(window.scrollY < heroEnd);
    };
    check();
    window.addEventListener("scroll", check, { passive: true });
    window.addEventListener("resize", check);
    return () => {
      window.removeEventListener("scroll", check);
      window.removeEventListener("resize", check);
    };
  }, [route]);

  let page;
  // While products are loading (or failed), show a minimal loading state
  // for routes that need them. Home is fine to render without products though
  // (hero, about sections, etc work standalone).
  const needsProducts = ["shop", "product", "cart"].includes(route);
  if (productsState === "loading" && needsProducts) {
    page = (
      <main data-screen-label="Loading" style={{ minHeight: "60vh", display: "grid", placeItems: "center" }}>
        <div style={{ textAlign: "center", color: "var(--muted)" }}>
          <div className="loading-spinner" style={{
            width: 32, height: 32, margin: "0 auto 16px",
            border: "2px solid var(--border)",
            borderTopColor: "var(--accent)",
            borderRadius: "50%",
            animation: "spin 0.9s linear infinite",
          }} />
          <div style={{ fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase" }}>
            Loading catalog…
          </div>
        </div>
      </main>
    );
  } else if (productsState === "error" && needsProducts) {
    page = (
      <main data-screen-label="Error" style={{ minHeight: "60vh", display: "grid", placeItems: "center" }}>
        <div style={{ textAlign: "center", maxWidth: 420, padding: 32 }}>
          <div style={{ fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: "#c4554d", marginBottom: 8 }}>
            Could not load catalog
          </div>
          <p style={{ color: "var(--muted)", fontSize: 14, lineHeight: 1.5 }}>
            {window.PRODUCTS_ERROR || "Unknown error connecting to the database."}
          </p>
          <p style={{ color: "var(--muted)", fontSize: 12, marginTop: 16 }}>
            Check <code>supabase-config.js</code> — make sure URL and anon key are set correctly,
            and that <code>01-schema.sql</code> + <code>03-seed-products.sql</code> have been run.
          </p>
        </div>
      </main>
    );
  } else {
    switch (route) {
      case "shop":    page = <ShopPage navigate={navigate} />; break;
      case "product": page = <ProductPage navigate={navigate} productId={productId} addToCart={addToCart} />; break;
      case "about":   page = <AboutPage navigate={navigate} />; break;
      case "contact": page = <ContactPage navigate={navigate} />; break;
      case "cart":    page = <CartPage navigate={navigate} cart={cart} updateQty={updateQty} removeItem={removeItem} />; break;
      default:        page = <HomePage navigate={navigate} addToCart={addToCart} />;
    }
  }

  return (
    <React.Fragment>
      {t.bgAnim && <BackgroundAnim accent={accent} dark={isDark} />}
      <div style={{ position: "relative", zIndex: 1 }}>
        <Header route={route} navigate={navigate} cartCount={cartCount} darkChrome={darkChrome} />
        {page}
        <Footer navigate={navigate} />
      </div>
      <TweaksPanel>
        <TweakSection label="Brand" />
        <TweakColor
          label="Accent"
          value={t.accent}
          options={ACCENT_OPTIONS}
          onChange={(v) => setTweak("accent", v)}
        />
        <TweakSection label="Layout" />
        <TweakRadio
          label="Density"
          value={t.density}
          options={["compact", "regular", "comfy"]}
          onChange={(v) => setTweak("density", v)}
        />
        <TweakSection label="Background" />
        <TweakToggle
          label="DNA helix scroll"
          value={t.bgAnim}
          onChange={(v) => setTweak("bgAnim", v)}
        />
        <TweakSection label="Theme" />
        <TweakToggle
          label="Dark mode"
          value={t.dark}
          onChange={(v) => setTweak("dark", v)}
        />
      </TweaksPanel>
    </React.Fragment>
  );
}

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