/* ============================================================
   ADORN — App shell: routing, global state, tweaks
   ============================================================ */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#4c453e", "#201d1a", "#f8f5f0"],
  "btnStyle": "solid",
  "heroLayout": "collage",
  "headlineFont": "'Cormorant Garamond', Georgia, serif",
  "heroHeadline": "The finishing touch."
}/*EDITMODE-END*/;

const PALETTE_MAP = {
  "#8a5f33": "brass",
  "#a35438": "terracotta",
  "#6d6d3f": "olive",
  "#4c453e": "noir",
};
const PALETTE_OPTS = [
  ["#4c453e", "#201d1a", "#f8f5f0"],
  ["#8a5f33", "#2b2118", "#faf6ee"],
  ["#a35438", "#2e211c", "#faf5ef"],
  ["#6d6d3f", "#262619", "#f9f7ee"],
];
const FONT_OPTS = [
  { value: "'Cormorant Garamond', Georgia, serif", label: "Cormorant (editorial serif)" },
  { value: "Georgia, 'Times New Roman', serif", label: "Georgia (classic serif)" },
  { value: "'Jost', Helvetica, sans-serif", label: "Jost (modern sans)" },
];

const store = {
  get(k, d) { try { const v = localStorage.getItem("adorn_" + k); return v ? JSON.parse(v) : d; } catch { return d; } },
  set(k, v) { try { localStorage.setItem("adorn_" + k, JSON.stringify(v)); } catch {} },
};

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = useState({ name: "home", params: {} });
  const [currency, setCurrencyState] = useState(() => store.get("currency", (window.BRAND && window.BRAND.currency.altCode) || "USD"));
  const [cart, setCart] = useState(() => store.get("cart", []));
  const [wishlist, setWishlist] = useState(() => store.get("wishlist", []));
  const [cartOpen, setCartOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  /* apply tweaks to document root — light theme only, house palettes */
  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute("data-theme", "light");
    const pal = PALETTE_MAP[(t.palette && t.palette[0]) || "#4c453e"] || "noir";
    r.setAttribute("data-palette", pal);
    r.setAttribute("data-btn", t.btnStyle || "solid");
    r.style.setProperty("--font-display", t.headlineFont || "'Cormorant Garamond', Georgia, serif");
  }, [t.palette, t.btnStyle, t.headlineFont]);

  /* persist */
  useEffect(() => store.set("currency", currency), [currency]);
  useEffect(() => store.set("cart", cart), [cart]);
  useEffect(() => store.set("wishlist", wishlist), [wishlist]);

  /* lock scroll when overlays open */
  useEffect(() => {
    document.body.classList.toggle("no-scroll", cartOpen || searchOpen);
  }, [cartOpen, searchOpen]);

  const onNav = (name, params = {}) => {
    setRoute({ name, params });
    setCartOpen(false); setSearchOpen(false);
    window.scrollTo({ top: 0, behavior: "auto" });
  };

  const setCurrency = (c) => setCurrencyState(c);

  /* size is OPTIONAL — most accessory categories never have one */
  const addToCart = (p, opts = {}) => {
    const size = opts.size || null;
    const color = opts.color || p.colors[0].name;
    const qty = opts.qty || 1;
    const key = p.id + "|" + (size || "std") + "|" + color;
    setCart((prev) => {
      const ex = prev.find((x) => x.key === key);
      if (ex) return prev.map((x) => x.key === key ? { ...x, qty: x.qty + qty } : x);
      return [...prev, { key, id: p.id, name: p.name, price: p.price, label: p.label, size, color, qty }];
    });
  };
  const updateQty = (key, d) => setCart((prev) => prev.map((x) => x.key === key ? { ...x, qty: Math.max(1, x.qty + d) } : x));
  const removeFromCart = (key) => setCart((prev) => prev.filter((x) => x.key !== key));
  const clearCart = () => setCart([]);
  const toggleWish = (id) => setWishlist((prev) => prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id]);

  const cartCount = cart.reduce((s, x) => s + x.qty, 0);
  const cartTotal = cart.reduce((s, x) => s + x.price * x.qty, 0);

  const ctx = {
    currency, setCurrency,
    cart, addToCart, updateQty, removeFromCart, clearCart, cartCount, cartTotal,
    wishlist, toggleWish, wishCount: wishlist.length,
    cartOpen, openCart: () => setCartOpen(true), closeCart: () => setCartOpen(false),
    searchOpen, openSearch: () => setSearchOpen(true), closeSearch: () => setSearchOpen(false),
    onNav,
  };
  useEffect(() => { window.__adorn = ctx; window.__nav = onNav; });

  const PAGES = {
    home: HomePage, shop: ShopPage, collections: CollectionsPage, product: ProductPage,
    lookbook: LookbookPage, cart: CartPage, checkout: CheckoutPage, track: TrackOrderPage,
    about: AboutPage, contact: ContactPage, account: AccountPage, wishlist: WishlistPage,
  };
  const Page = PAGES[route.name] || HomePage;
  const hideChrome = route.name === "checkout";

  return (
    <RBCtx.Provider value={ctx}>
      {!hideChrome && <Header route={route} onNav={onNav} heroLayout={t.heroLayout} />}
      <main>
        <Page route={route} onNav={onNav} tweaks={t} />
      </main>
      {!hideChrome && <Footer onNav={onNav} />}
      <CartDrawer />
      <SearchOverlay />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme" />
        <TweakColor label="Palette" value={t.palette} options={PALETTE_OPTS} onChange={(v) => setTweak("palette", v)} />
        <TweakSelect label="Button style" value={t.btnStyle}
          options={[{ value: "solid", label: "Solid" }, { value: "outline", label: "Outline" }, { value: "minimal", label: "Minimal (underline)" }, { value: "pill", label: "Pill" }]}
          onChange={(v) => setTweak("btnStyle", v)} />

        <TweakSection label="Typography" />
        <TweakSelect label="Headline font" value={t.headlineFont} options={FONT_OPTS} onChange={(v) => setTweak("headlineFont", v)} />

        <TweakSection label="Hero" />
        <TweakSelect label="Layout" value={t.heroLayout}
          options={[
            { value: "collage", label: "★ Collage — multi-panel grid (default)" },
            { value: "split", label: "Editorial split" },
            { value: "centered", label: "Full-bleed image" },
            { value: "stacked", label: "Typographic stack" },
          ]}
          onChange={(v) => { setTweak("heroLayout", v); if (route.name !== "home") onNav("home", {}); }} />
        <TweakText label="Headline" value={t.heroHeadline} onChange={(v) => setTweak("heroHeadline", v)} />
        <TweakButton label="View homepage hero" secondary onClick={() => onNav("home", {})} />
      </TweaksPanel>
    </RBCtx.Provider>
  );
}

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