// Shared components

const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

const StoreCtx = createContext(null);
window.useStore = () => useContext(StoreCtx);

// ===== Store Provider =====
function MaskaStore({ children }) {
  const [lang, setLang] = useState(() => localStorage.getItem("maska_lang") || "en");
  const [currency, setCurrency] = useState(() => localStorage.getItem("maska_ccy") || "AED");
  const [cart, setCart] = useState(() => {
    try { return JSON.parse(localStorage.getItem("maska_cart") || "[]"); } catch { return []; }
  });
  const [cartOpen, setCartOpen] = useState(false);
  const [toast, setToast] = useState(null);
  const [giftMsg, setGiftMsg] = useState(() => localStorage.getItem("maska_giftmsg") || "");

  useEffect(() => { localStorage.setItem("maska_lang", lang); document.documentElement.lang = lang; document.documentElement.dir = lang === "ar" ? "rtl" : "ltr"; }, [lang]);
  useEffect(() => { localStorage.setItem("maska_ccy", currency); }, [currency]);
  useEffect(() => { localStorage.setItem("maska_cart", JSON.stringify(cart)); }, [cart]);
  useEffect(() => { localStorage.setItem("maska_giftmsg", giftMsg); }, [giftMsg]);

  function t(key) {
    const dict = MASKA_CONTENT.i18n[lang] || MASKA_CONTENT.i18n.en;
    return dict[key] || MASKA_CONTENT.i18n.en[key] || key;
  }

  function addToCart(product, variantTitle = null, qty = 1) {
    const key = product.handle + (variantTitle ? "::" + variantTitle : "");
    setCart(prev => {
      const ex = prev.find(i => i.key === key);
      if (ex) return prev.map(i => i.key === key ? { ...i, qty: i.qty + qty } : i);
      return [...prev, { key, handle: product.handle, title: product.title, price: product.price, image: product.images[0], variantTitle, qty }];
    });
    setToast({ msg: t("added_to_bag"), title: product.title });
    setTimeout(() => setToast(null), 2200);
  }

  function removeFromCart(key) { setCart(prev => prev.filter(i => i.key !== key)); }
  function updateQty(key, qty) {
    if (qty < 1) return removeFromCart(key);
    setCart(prev => prev.map(i => i.key === key ? { ...i, qty } : i));
  }

  const subtotal = cart.reduce((s, i) => s + parseFloat(i.price) * i.qty, 0);
  const cartCount = cart.reduce((s, i) => s + i.qty, 0);

  // Currency conversion (illustrative — AED is base)
  const rates = { AED: 1, USD: 0.272, EUR: 0.251, GBP: 0.215, SAR: 1.02 };
  function formatPrice(aedPrice, opts = {}) {
    const num = parseFloat(aedPrice);
    if (isNaN(num)) return "";
    const rate = rates[currency] || 1;
    const v = num * rate;
    const sym = { AED: "AED", USD: "USD", EUR: "EUR", GBP: "GBP", SAR: "SAR" }[currency] || currency;
    return { ccy: sym, num: v.toFixed(2) };
  }

  const value = {
    lang, setLang, t,
    currency, setCurrency, formatPrice,
    cart, addToCart, removeFromCart, updateQty,
    cartOpen, setCartOpen,
    subtotal, cartCount,
    toast,
    giftMsg, setGiftMsg,
  };

  return React.createElement(StoreCtx.Provider, { value }, children);
}
window.MaskaStore = MaskaStore;

