/* global React, ReactDOM */
const { useState: useStateA, useEffect: useEffectA } = React;

/* =========================================================
   APP ROOT — router, providers, cart state
   ========================================================= */
function App() {
  const route = useRoute();
  const [lang, setLang] = useStateA("en");
  const [cart, setCart] = useStateA([]);
  const [cartOpen, setCartOpen] = useStateA(false);
  const [toast, setToast] = useStateA("");

  // Tweaks — defaults wrapped for EDITMODE persistence
  const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
    "palette": "gold",
    "density": "default",
    "hero": "maker",
    "showOOAKBadges": true,
    "introQuote": "This is luxury now. The handmade and unique."
  }/*EDITMODE-END*/;
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply tweaks at document level
  useEffectA(() => {
    document.documentElement.setAttribute("data-palette", t.palette);
    document.documentElement.setAttribute("data-density", t.density);
    document.documentElement.setAttribute("data-ooak", t.showOOAKBadges ? "on" : "off");
    document.documentElement.setAttribute("dir", lang === "ar" ? "rtl" : "ltr");
    document.documentElement.lang = lang;
  }, [t.palette, t.density, t.showOOAKBadges, lang]);

  // Cart helpers
  const addToCart = (p, qty = 1) => {
    setCart((prev) => {
      const i = prev.findIndex(x => x.id === p.id);
      if (i >= 0) {
        const next = prev.slice();
        next[i] = { ...next[i], qty: next[i].qty + qty };
        return next;
      }
      return [...prev, { id: p.id, name: p.name, img: p.img, price: p.price, type: p.type, material: p.material, qty }];
    });
    setToast("Added to bag · " + p.name.slice(0, 40));
    setTimeout(() => setToast(""), 2200);
    setCartOpen(true);
  };
  const removeFromCart = (id) => setCart((prev) => prev.filter(x => x.id !== id));
  const setQty = (id, q) => setCart((prev) => {
    if (q < 1) return prev.filter(x => x.id !== id);
    return prev.map(x => x.id === id ? { ...x, qty: q } : x);
  });

  const ctx = {
    route, lang, setLang,
    cart, addToCart, removeFromCart, setQty,
    cartOpen, openCart: () => setCartOpen(true), closeCart: () => setCartOpen(false),
    toast,
    palette: t.palette, density: t.density, hero: t.hero,
    introQuote: t.introQuote, showOOAKBadges: t.showOOAKBadges
  };

  // Routing
  let page;
  const segs = route.segments;
  if (segs.length === 0) page = <HomePage />;
  else if (segs[0] === "story") page = <StoryPage />;
  else if (segs[0] === "fashion") page = <FashionPage />;
  else if (segs[0] === "home-decor") page = <DecorPage />;
  else if (segs[0] === "sustainability") page = <SustainabilityPage />;
  else if (segs[0] === "boutique") page = <BoutiquePage />;
  else if (segs[0] === "contact") page = <ContactPage />;
  else if (segs[0] === "journal" && segs[1]) page = <JournalDetailPage slug={segs[1]} />;
  else if (segs[0] === "journal") page = <JournalPage />;
  else if (segs[0] === "product" && segs[1]) page = <ProductPage id={segs[1]} />;
  else page = <HomePage />;

  // Palette options — first hex is the "primary" for that palette
  const palettes = [
    ["#BF9F58", "#9C6B45", "#33405B"], // gold
    ["#9C6B45", "#7e5535", "#241B14"], // copper
    ["#33405B", "#232c40", "#BF9F58"]  // indigo
  ];
  const paletteName = { "#BF9F58": "gold", "#9C6B45": "copper", "#33405B": "indigo" };
  const currentPalette = palettes.find(p => paletteName[p[0]] === t.palette) || palettes[0];

  return (
    <AppCtx.Provider value={ctx}>
      <Nav />
      {page}
      <Footer />
      <CartDrawer />
      <Toast />
      <TweaksPanel title="Tweaks">
        <TweakSection label="Brand">
          <TweakColor
            label="Accent palette"
            value={currentPalette}
            options={palettes}
            onChange={(opt) => setTweak("palette", paletteName[opt[0]])}
          />
        </TweakSection>
        <TweakSection label="Layout">
          <TweakRadio
            label="Density"
            value={t.density}
            options={["cozy", "default", "airy"]}
            onChange={(v) => setTweak("density", v)}
          />
          <TweakSelect
            label="Home hero"
            value={t.hero}
            options={[
              { value: "maker",   label: "Maker portrait (placeholder)" },
              { value: "garment", label: "Hero garment · Kawthar" },
              { value: "decor",   label: "Hero décor · Beirut Lightbulbs" }
            ]}
            onChange={(v) => setTweak("hero", v)}
          />
          <TweakToggle
            label="One-of-a-kind badges"
            value={t.showOOAKBadges}
            onChange={(v) => setTweak("showOOAKBadges", v)}
          />
        </TweakSection>
        <TweakSection label="Voice">
          <TweakText
            label="Pull-quote"
            value={t.introQuote}
            placeholder="One short editorial line…"
            onChange={(v) => setTweak("introQuote", v)}
          />
        </TweakSection>
      </TweaksPanel>
    </AppCtx.Provider>
  );
}

/* =========================================================
   Hide OOAK badges via root flag (CSS in styles.css uses it)
   ========================================================= */

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