/* ============================================================
   FLORÍADE — Carrinho (contexto + gaveta)
   ============================================================ */
const { createContext, useContext, useState, useEffect, useCallback } = React;

const CartCtx = createContext(null);
const useCart = () => useContext(CartCtx);

function CartProvider({ children }){
  const [items, setItems] = useState(()=>{
    try{ return JSON.parse(localStorage.getItem("fl-cart")||"[]"); }catch{ return []; }
  });
  const [open, setOpen] = useState(false);
  const [pulse, setPulse] = useState(0);

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

  const add = useCallback((id, qty=1)=>{
    setItems(prev=>{
      const f = prev.find(i=>i.id===id);
      if(f) return prev.map(i=>i.id===id?{...i,qty:i.qty+qty}:i);
      return [...prev,{id,qty}];
    });
    setPulse(p=>p+1);
  },[]);
  const setQty = useCallback((id,qty)=>{
    setItems(prev=> qty<=0 ? prev.filter(i=>i.id!==id) : prev.map(i=>i.id===id?{...i,qty}:i));
  },[]);
  const remove = useCallback((id)=> setItems(prev=>prev.filter(i=>i.id!==id)),[]);
  const clear = useCallback(()=> setItems([]),[]);

  const count = items.reduce((s,i)=>s+i.qty,0);
  const detailed = items.map(i=>({ ...i, p: PRODUCTS.find(p=>p.id===i.id) })).filter(i=>i.p);
  const total = detailed.reduce((s,i)=>s+i.p.price*i.qty,0);

  const value = { items, detailed, add, setQty, remove, clear, count, total, open, setOpen, pulse };
  return <CartCtx.Provider value={value}>{children}</CartCtx.Provider>;
}

function CartDrawer({ onGoProduct }){
  const { open, setOpen, detailed, setQty, remove, total, count, clear } = useCart();
  useEffect(()=>{
    const onKey = e => { if(e.key==="Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return ()=> window.removeEventListener("keydown", onKey);
  },[setOpen]);

  return (
    <div className={"drawer-root"+(open?" is-open":"")} aria-hidden={!open}>
      <div className="drawer-scrim" onClick={()=>setOpen(false)}></div>
      <aside className="drawer" role="dialog" aria-label="Carrinho">
        <div className="drawer-head">
          <div className="eyebrow"><Glyph g="✶"/> Sua Cesta · {count} {count===1?"essência":"essências"}</div>
          <button className="icon-btn" onClick={()=>setOpen(false)} aria-label="Fechar">✕</button>
        </div>
        <div className="vine vine--thin"></div>

        <div className="drawer-body">
          {detailed.length===0 && (
            <div className="drawer-empty">
              <Seal size={92} glyphs={false}/>
              <p className="serif" style={{fontSize:"1.3rem",marginBottom:4}}>Sua cesta está vazia</p>
              <p style={{color:"var(--ink-faint)"}}>As essências aguardam por você no laboratório.</p>
              <button className="btn btn--sm" onClick={()=>setOpen(false)}><span>Explorar a Loja</span></button>
            </div>
          )}
          {detailed.map(({id,qty,p})=>(
            <div className="cart-line" key={id}>
              <div className="cart-thumb frame" onClick={()=>{ onGoProduct(id); setOpen(false); }}>
                <image-slot id={"product-"+id} shape="rect" placeholder="" style={{width:"100%",height:"100%"}}></image-slot>
              </div>
              <div className="cart-info">
                <button className="cart-name serif" onClick={()=>{ onGoProduct(id); setOpen(false); }}>{p.name}</button>
                <div className="cart-meta"><span className="glyph">{p.planet}</span> {p.lineLabel}</div>
                <div className="qty">
                  <button onClick={()=>setQty(id,qty-1)} aria-label="Menos">−</button>
                  <span>{qty}</span>
                  <button onClick={()=>setQty(id,qty+1)} aria-label="Mais">+</button>
                  <button className="cart-remove" onClick={()=>remove(id)}>remover</button>
                </div>
              </div>
              <div className="cart-price serif">{brl(p.price*qty)}</div>
            </div>
          ))}
        </div>

        {detailed.length>0 && (
          <div className="drawer-foot">
            <div className="vine vine--thin"></div>
            <div className="drawer-total">
              <span className="eyebrow eyebrow--ink">Total</span>
              <span className="serif total-val">{brl(total)}</span>
            </div>
            <p className="drawer-note">Frete e oferenda calculados na finalização.</p>
            <button className="btn btn--solid btn--block"><span>Selar o Pedido</span></button>
            <button className="link-min" onClick={clear}>esvaziar cesta</button>
          </div>
        )}
      </aside>
    </div>
  );
}

Object.assign(window, { CartProvider, useCart, CartDrawer });
