/* JOVI Site — shared components (Header, Footer, ProductCard, CartDrawer)
   Babel transpiled. Exports to window.JM.UI */
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

const JMUI = {};

/* ----- i18n ----- */
const I18nContext = createContext({ lang: "en", t: (k) => k });
JMUI.useI18n = () => useContext(I18nContext);
JMUI.I18nProvider = function I18nProvider({ children }) {
  const [lang, setLang] = useState(() => localStorage.getItem("jm.lang") || "en");
  useEffect(() => { localStorage.setItem("jm.lang", lang); document.documentElement.lang = lang; }, [lang]);
  const t = (key, fallback) => (JM.STRINGS[lang] && JM.STRINGS[lang][key]) || JM.STRINGS.en[key] || fallback || key;
  const tt = (obj) => (obj && (obj[lang] || obj.en)) || "";
  return <I18nContext.Provider value={{ lang, setLang, t, tt }}>{children}</I18nContext.Provider>;
};

/* ----- Cart store ----- */
const CartContext = createContext(null);
JMUI.useCart = () => useContext(CartContext);
JMUI.CartProvider = function CartProvider({ children }) {
  const [items, setItems] = useState(() => {
    try { return JSON.parse(localStorage.getItem("jm.cart") || "[]"); } catch { return []; }
  });
  const [open, setOpen] = useState(false);
  useEffect(() => { localStorage.setItem("jm.cart", JSON.stringify(items)); }, [items]);
  /* add(product, variantId, qty, weightId?) — distinguishes by variant + weight */
  const add = (product, variantId, qty = 1, weightId = null) => {
    setItems(prev => {
      const wkey = weightId || "_";
      const key = product.id + "::" + variantId + "::" + wkey;
      const ex = prev.find(i => i.key === key);
      if (ex) return prev.map(i => i.key === key ? { ...i, qty: i.qty + qty } : i);
      const v = product.variants.find(x => x.id === variantId) || product.variants[0];
      const w = product.weights ? (product.weights.find(x => x.id === weightId) || product.weights[0]) : null;
      const unit = w ? w.price : product.price;
      const wlabel = w ? w.label : product.weight;
      return [...prev, { key, productId: product.id, variantId: v.id, weightId: w ? w.id : null, qty, price: unit, name: product.name, vname: v.name, wname: wlabel, image: v.image }];
    });
    setOpen(true);
  };
  const update = (key, qty) => setItems(prev => prev.flatMap(i => i.key === key ? (qty <= 0 ? [] : [{ ...i, qty }]) : [i]));
  const remove = (key) => setItems(prev => prev.filter(i => i.key !== key));
  const clear = () => setItems([]);
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const count = items.reduce((s, i) => s + i.qty, 0);
  return <CartContext.Provider value={{ items, add, update, remove, clear, open, setOpen, subtotal, count }}>{children}</CartContext.Provider>;
};

