/* ============================================================
   Төрмен — cart context + cart screen
   (multi-step checkout lives in checkout.jsx)
   ============================================================ */
const { createContext:createCtxC, useContext:useCtxC, useState:useStateC, useEffect:useEffectC } = React;

const CartContext = createCtxC(null);
function CartProvider({ children }){
  const [items, setItems] = useStateC(()=>{
    try{ return JSON.parse(localStorage.getItem('tormen_cart')||'[]'); }catch(e){ return []; }
  });
  useEffectC(()=>{ localStorage.setItem('tormen_cart', JSON.stringify(items)); }, [items]);

  const add = (set, variant)=>{
    const key = variant.medusaVariantId || (set.id+'-'+variant.persons);
    setItems(prev=>{
      const ex = prev.find(i=>i.key===key);
      if(ex) return prev.map(i=> i.key===key ? {...i, qty:i.qty+1} : i);
      return [...prev, { key, setId:set.id, name:set.name, persons:variant.persons,
                         choice: variant.choice || variant.label || '',
                         price:variant.price, weight:variant.weight, ph:set.ph, qty:1,
                         thumb: window.setImg?.(set, 0) || set.thumbnail || null,
                         medusaVariantId: variant.medusaVariantId || null }];
    });
  };
  const addItem = (item)=>{
    setItems(prev=>{
      const ex = prev.find(i=>i.key===item.key);
      if(ex) return prev.map(i=> i.key===item.key ? {...i, qty:i.qty+1} : i);
      return [...prev, { ...item, qty:1 }];
    });
  };
  const setQty = (key, qty)=> setItems(prev=> qty<=0 ? prev.filter(i=>i.key!==key) : prev.map(i=> i.key===key?{...i,qty}:i));
  const remove = (key)=> setItems(prev=> prev.filter(i=>i.key!==key));
  const clear = ()=> setItems([]);
  const count = items.reduce((s,i)=>s+i.qty,0);
  const subtotal = items.reduce((s,i)=>s+i.price*i.qty,0);
  return <CartContext.Provider value={{ items, add, addItem, setQty, remove, clear, count, subtotal }}>{children}</CartContext.Provider>;
}
function useCart(){ return useCtxC(CartContext); }

/* ---------- qty stepper ---------- */
function Stepper({ value, onDec, onInc }){
  return (
    <div className="inline-flex items-center gap-1 rounded-full p-1" style={{ background:'var(--surface-2)', border:'1px solid var(--border)' }}>
      <button onClick={onDec} className="grid place-items-center rounded-full" style={{ width:30, height:30, color:'var(--ink)' }}>
        <Icon name="minus" size={15} stroke={2} />
      </button>
      <span className="tnum text-center" style={{ minWidth:22, fontWeight:600, fontSize:14 }}>{value}</span>
      <button onClick={onInc} className="grid place-items-center rounded-full" style={{ width:30, height:30, color:'var(--on-accent)', background:'var(--ember)' }}>
        <Icon name="plus" size={15} stroke={2} />
      </button>
    </div>
  );
}

