// Cart drawer + thumbnail helper
const { useState, useEffect, useContext } = React;

const CartThumb = ({ id }) => {
  const item = ALL_ITEMS[id];
  if (!item) return null;
  if (id === "v20" || id === "gt2000") {
    const gal = (window.GALLERY && window.GALLERY[id]) || [];
    const src = gal[0] || `assets/${id}-hero.jpg`;
    return (
      <img
        src={src}
        alt={item.short}
        style={{width:"72px", height:"72px", objectFit:"contain", display:"block", borderRadius:"6px"}}
      />
    );
  }
  const A = Acc[item.icon];
  return A ? <A size={64}/> : <BikePictogram size={36}/>;
};

const CartDrawer = ({ setPage }) => {
  const cart = useContext(CartContext);
  const langCtx = useContext(window.LangContext || React.createContext({ lang:"nl", t: (nl) => nl }));
  const t = langCtx.t || ((nl) => nl);
  const lang = langCtx.lang || "nl";
  const LP = window.LP || ((o, f) => o && o[f]);
  const vatAmt = (window.vatPortion ? window.vatPortion(cart.total) : 0);
  const threshold = Number(cart.freeShippingThreshold || 0);
  if (!cart.open) return null;
  return (
    <>
      <div className="cart-overlay" onClick={() => cart.setOpen(false)}/>
      <aside className="cart-drawer">
        <div className="cart-head">
          <h3>{t("Winkelmand","Cart")} · {cart.count}</h3>
          <button className="icon-btn" onClick={() => cart.setOpen(false)}><Icon name="x" size={22}/></button>
        </div>
        {cart.items.length === 0 ? (
          <div className="empty-cart">
            <div style={{width:64, height:64, borderRadius:50, background:"var(--bg)", margin:"0 auto 16px", display:"grid", placeItems:"center", color:"var(--ink-mute)"}}>
              <Icon name="cart" size={26}/>
            </div>
            <div style={{fontFamily:"var(--f-display)", fontSize:18, textTransform:"uppercase", marginBottom:8}}>{t("Je winkelmand is leeg","Your cart is empty")}</div>
            <p style={{fontSize:13.5, marginBottom: 22}}>{t("Voeg een Zyro of accessoire toe om verder te gaan.","Add a Zyro or accessory to continue.")}</p>
            <button className="btn btn-primary" onClick={() => { cart.setOpen(false); setPage("shop"); }}>{t("Naar de webshop","To the shop")} <Icon name="arrow" size={15}/></button>
          </div>
        ) : (
          <>
            <div className="cart-items">
              {cart.items.map(it => {
                const p = ALL_ITEMS[it.id];
                if (!p) return null;
                const showDiscount = window.hasDiscount && window.hasDiscount(p);
                return (
                  <div key={it.id} className="cart-row">
                    <div className="cart-thumb"><CartThumb id={it.id}/></div>
                    <div>
                      <h4>{LP(p,"name",lang) || LP(p,"short",lang) || p.name || p.short}</h4>
                      <div className="meta">{LP(p,"color",lang) || LP(p,"type",lang)}</div>
                      <div className="qty-stepper">
                        <button onClick={() => cart.setQty(it.id, it.qty - 1)}>−</button>
                        <span>{it.qty}</span>
                        <button onClick={() => cart.setQty(it.id, it.qty + 1)}>+</button>
                      </div>
                    </div>
                    <div style={{textAlign:"right", display:"flex", flexDirection:"column", gap:10, alignItems:"flex-end"}}>
                      {showDiscount && <div className="mono" style={{fontSize:11, color:"var(--ink-mute)", textDecoration:"line-through"}}>{formatEUR(p.oldPrice * it.qty)}</div>}
                      <div style={{fontFamily:"var(--f-display)", fontWeight:700, fontSize:15}}>{formatEUR(p.price * it.qty)}</div>
                      {showDiscount && <span className="tag warn" style={{fontSize:10}}>{window.discountLabel(p, lang)}</span>}
                      <button onClick={() => cart.remove(it.id)} style={{color:"var(--ink-mute)", fontSize:11, textTransform:"uppercase", letterSpacing:".1em", fontFamily:"var(--f-mono)"}}>{t("Verwijder","Delete")}</button>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="cart-foot">
              <div className="cart-totals">
                <div className="row"><span>{t("Subtotaal","Subtotal")}</span><span>{formatEUR(cart.subtotal)}</span></div>
                <div className="row"><span>{t("Verzendkosten","Shipping costs")}</span><span>{cart.shipping === 0 ? <strong style={{color:"var(--ok)"}}>{t("Gratis","Free")}</strong> : formatEUR(cart.shipping)}</span></div>
                {threshold > 0 && cart.subtotal > 0 && cart.subtotal < threshold && <div className="row" style={{color:"var(--ink-mute)", fontSize:11.5}}><span>{t("Gratis verzending vanaf","Free shipping from")} {formatEUR(threshold)}</span><span>{t("nog","still")} {formatEUR(threshold - cart.subtotal)}</span></div>}
                <div className="row total"><span>{t("Totaal","Total")}</span><span>{formatEUR(cart.total)}</span></div>
                {cart.total > 0 && window.vatRowLabel && (
                  <div className="row" style={{color:"var(--ink-mute)", fontSize:11.5}}>
                    <span>{window.vatRowLabel(langCtx.lang)}</span><span>{formatEUR(vatAmt)}</span>
                  </div>
                )}
              </div>
              {cart.hasUnavailable && (
                <div style={{margin:"10px 0", padding:"10px 12px", borderRadius:8, background:"#fbe9e9", border:"1px solid #efc5c5", color:"#9a2222", fontSize:12.5}}>
                  {t("Een product in je winkelmand is niet meer beschikbaar.","An item in your cart is no longer available.")}
                </div>
              )}
              <button className="btn btn-accent btn-lg btn-block" onClick={() => { cart.setOpen(false); setPage("checkout"); }} disabled={cart.hasUnavailable}>
                {t("Verder naar checkout","Continue to checkout")} <Icon name="arrow" size={16}/>
              </button>
              <button className="btn btn-ghost btn-block btn-sm" onClick={() => cart.setOpen(false)}>{t("Doorgaan met winkelen","Continue shopping")}</button>
            </div>
          </>
        )}
      </aside>
    </>
  );
};

window.CartDrawer = CartDrawer;
window.CartThumb = CartThumb;