/* ----- Router ----- */
const RouterContext = createContext(null);
JMUI.useRouter = () => useContext(RouterContext);
JMUI.RouterProvider = function RouterProvider({ children }) {
  const parse = () => {
    const h = window.location.hash.replace(/^#\/?/, "") || "home";
    const [page, ...rest] = h.split("/");
    return { page: page || "home", param: rest.join("/") };
  };
  const [route, setRoute] = useState(parse);
  useEffect(() => {
    const onHash = () => { setRoute(parse()); window.scrollTo({ top: 0, behavior: "auto" }); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  const go = (page, param) => { window.location.hash = "#/" + page + (param ? "/" + param : ""); };
  return <RouterContext.Provider value={{ ...route, go }}>{children}</RouterContext.Provider>;
};

/* ----- Logo (uses official JOVI artwork) ----- */
JMUI.Logo = function Logo({ size = 38, variant = "jovi" }) {
  const src = variant === "jm" ? "assets/jm-brands-logo.png" : "assets/jovi-logo.png";
  const alt = variant === "jm" ? "JM Brands Sdn Bhd" : "JOVI";
  const h = variant === "jm" ? size : size * 0.95;
  return <img src={src} alt={alt} style={{ height: h, width: "auto", display: "block" }}/>;
};

/* ----- Header ----- */
JMUI.Header = function Header() {
  const { t, lang, setLang } = JMUI.useI18n();
  const { count, setOpen } = JMUI.useCart();
  const { page, go } = JMUI.useRouter();
  const [mobileOpen, setMobileOpen] = useState(false);
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);
  const goAndClose = (id) => { go(id); setMobileOpen(false); };
  return (
    <header className="hdr">
      <div className="hdr-strip">
        <span>🇪🇸 Made in Spain since 1939</span>
        <span style={{margin:"0 12px", opacity:.4}}>·</span>
        <span><strong>{t("freeship")}</strong></span>
        <span style={{margin:"0 12px", opacity:.4}}>·</span>
        <span>JM Brands · Official JOVI Distributor in Malaysia</span>
      </div>
      <div className="container hdr-row">
        <button className="hdr-burger" aria-label="Open menu" aria-expanded={mobileOpen} onClick={()=>setMobileOpen(true)}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
        </button>
        <a href="#/home" className="hdr-logo" onClick={(e)=>{e.preventDefault(); go("home");}}>
          <JMUI.Logo size={36}/>
          <span className="hdr-logo-divider" style={{display:"inline-block", width:1, height:30, background:"rgba(0,0,0,.12)", margin:"0 4px"}}/>
          <JMUI.Logo size={32} variant="jm"/>
        </a>
        <nav className="hdr-nav">
          {JM.NAV.map(n => (
            <a key={n.id} href={"#/"+n.id}
               className={page === n.id ? "active" : ""}
               onClick={(e)=>{e.preventDefault(); go(n.id);}}>{t(n.labelKey)}</a>
          ))}
        </nav>
        <div className="hdr-actions">
          <div className="lang-pill hdr-lang-desktop">
            {["en","bm","zh"].map(l => (
              <button key={l} className={lang === l ? "active" : ""} onClick={()=>setLang(l)}>
                {l === "en" ? "EN" : l === "bm" ? "BM" : "中文"}
              </button>
            ))}
          </div>
          <button className="hdr-icon-btn hdr-search-desktop" aria-label="Search">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3-3"/></svg>
          </button>
          <button className="hdr-icon-btn" aria-label="Cart" onClick={()=>setOpen(true)}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2"><path d="M3 6h2l2.5 12h11L21 9H6"/><circle cx="9" cy="21" r="1.5"/><circle cx="18" cy="21" r="1.5"/></svg>
            {count > 0 && <span className="badge">{count}</span>}
          </button>
        </div>
      </div>

      {mobileOpen && (
        <div className="mobile-menu" role="dialog" aria-modal="true" aria-label="Site menu">
          <div className="mm-scrim" onClick={()=>setMobileOpen(false)}/>
          <div className="mm-panel">
            <div className="mm-head">
              <JMUI.Logo size={32}/>
              <button className="mm-close" aria-label="Close menu" onClick={()=>setMobileOpen(false)}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
              </button>
            </div>
            <nav className="mm-nav">
              {JM.NAV.map(n => (
                <a key={n.id} href={"#/"+n.id}
                   className={page === n.id ? "active" : ""}
                   onClick={(e)=>{e.preventDefault(); goAndClose(n.id);}}>
                  {t(n.labelKey)}
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M9 6l6 6-6 6"/></svg>
                </a>
              ))}
            </nav>
            <div className="mm-foot">
              <div className="mm-lang-label">Language · Bahasa · 语言</div>
              <div className="lang-pill mm-lang">
                {["en","bm","zh"].map(l => (
                  <button key={l} className={lang === l ? "active" : ""} onClick={()=>setLang(l)}>
                    {l === "en" ? "EN" : l === "bm" ? "BM" : "中文"}
                  </button>
                ))}
              </div>
              <a href="https://wa.me/60136067062" target="_blank" rel="noreferrer" className="mm-wa">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 14.4c-.3-.1-1.7-.8-1.9-.9-.3-.1-.5-.1-.7.1-.2.3-.8.9-1 1.1-.2.2-.4.2-.7.1-.3-.1-1.2-.4-2.2-1.4-.8-.7-1.4-1.6-1.5-1.9-.2-.3 0-.4.1-.6.1-.1.3-.4.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5-.1-.1-.7-1.7-1-2.3-.3-.6-.5-.5-.7-.5h-.6c-.2 0-.5.1-.8.4-.3.3-1 1-1 2.5s1 2.9 1.2 3.1c.1.2 2 3.1 4.9 4.3 2.9 1.2 2.9.8 3.4.7.5-.1 1.7-.7 1.9-1.4.2-.7.2-1.2.2-1.4-.1-.1-.3-.2-.6-.3zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.3c1.4.8 3 1.3 4.8 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2z"/></svg>
                <span>WhatsApp +60 13-606 7062</span>
              </a>
            </div>
          </div>
        </div>
      )}
    </header>
  );
};

/* ----- ProductCard
   - For products with weight tiers, shows "from RMxx.xx · 250 g+"
   - Weight + price stay on one line; rating moves to its own line
   - Inline weight selector dropdown when present
   - Add to cart respects selected weight */
JMUI.ProductCard = function ProductCard({ product }) {
  const { tt, t } = JMUI.useI18n();
  const { add } = JMUI.useCart();
  const { go } = JMUI.useRouter();
  const cat = JM.CATEGORIES.find(c => c.id === product.category);
  const hasWeights = !!(product.weights && product.weights.length > 1);
  const [wId, setWId] = useState(hasWeights ? product.weights[0].id : null);
  const w = hasWeights ? product.weights.find(x => x.id === wId) : null;
  const price = w ? w.price : product.price;
  const wlabel = w ? w.label : product.weight;
  return (
    <article className="prod" onClick={()=>go("product", product.slug)}>
      <div className="prod-img">
        <span className={"prod-tag " + product.category}>{t(cat.labelKey)}</span>
        <img src={product.image} alt={tt(product.name)} />
      </div>
      <div className="prod-body">
        <div className="prod-name">{tt(product.name)}</div>
        <div className="prod-tagline">{tt(product.tagline)}</div>
        <div className="prod-price-row">
          <div className="prod-price">{hasWeights && <span className="from">from </span>}RM{price.toFixed(2)}</div>
          <div className="prod-weight">{wlabel}</div>
        </div>
        <div className="prod-rating-row">
          <span className="prod-stars">★★★★★</span>
          <span className="prod-rate-num">{product.rating}</span>
          <span className="prod-rate-count">({product.reviews})</span>
          {product.variants.length > 1 && (
            <span className="prod-swatches">
              {product.variants.slice(0,4).map(v => <span key={v.id} className="prod-swatch" style={{background:v.swatch}}/>)}
            </span>
          )}
        </div>
        {hasWeights && (
          <select className="prod-weight-pick" value={wId} onClick={(e)=>e.stopPropagation()} onChange={(e)=>{e.stopPropagation(); setWId(e.target.value);}}>
            {product.weights.map(x => <option key={x.id} value={x.id}>{x.label} — RM{x.price.toFixed(2)}</option>)}
          </select>
        )}
        <button className="btn btn-primary prod-cta btn-sm" onClick={(e)=>{e.stopPropagation(); add(product, product.variants[0].id, 1, wId);}}>
          {t("addtocart")} →
        </button>
      </div>
    </article>
  );
};

/* ----- Cart drawer — WhatsApp order flow ----- */
JMUI.CartDrawer = function CartDrawer() {
  const { items, update, remove, open, setOpen, subtotal } = JMUI.useCart();
  const { t, tt, lang } = JMUI.useI18n();
  const buildWA = () => {
    const lines = items.map(i => `• ${tt(i.name)}${i.vname ? " — " + i.vname : ""}${i.wname ? " · " + i.wname : ""} × ${i.qty} = RM${(i.price*i.qty).toFixed(2)}`);
    const greet = lang === "bm" ? "Hai JM Brands! Saya nak pesan:" : lang === "zh" ? "您好 JM Brands！我想下单：" : "Hi JM Brands! I'd like to order:";
    const total = `\n\n${t("cart.subtotal")}: RM${subtotal.toFixed(2)}`;
    const text = encodeURIComponent(`${greet}\n\n${lines.join("\n")}${total}`);
    return `https://wa.me/${JM.ORDER_WHATSAPP}?text=${text}`;
  };
  return (
    <>
      <div className={"drawer-mask" + (open ? " open" : "")} onClick={()=>setOpen(false)} />
      <aside className={"drawer" + (open ? " open" : "")} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>{t("cart.title")} {items.length > 0 && <span style={{color:"var(--fg-3)", fontWeight:500, fontSize:14}}>· {items.length}</span>}</h3>
          <button className="hdr-icon-btn" onClick={()=>setOpen(false)} aria-label="Close">✕</button>
        </div>
        <div className="drawer-body">
          {items.length === 0 ? (
            <div style={{textAlign:"center", padding:"48px 0", color:"var(--fg-3)"}}>
              <div style={{fontSize:48, marginBottom:12}}>🧺</div>
              <p>{t("cart.empty")}</p>
            </div>
          ) : items.map(i => (
            <div key={i.key} className="cart-line">
              <div className="img"><img src={i.image} alt="" /></div>
              <div className="info">
                <div className="name">{tt(i.name)}</div>
                <div className="v">{i.vname}{i.wname ? " · " + i.wname : ""}</div>
                <div className="ctrls">
                  <div className="qty">
                    <button onClick={()=>update(i.key, i.qty - 1)}>−</button>
                    <span>{i.qty}</span>
                    <button onClick={()=>update(i.key, i.qty + 1)}>+</button>
                    <button onClick={()=>remove(i.key)} style={{marginLeft:8, fontSize:11, color:"var(--fg-3)", textDecoration:"underline"}}>remove</button>
                  </div>
                  <div className="price">RM{(i.price * i.qty).toFixed(2)}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div className="drawer-foot">
            <div className="subtotal-row">
              <span className="l">{t("cart.subtotal")}</span>
              <span className="r">RM{subtotal.toFixed(2)}</span>
            </div>
            <div className="cart-checkouts">
              <a className="btn btn-primary" href={buildWA()} target="_blank" rel="noreferrer" style={{background:"#25D366", color:"#fff"}}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor"><path d="M.057 24l1.687-6.163a11.867 11.867 0 0 1-1.587-5.946C.16 5.335 5.495 0 12.05 0a11.81 11.81 0 0 1 8.413 3.488 11.824 11.824 0 0 1 3.48 8.414c-.003 6.557-5.338 11.892-11.893 11.892a11.9 11.9 0 0 1-5.688-1.448L.057 24zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884a9.86 9.86 0 0 0 1.51 5.26l.241.382-1.001 3.658 3.749-.999z"/></svg>
                {t("cart.checkoutwa")}
              </a>
            </div>
            <p className="cart-note">{t("cart.note")}</p>
          </div>
        )}
      </aside>
    </>
  );
};

/* ----- Sticky marketplace buttons ----- */
JMUI.StickyMP = function StickyMP() {
  const { t } = JMUI.useI18n();
  return (
    <div className="sticky-mp">
      <a href={JM.MARKETPLACES.shopee.url} target="_blank" rel="noreferrer">
        <img src={JM.MARKETPLACES.shopee.logo} alt="" /> {t("buyon")} Shopee
      </a>
      <a href={JM.MARKETPLACES.lazada.url} target="_blank" rel="noreferrer" style={{background:"var(--jovi-red)"}}>
        <img src={JM.MARKETPLACES.lazada.logo} alt="" /> {t("buyon")} Lazada
      </a>
      <a href={JM.MARKETPLACES.tiktok.url} target="_blank" rel="noreferrer" style={{background:"#fe2c55"}}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" style={{flex:"0 0 auto"}}><path d="M19.59 6.69a4.83 4.83 0 0 1-3.77-4.25V2h-3.45v13.67a2.89 2.89 0 0 1-5.2 1.74 2.89 2.89 0 0 1 2.31-4.64 2.93 2.93 0 0 1 .88.13V9.4a6.84 6.84 0 0 0-1-.05A6.33 6.33 0 0 0 5.8 20.1a6.34 6.34 0 0 0 10.86-4.43V8.86a8.16 8.16 0 0 0 4.77 1.52V6.93a4.85 4.85 0 0 1-1.84-.24z"/></svg>
        {t("buyon")} TikTok
      </a>
    </div>
  );
};

/* ----- Newsletter ----- */
JMUI.Newsletter = function Newsletter() {
  const { t } = JMUI.useI18n();
  const [email, setEmail] = useState("");
  const [done, setDone] = useState(false);
  return (
    <section className="newsletter">
      <div className="container">
        <div className="newsletter-inner">
          <div>
            <h2>{t("newsletter.title")}</h2>
            <p>{t("newsletter.body")}</p>
          </div>
          {done ? (
            <div style={{padding:"16px 20px", background:"var(--jovi-yellow)", color:"var(--jovi-red)", borderRadius:999, fontWeight:700, textAlign:"center"}}>
              ✔ Thanks — see you in your inbox.
            </div>
          ) : (
            <form className="form" onSubmit={(e)=>{e.preventDefault(); if(email) setDone(true);}}>
              <input type="email" placeholder={t("newsletter.placeholder")} value={email} onChange={e=>setEmail(e.target.value)} required/>
              <button className="btn btn-yellow" type="submit">{t("newsletter.cta")}</button>
            </form>
          )}
        </div>
      </div>
    </section>
  );
};

/* ----- Footer (logos blend with dark bg, no white plate) ----- */
JMUI.Footer = function Footer() {
  const { t } = JMUI.useI18n();
  const { go } = JMUI.useRouter();
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="footer-logo">
              <JMUI.Logo size={40}/>
              <span style={{display:"inline-block", width:1, height:30, background:"rgba(255,220,0,.25)"}}/>
              <JMUI.Logo size={36} variant="jm"/>
            </div>
            <p style={{fontSize:14, lineHeight:1.6, maxWidth:340, color:"rgba(255,220,0,.75)", marginTop:14}}>
              JM Brands Sdn Bhd is the official & exclusive JOVI distributor in Malaysia — bringing JOVI's 87-year European craft heritage to Malaysian classrooms, studios and homes.
            </p>
            <div className="marketplace-row" style={{marginTop:18}}>
              <a href={JM.MARKETPLACES.shopee.url} target="_blank" rel="noreferrer"><img src={JM.MARKETPLACES.shopee.logo} alt="Shopee"/></a>
              <a href={JM.MARKETPLACES.lazada.url} target="_blank" rel="noreferrer"><img src={JM.MARKETPLACES.lazada.logo} alt="Lazada"/></a>
              <a href={JM.MARKETPLACES.tiktok.url} target="_blank" rel="noreferrer"><img src={JM.MARKETPLACES.tiktok.logo} alt="TikTok"/></a>
            </div>
          </div>
          <div>
            <h5>Shop</h5>
            <ul>
              <li><a href="#/shop" onClick={(e)=>{e.preventDefault(); go("shop");}}>All products</a></li>
              <li><a href="#/shop">Air Dry Clay</a></li>
              <li><a href="#/shop">Plastilina</a></li>
              <li><a href="#/shop">Modelling tools</a></li>
            </ul>
          </div>
          <div>
            <h5>Brand</h5>
            <ul>
              <li><a href="#/about" onClick={(e)=>{e.preventDefault(); go("about");}}>About JM Brands</a></li>
              <li><a href="#/schools" onClick={(e)=>{e.preventDefault(); go("schools");}}>For schools</a></li>
              <li><a href="#/creates" onClick={(e)=>{e.preventDefault(); go("creates");}}>#JoviCreates</a></li>
              <li><a href="#/blog" onClick={(e)=>{e.preventDefault(); go("blog");}}>Journal</a></li>
            </ul>
          </div>
          <div>
            <h5>Help</h5>
            <ul>
              <li><a href="#/faq" onClick={(e)=>{e.preventDefault(); go("faq");}}>FAQ</a></li>
              <li><a href="#/contact" onClick={(e)=>{e.preventDefault(); go("contact");}}>Contact</a></li>
              <li><a href="#/contact">Wholesale enquiry</a></li>
              <li><a href="mailto:info@jmbrands.com.my">info@jmbrands.com.my</a></li>
              <li><a href="https://wa.me/60136067062" target="_blank" rel="noreferrer">WhatsApp +60 13-606 7062</a></li>
            </ul>
          </div>
        </div>
        <div className="legal">
          <span>{t("footer.legal")}</span>
          <span>© 2026 JM Brands Sdn Bhd · JOVI® is a trademark of Jovi S.A., Spain</span>
        </div>
      </div>
    </footer>
  );
};

window.JMUI = JMUI;
