/* ============================================================
   EMAGINE BY BUKOLA — App shell: routing, global state, tweaks
   Hand-beaded couture · Made in Nigeria · Worn Worldwide
   ============================================================ */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "palette": ["#0a0a0a", "#c9a84c", "#faf5ee"],
  "btnStyle": "pill",
  "headlineFont": "'Cormorant Garamond', Georgia, serif",
  "heroHeadline": "Hand-beaded. Unforgettable.",
  "heroSub": "Emagine by Bukola is a Nigerian luxury womenswear atelier — hand-beaded couture with fluid lines and quiet-luxury detailing, made in Lagos and worn worldwide."
}/*EDITMODE-END*/;

const PALETTE_MAP = {
  "#0a0a0a": "noir",
  "#0a1a10": "emerald",
  "#2a0e16": "burgundy",
  "#1a0a2a": "purple",
};
const PALETTE_OPTS = [
  ["#0a0a0a", "#c9a84c", "#faf5ee"],
  ["#0a1a10", "#c8a24a", "#f4efe4"],
  ["#2a0e16", "#cba36a", "#faf0ee"],
  ["#1a0a2a", "#d2b86a", "#faf4f8"],
];
const FONT_OPTS = [
  { value: "'Cormorant Garamond', Georgia, serif", label: "Cormorant (elegant)" },
  { value: "'Playfair Display', Georgia, serif", label: "Playfair (editorial)" },
  { value: "'Marcellus', Georgia, serif", label: "Marcellus (roman)" },
  { value: "'Bodoni Moda', Georgia, serif", label: "Bodoni (high-fashion)" },
];

const store = {
  get(k, d) { try { const v = localStorage.getItem("rb_" + k); return v ? JSON.parse(v) : d; } catch { return d; } },
  set(k, v) { try { localStorage.setItem("rb_" + 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", "NGN"));
  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 — theme is always light per brand guidelines */
  useEffect(() => {
    const r = document.documentElement;
    r.setAttribute("data-theme", "light");
    const pal = PALETTE_MAP[(t.palette && t.palette[0]) || "#0a0a0a"] || "noir";
    r.setAttribute("data-palette", pal);
    r.setAttribute("data-btn", t.btnStyle || "pill");
    r.style.setProperty("--font-display", t.headlineFont || "'Cormorant Garamond', 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);

  const addToCart = (p, opts = {}) => {
    const size = opts.size || p.sizes[0];
    const color = opts.color || p.colors[0].name;
    const qty = opts.qty || 1;
    const key = p.id + "|" + size + "|" + 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,
  };

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

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

      <TweaksPanel title="Tweaks">
        <TweakSection label="Look" />
        <TweakColor label="Accent 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)} />
        <TweakSelect label="Headline font" value={t.headlineFont} options={FONT_OPTS} onChange={(v) => setTweak("headlineFont", v)} />

        <TweakSection label="Hero" />
        <TweakText label="Headline" value={t.heroHeadline} onChange={(v) => setTweak("heroHeadline", v)} />
        <TweakText label="Subtext" value={t.heroSub} onChange={(v) => setTweak("heroSub", v)} />
        <TweakButton label="View homepage" secondary onClick={() => onNav("home", {})} />
      </TweaksPanel>
    </RBCtx.Provider>
  );
}

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