// ===== Router (hash-based) =====
function useRoute() {
  const [hash, setHash] = useState(() => window.location.hash.slice(1) || "/");
  useEffect(() => {
    const onHash = () => { setHash(window.location.hash.slice(1) || "/"); window.scrollTo(0, 0); };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);
  return hash;
}
window.useRoute = useRoute;

function navigate(to) {
  window.location.hash = to;
}
window.navigate = navigate;

// ===== Icons =====
const Icon = {
  search: (p={}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>,
  bag: (p={}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M6 8h12l-1 12H7L6 8z"/><path d="M9 8V6a3 3 0 0 1 6 0v2"/></svg>,
  user: (p={}) => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>,
  arrow: (p={}) => <svg className="arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" {...p}><path d="M5 12h14m-6-6 6 6-6 6"/></svg>,
  close: (p={}) => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="m6 6 12 12M18 6 6 18"/></svg>,
  plus: (p={}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M12 5v14M5 12h14"/></svg>,
  minus: (p={}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M5 12h14"/></svg>,
  whatsapp: (p={}) => <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor" {...p}><path d="M12.04 2C6.58 2 2.13 6.45 2.13 11.91c0 1.75.46 3.45 1.32 4.95L2 22l5.25-1.38a9.94 9.94 0 0 0 4.79 1.22h.01c5.46 0 9.91-4.45 9.91-9.91 0-2.65-1.03-5.14-2.9-7.01A9.87 9.87 0 0 0 12.04 2zm5.83 14.16c-.25.7-1.44 1.34-2 1.42-.51.08-1.16.11-1.87-.12-.43-.14-.99-.32-1.7-.63-2.99-1.29-4.94-4.3-5.09-4.5-.15-.2-1.22-1.62-1.22-3.1 0-1.47.77-2.2 1.05-2.5.27-.3.6-.38.8-.38.2 0 .4 0 .57.01.18.01.43-.07.67.51.25.6.85 2.07.92 2.22.07.15.12.32.02.52-.1.2-.15.32-.3.5-.15.18-.31.4-.45.54-.15.15-.3.31-.13.6.17.3.78 1.28 1.67 2.07 1.15 1.02 2.11 1.34 2.41 1.49.3.15.47.13.65-.08.18-.2.75-.87.95-1.17.2-.3.4-.25.67-.15.27.1 1.72.81 2.02.96.3.15.5.22.57.35.07.13.07.75-.18 1.45z"/></svg>,
  globe: (p={}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>,
  chevron: (p={}) => <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" {...p}><path d="m6 9 6 6 6-6"/></svg>,
  pin: (p={}) => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" {...p}><path d="M12 2a7 7 0 0 1 7 7c0 5-7 13-7 13S5 14 5 9a7 7 0 0 1 7-7z"/><circle cx="12" cy="9" r="2.5"/></svg>,
};
window.Icon = Icon;

// ===== Brand Mark (uses logo) =====
function BrandMark({ inverse = false }) {
  return (
    <a href="#/" className="nav-brand" aria-label="MASKA home">
      <span className="nav-brand-mark">
        <img src={inverse ? "media/maska-logo-white.svg" : "media/maska-logo-official.webp"} alt="MASKA" onError={(e) => { e.target.style.display = "none"; }}/>
      </span>
      <span className="nav-brand-text">MASKA</span>
    </a>
  );
}
window.BrandMark = BrandMark;

// ===== Topbar (ticker + lang/currency) =====
function Topbar() {
  const { lang, setLang, currency, setCurrency, t } = window.useStore();
  const items = lang === "ar" ? [
    "موطن الفوروشيكي في دبي",
    "توصيل مجاني داخل الدولة عند الشراء فوق 250 درهم",
    "خدمة من الباب إلى الباب في دبي",
    "هدايا مصممة يدوياً منذ 2013",
    "قابل لإعادة الاستخدام بالتصميم",
  ] : [
    "Dubai's home of Furoshiki",
    "Complimentary UAE shipping over AED 250",
    "Door-to-door wrapping across Dubai",
    "Handmade in our d3 studio since 2013",
    "Reusable by design",
  ];
  return (
    <div className="topbar">
      <div className="shell">
        <div className="marquee-track">
          <div className="marquee-inner">
            {[...items, ...items].map((s, i) => <span key={i}><span className="dot"/>{s}</span>)}
          </div>
        </div>
        <div className="topbar-actions">
          <button onClick={() => setLang(lang === "en" ? "ar" : "en")}>
            <Icon.globe /> {lang === "en" ? "عربي" : "EN"}
          </button>
          <div className="sep"/>
          <button onClick={() => {
            const opts = ["AED","USD","EUR","GBP","SAR"];
            setCurrency(opts[(opts.indexOf(currency)+1) % opts.length]);
          }}>
            {currency} <Icon.chevron />
          </button>
        </div>
      </div>
    </div>
  );
}
window.Topbar = Topbar;

// ===== Navbar =====
function Navbar({ heroMode = false }) {
  const { t, setCartOpen, cartCount, lang } = window.useStore();
  const route = useRoute();
  const [scrolled, setScrolled] = useState(false);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 50);
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const isHero = heroMode && !scrolled;

  return (
    <nav className={"navbar " + (isHero ? "hero-mode" : "")}>
      <div className="shell">
        <div className="nav-row">
          <div className="nav-left">
            <div className="nav-link-wrap">
              <button className={"nav-link " + (route.startsWith("/shop") || route.startsWith("/c/") ? "active" : "")}>
                {t("shop")} <Icon.chevron />
              </button>
              <div className="nav-dropdown">
                <div className="nav-dropdown-grid">
                  <div>
                    <div className="nav-dropdown-col-title">{t("shop_by_occasion")}</div>
                    {MASKA_CONTENT.occasions.map(o =>
                      <a key={o.id} href={`#/c/${o.id}`}>{lang === "ar" ? o.ar : o.en}</a>
                    )}
                  </div>
                  <div>
                    <div className="nav-dropdown-col-title">{t("shop_by_type")}</div>
                    {MASKA_CONTENT.types.map(o =>
                      <a key={o.id} href={`#/c/${o.id}`}>{lang === "ar" ? o.ar : o.en}</a>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <div className="nav-link-wrap">
              <button className={"nav-link " + (route === "/services" ? "active" : "")} onClick={() => navigate("/services")}>
                {t("services")} <Icon.chevron />
              </button>
              <div className="nav-dropdown" style={{minWidth: 240}}>
                <a href="#/services#in-store">{t("in_store_wrapping")}</a>
                <a href="#/services#door-to-door">{t("door_to_door")}</a>
              </div>
            </div>

            <button className={"nav-link " + (route === "/corporate" ? "active" : "")} onClick={() => navigate("/corporate")}>
              {t("corporate")}
            </button>
            <button className={"nav-link " + (route === "/our-story" ? "active" : "")} onClick={() => navigate("/our-story")}>
              {t("our_story")}
            </button>
          </div>

          <BrandMark inverse={isHero}/>

          <div className="nav-right">
            <button className={"nav-link " + (route === "/stores" ? "active" : "")} onClick={() => navigate("/stores")}>
              {t("stores")}
            </button>
            <button className={"nav-link " + (route === "/contact" ? "active" : "")} onClick={() => navigate("/contact")}>
              {t("contact")}
            </button>
            <a href="#/corporate" className="nav-corp-cta">{t("corporate_cta")}</a>
            <button className="nav-icon-btn" onClick={() => setCartOpen(true)} aria-label={t("cart")}>
              <Icon.bag/>
              {cartCount > 0 && <span className="cart-count">{cartCount}</span>}
            </button>
          </div>
        </div>
      </div>
    </nav>
  );
}
window.Navbar = Navbar;

// ===== Cart Drawer =====
function CartDrawer() {
  const { cart, cartOpen, setCartOpen, removeFromCart, updateQty, subtotal, formatPrice, t, giftMsg, setGiftMsg } = window.useStore();
  return (
    <>
      <div className={"cart-overlay " + (cartOpen ? "open" : "")} onClick={() => setCartOpen(false)}/>
      <aside className={"cart-drawer " + (cartOpen ? "open" : "")}>
        <div className="cart-head">
          <h3>{t("cart")} <span style={{color:"var(--muted)",fontSize:14}}> · {cart.length}</span></h3>
          <button className="nav-icon-btn" onClick={() => setCartOpen(false)}><Icon.close/></button>
        </div>
        <div className="cart-items">
          {cart.length === 0 && (
            <div className="cart-empty">
              <p style={{fontFamily:"Fraunces, serif", fontSize: 22, fontStyle:"italic", color:"var(--ink)"}}>{t("bag_empty")}</p>
              <p style={{marginTop: 8}}>{t("bag_empty_sub")}</p>
              <button className="btn btn-ghost" style={{marginTop: 24}} onClick={() => { setCartOpen(false); navigate("/shop"); }}>{t("start_shopping")}</button>
            </div>
          )}
          {cart.map(item => {
            const fp = formatPrice(item.price);
            return (
              <div key={item.key} className="cart-item">
                <div className="cart-item-img"><img src={item.image} alt=""/></div>
                <div>
                  <div className="cart-item-title">{item.title}</div>
                  {item.variantTitle && item.variantTitle !== "Default Title" && <div className="cart-item-price">{item.variantTitle}</div>}
                  <div className="cart-item-price">{fp.ccy} {fp.num}</div>
                  <div className="qty-stepper" style={{marginTop: 8, fontSize: 12}}>
                    <button onClick={() => updateQty(item.key, item.qty - 1)}><Icon.minus/></button>
                    <span>{item.qty}</span>
                    <button onClick={() => updateQty(item.key, item.qty + 1)}><Icon.plus/></button>
                  </div>
                  <button className="cart-item-remove" onClick={() => removeFromCart(item.key)}>{t("remove")}</button>
                </div>
                <div style={{fontFamily:"Fraunces, serif", fontSize: 16}}>{(parseFloat(item.price) * item.qty).toFixed(0)}</div>
              </div>
            );
          })}
        </div>
        {cart.length > 0 && (
          <div className="cart-foot">
            <textarea className="gift-msg-field" placeholder={t("gift_message_placeholder")} value={giftMsg} onChange={e => setGiftMsg(e.target.value)}/>
            <div className="cart-subtotal" style={{marginTop:16}}>
              <span>{t("subtotal")}</span>
              <b>{formatPrice(subtotal).ccy} {formatPrice(subtotal).num}</b>
            </div>
            <button className="btn">{t("checkout")} <Icon.arrow/></button>
            <p style={{textAlign:"center", color:"var(--muted)", fontSize:11, letterSpacing:"0.12em", textTransform:"uppercase", marginTop:14}}>
              ↻ {t("reusable")} · {t("handmade_in_dubai")}
            </p>
          </div>
        )}
      </aside>
    </>
  );
}
window.CartDrawer = CartDrawer;

// ===== Toast =====
function Toast() {
  const { toast } = window.useStore();
  return (
    <div className={"toast " + (toast ? "show" : "")}>
      <span className="check">✓</span>
      {toast?.msg} <span style={{opacity:0.6, marginLeft:6}}>· {toast?.title}</span>
    </div>
  );
}
window.Toast = Toast;

// ===== Product Card =====
function ProductCard({ product, onAdd }) {
  const { formatPrice, t, addToCart } = window.useStore();
  const fp = formatPrice(product.price);
  return (
    <a href={`#/product/${product.handle}`} className="product-card">
      <div className="product-card-img">
        <img src={product.images[0]} alt={product.title} loading="lazy"/>
        {product.images[1] && <img className="product-card-img-2" src={product.images[1]} alt="" loading="lazy"/>}
        <button className="product-card-quickadd" onClick={(e) => { e.preventDefault(); addToCart(product); }}>
          + {t("add_to_bag")}
        </button>
      </div>
      <div className="product-card-meta">
        <div className="product-card-title">{product.title}</div>
        <div className="product-card-price"><span className="ccy" style={{fontSize: 11, letterSpacing:"0.08em", color:"var(--muted)", marginRight:4}}>{fp.ccy}</span><span className="price-num">{fp.num}</span></div>
      </div>
    </a>
  );
}
window.ProductCard = ProductCard;

// ===== Footer =====
function Footer() {
  const { t, lang } = window.useStore();
  return (
    <footer className="footer">
      <div className="shell">
        <div className="footer-grid">
          <div className="footer-brand">
            <div className="footer-brand-mark">M<span style={{color:"var(--gold)"}}>·</span>A<span style={{color:"var(--gold)"}}>·</span>S<span style={{color:"var(--gold)"}}>·</span>K<span style={{color:"var(--gold)"}}>·</span>A</div>
            <p>{t("footer_about")}</p>
            <div style={{marginTop: 20}}>
              <div style={{color: "var(--gold)", fontSize: 11, letterSpacing: "0.16em", textTransform:"uppercase", marginBottom: 8}}>{t("footer_newsletter")}</div>
              <p style={{color:"rgba(246,239,228,0.6)", fontSize:13, marginTop:0}}>{t("footer_newsletter_sub")}</p>
              <div className="newsletter-row">
                <input type="email" placeholder={t("email_placeholder")}/>
                <button>{t("subscribe")}</button>
              </div>
            </div>
          </div>

          <div className="footer-col">
            <h5>{t("footer_shop")}</h5>
            {MASKA_CONTENT.occasions.slice(0, 6).map(o => <a key={o.id} href={`#/c/${o.id}`}>{lang === "ar" ? o.ar : o.en}</a>)}
          </div>

          <div className="footer-col">
            <h5>{t("footer_services")}</h5>
            <a href="#/services">{t("in_store_wrapping")}</a>
            <a href="#/services">{t("door_to_door")}</a>
            <a href="#/corporate">{t("corporate_cta")}</a>
            <a href="#/c/giftsets">{lang === "ar" ? "هدايا الشركات" : "Bulk gifting"}</a>
          </div>

          <div className="footer-col">
            <h5>{t("footer_company")}</h5>
            <a href="#/our-story">{t("our_story")}</a>
            <a href="#/our-story">{lang === "ar" ? "الاستدامة" : "Sustainability"}</a>
            <a href="#/our-story">{lang === "ar" ? "الصحافة" : "Press"}</a>
            <a href="#/stores">{t("stores")}</a>
            <a href="#/contact">{t("contact")}</a>
          </div>

          <div className="footer-col">
            <h5>{t("footer_help")}</h5>
            <a href="#/contact">FAQ</a>
            <a href="#/contact">{lang === "ar" ? "الشحن" : "Shipping"}</a>
            <a href="#/contact">{lang === "ar" ? "الإرجاع" : "Returns"}</a>
            <a href="#/contact">{lang === "ar" ? "الخصوصية" : "Privacy"}</a>
          </div>
        </div>

        <div className="footer-bottom">
          <div>© {new Date().getFullYear()} MASKA — Maska Gift Wrapping LLC, Dubai</div>
          <div style={{display:"flex", gap:18}}>
            <a href="#" style={{color:"rgba(246,239,228,0.7)"}}>Instagram</a>
            <a href="#" style={{color:"rgba(246,239,228,0.7)"}}>Facebook</a>
            <a href="#" style={{color:"rgba(246,239,228,0.7)"}}>TikTok</a>
            <a href="#" style={{color:"rgba(246,239,228,0.7)"}}>LinkedIn</a>
          </div>
        </div>
      </div>
    </footer>
  );
}
window.Footer = Footer;

// ===== Floating WhatsApp button =====
function WhatsAppFab() {
  return <a className="fab-whatsapp" href="https://wa.me/97144427082" aria-label="WhatsApp"><Icon.whatsapp/></a>;
}
window.WhatsAppFab = WhatsAppFab;
