/* ============================================================
   STORE — cart + router contexts
   ============================================================ */
const CartCtx = createContext(null);
const useCart = () => useContext(CartCtx);

function bundleById(id){ return BUNDLES.find(b=>b.id===id) || BUNDLES[0]; }

function CartProvider({ children }){
  const [items, setItems] = useState(()=>{
    try{ return JSON.parse(localStorage.getItem("mye_cart")||"[]"); }catch(e){ return []; }
  });
  const [open, setOpen] = useState(false);
  const [justAdded, setJustAdded] = useState(null);
  const [selected, setSelected] = useState("duo"); // shared PDP/sticky bundle selection
  const [busy, setBusy] = useState(false);
  const [shopifyError, setShopifyError] = useState("");

  useEffect(()=>{ localStorage.setItem("mye_cart", JSON.stringify(items)); },[items]);

  const add = async (bundleId, qty=1)=>{
    setBusy(true);
    setShopifyError("");
    try{
      await ShopifyAPI.addBundleToCart(bundleId, qty);
      setItems(prev=>{
        const i = prev.findIndex(x=>x.bundleId===bundleId);
        if(i>=0){ const n=[...prev]; n[i]={...n[i],qty:n[i].qty+qty}; return n; }
        return [...prev,{bundleId,qty}];
      });
      setJustAdded(bundleId);
      setOpen(true);
    }catch(err){
      const msg = err && err.message ? err.message : "Unable to add this product to Shopify cart.";
      setShopifyError(msg);
      alert(msg);
    }finally{
      setBusy(false);
    }
  };
  const syncItemsToShopify = async (nextItems)=>{
    setBusy(true);
    setShopifyError("");
    try{ await ShopifyAPI.replaceCartFromItems(nextItems); }
    catch(err){
      const msg = err && err.message ? err.message : "Unable to update Shopify cart.";
      setShopifyError(msg);
      alert(msg);
    }finally{
      setBusy(false);
    }
  };
  const updateItems = (deriveNext)=>{
    const next = deriveNext(items);
    setItems(next);
    syncItemsToShopify(next);
  };
  const setQty = (bundleId, qty)=> updateItems(prev=>
    qty<=0 ? prev.filter(x=>x.bundleId!==bundleId) : prev.map(x=>x.bundleId===bundleId?{...x,qty}:x)
  );
  const remove = (bundleId)=> updateItems(prev=>prev.filter(x=>x.bundleId!==bundleId));
  const clear = ()=>{
    localStorage.removeItem("mye_shopify_cart_id");
    localStorage.removeItem("mye_shopify_checkout_url");
    setItems([]);
  };
  const buyNow = async (bundleId, qty=1)=>{
    setBusy(true);
    setShopifyError("");
    try{
      await ShopifyAPI.buyNow(bundleId, qty);
    }catch(err){
      const msg = err && err.message ? err.message : "Unable to start Shopify checkout.";
      setShopifyError(msg);
      alert(msg);
      setBusy(false);
    }
  };
  const checkout = ()=>{
    try{ ShopifyAPI.checkout(); }
    catch(err){ const msg = err && err.message ? err.message : "No Shopify checkout is available yet."; setShopifyError(msg); alert(msg); }
  };

  const lines = items.map(it=>{ const b=bundleById(it.bundleId); return { ...it, bundle:b, line:b.price*it.qty }; });
  const subtotal = lines.reduce((s,l)=>s+l.line,0);
  const count = lines.reduce((s,l)=>s+l.qty,0);
  const tinCount = lines.reduce((s,l)=>s+l.qty*l.bundle.tins,0);

  const val = { items, lines, subtotal, count, tinCount, add, buyNow, checkout, setQty, remove, clear, open, setOpen, justAdded, selected, setSelected, busy, shopifyError };
  return <CartCtx.Provider value={val}>{children}</CartCtx.Provider>;
}

/* ---- Router ---- */
const RouteCtx = createContext(null);
const useRoute = () => useContext(RouteCtx);

function parseHash(){
  let h = (location.hash||"#/").replace(/^#/, "");
  if(!h.startsWith("/")) h = "/"+h;
  const [path, q] = h.split("?");
  return { path, query:q||"" };
}

function RouterProvider({ children }){
  const [route, setRoute] = useState(parseHash());
  useEffect(()=>{
    const on = ()=>{ setRoute(parseHash()); window.scrollTo({top:0,behavior:"instant"in document.documentElement.style?"instant":"auto"}); };
    window.addEventListener("hashchange", on);
    return ()=>window.removeEventListener("hashchange", on);
  },[]);
  const navigate = (to)=>{ location.hash = to.startsWith("#")?to:("#"+to); };
  return <RouteCtx.Provider value={{ ...route, navigate }}>{children}</RouteCtx.Provider>;
}

/* link helper */
function Link({ to, children, className, style, onClick }){
  const { navigate } = useRoute();
  return <a href={"#"+to} className={className} style={style}
    onClick={(e)=>{ e.preventDefault(); onClick&&onClick(); navigate(to); }}>{children}</a>;
}

Object.assign(window, { CartProvider, useCart, RouterProvider, useRoute, Link, bundleById });