/* ---------- Cart screen ---------- */
function CartView({ go }){
  const { t, tx, lang } = useLang();
  const { items, setQty, subtotal, clear, count } = useCart();
  const L = (ru,kz)=> lang==='kz'?kz:ru;

  if(items.length===0){
    return (
      <div className="max-w-2xl mx-auto px-5 pt-28 pb-32 text-center">
        <div className="mx-auto mb-7 grid place-items-center rounded-full" style={{ width:96, height:96, background:'var(--surface-1)', border:'1px solid var(--border-soft)' }}>
          <Icon name="shopping-bag" size={36} stroke={1.4} style={{ color:'var(--ink-3)' }} />
        </div>
        <div className="eyebrow mb-3">{t('cart')}</div>
        <h2 className="serif-title text-3xl mb-3"><span className="grad-text">{t('cart_empty')}</span></h2>
        <p className="mb-8" style={{ color:'var(--ink-2)' }}>{t('cart_empty_d')}</p>
        <button className="btn btn-primary" onClick={()=>go('catalog')}><span className="shine"></span>{t('go_catalog')}<Icon name="arrow-right" size={17} /></button>
      </div>
    );
  }

  const total = subtotal;

  return (
    <div className="max-w-7xl mx-auto px-5 pt-24 md:pt-28 pb-36">
      <div className="eyebrow mb-3">{t('cart')}</div>
      <h1 className="serif-title text-3xl md:text-5xl mb-2"><span className="grad-text">{t('checkout')}</span></h1>
      <div className="flex items-center gap-2 mb-8 text-sm" style={{ color:'var(--ink-3)' }}>
        <Icon name="shopping-bag" size={13} />
        <span><span className="tnum">{count}</span> {L('шт. в корзине','дана себетте')}</span>
      </div>

      <div className="grid lg:grid-cols-[1fr_380px] gap-6 items-start">
        {/* line items — light cards, glass reserved for the summary */}
        <div className="space-y-3">
          {items.map((i,idx)=>{
            const unit = i.weight || i.vol || '';
            const metaText = i.choice || (i.persons ? `${i.persons} ${t('persons')}` : (i.label || unit));
            const metaIcon = i.persons ? 'users' : (i.custom ? 'sliders-horizontal' : (i.vol ? 'soup' : 'weight'));
            return (
              <Reveal key={i.key} delay={Math.min(idx,5)*60}>
                <div className="p-3 md:p-4 flex items-center gap-4" style={{ background:'var(--surface-1)', border:'1px solid var(--border-soft)', borderRadius:'var(--radius)' }}>
                  <Ph type={i.ph} imgKey={i.setId || i.key} photoSrc={i.thumb} medusaPhoto={!!i.thumb} className="w-20 h-20 md:w-24 md:h-24 shrink-0" rounded="18px" />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5 mb-1" style={{ color: i.persons?'var(--ember)':'var(--gold)', fontSize:11, fontWeight:600, letterSpacing:'.07em', textTransform:'uppercase' }}>
                      <Icon name={metaIcon} size={12} stroke={1.8} />
                      <span className="tnum">{metaText}</span>
                    </div>
                    <div className="font-semibold truncate" style={{ fontSize:16 }}>{tx(i.name)}</div>
                    {i.custom && i.custom.length>0 && (
                      <div className="text-xs truncate mt-0.5" style={{ color:'var(--ink-3)' }}>{i.custom.join(' · ')}</div>
                    )}
                    <div className="text-sm tnum mt-0.5" style={{ color:'var(--ink-3)' }}>
                      {unit && unit!==metaText ? `${unit} · ` : ''}{fmtPrice(i.price)}
                    </div>
                  </div>
                  <div className="flex flex-col items-end gap-2">
                    <div className="tnum font-semibold whitespace-nowrap" style={{ fontSize:16 }}>{fmtPrice(i.price*i.qty)}</div>
                    <Stepper value={i.qty} onDec={()=>setQty(i.key,i.qty-1)} onInc={()=>setQty(i.key,i.qty+1)} />
                  </div>
                </div>
              </Reveal>
            );
          })}
          <button onClick={clear} className="text-sm inline-flex items-center gap-2 mt-1" style={{ color:'var(--ink-3)' }}>
            <Icon name="trash-2" size={15} />{t('remove')} {t('all').toLowerCase()}
          </button>
        </div>

        {/* summary → checkout: ledger, без glass */}
        <aside className="ledger-aside lg:sticky lg:top-24">
          <div className="eyebrow mb-4">{t('checkout')}</div>
          <div className="space-y-3 mb-6">
            <Row label={t('subtotal')} value={fmtPrice(subtotal)} />
            <div className="hairline my-4" />
            <Row label={t('total')} value={fmtPrice(total)} big />
          </div>

          <button className="btn btn-primary w-full" onClick={()=>go('checkout')}>
            <span className="shine"></span>
            <Icon name="arrow-right" size={17} />{t('checkout')}
          </button>
          <p className="flex items-center justify-center gap-2 mt-4 text-[11px] tracking-wide" style={{ color:'var(--ink-3)' }}>
            <Icon name="shield-check" size={12} stroke={1.8} />{L('Безопасно · охлаждённая доставка','Қауіпсіз · салқын жеткізу')}
          </p>
        </aside>
      </div>
    </div>
  );
}

function Row({ label, value, big, accent }){
  return (
    <div className="flex items-center justify-between">
      <span style={{ color:'var(--ink-2)', fontSize: big?16:14, fontWeight: big?600:400 }}>{label}</span>
      <span className="tnum" style={{ fontSize: big?22:15, fontWeight: big?700:600,
        color: accent?'var(--emerald)':'var(--ink)' }}>{value}</span>
    </div>
  );
}

Object.assign(window, { CartProvider, useCart, CartView, Stepper, Row });
