/* Products listing, Product Detail, Cart, Order Success. Exposes window.AXShop. */
(function(){
const { Button, IconButton, Badge, Rating, PriceTag, QuantityStepper, Eyebrow, ProductCard } = window.AXUI;
const Ic=()=>window.AXIcons; const D=()=>window.AX_DATA;
const wrap={maxWidth:'var(--container-max)',margin:'0 auto',padding:'0 var(--gutter)'};
const cats=['Short Sleeve Tees','Hoodies & Sweatshirts','Tops','Caps','Hanfu Dresses','Plaid Shirts','Pants','Outerwear'];
const sorts=[['featured','Featured'],['price-asc','Price: Low to High'],['price-desc','Price: High to Low'],['newest','Newest']];

/* ---------------- PRODUCTS ---------------- */
function Products({ initialLabel, query, onAdd, onView, onNav }){
  const labelCat = cats.includes(initialLabel) ? [initialLabel] : [];
  const [selCats,setSelCats]=React.useState(labelCat);
  const [maxPrice,setMaxPrice]=React.useState(150);
  const [minRating,setMinRating]=React.useState(0);
  const [sort,setSort]=React.useState('featured');
  const i=Ic();
  const toggle=(c)=>setSelCats(s=>s.includes(c)?s.filter(x=>x!==c):[...s,c]);

  let list=D().products.filter(p=>
    (selCats.length===0||selCats.includes(p.category)) &&
    p.price<=maxPrice && p.rating>=minRating &&
    (!query||p.name.toLowerCase().includes(query.toLowerCase())||p.category.toLowerCase().includes(query.toLowerCase()))
  );
  if(sort==='price-asc')list=[...list].sort((a,b)=>a.price-b.price);
  if(sort==='price-desc')list=[...list].sort((a,b)=>b.price-a.price);
  if(sort==='newest')list=[...list].sort((a,b)=>(b.badge==='New')-(a.badge==='New'));

  const title = initialLabel && !cats.includes(initialLabel) ? initialLabel : (selCats.length===1?selCats[0]:'All Products');

  return <div style={{...wrap,padding:'36px var(--gutter) 0'}}>
    <nav style={{fontSize:'var(--fs-sm)',color:'var(--text-muted)',marginBottom:14,display:'flex',gap:6,alignItems:'center'}}>
      <a href="#" onClick={e=>{e.preventDefault();onNav({type:'home'});}} style={{color:'var(--text-muted)'}}>Home</a>
      {React.createElement(i.ChevronRight,{size:14,style:{color:'var(--text-faint)'}})}<span style={{color:'var(--text-strong)',fontWeight:500}}>{title}</span>
    </nav>
    <div style={{display:'flex',alignItems:'flex-end',justifyContent:'space-between',gap:16,marginBottom:24,flexWrap:'wrap'}}>
      <div><Eyebrow>Shop</Eyebrow><h1 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-3xl)',fontWeight:700,color:'var(--text-strong)',letterSpacing:'-0.02em',margin:'8px 0 0'}}>{title}</h1></div>
      <div style={{display:'flex',alignItems:'center',gap:10}}>
        <span style={{fontSize:'var(--fs-sm)',color:'var(--text-muted)'}}>{list.length} products</span>
        <div style={{display:'flex',alignItems:'center',gap:8,height:42,padding:'0 12px 0 14px',background:'var(--surface-card)',border:'1px solid var(--border-default)',borderRadius:'var(--radius-md)'}}>
          <select value={sort} onChange={e=>setSort(e.target.value)} style={{border:'none',outline:'none',background:'transparent',fontFamily:'var(--font-body)',fontSize:'var(--fs-sm)',fontWeight:600,color:'var(--text-strong)',cursor:'pointer'}}>
            {sorts.map(([v,l])=><option key={v} value={v}>{l}</option>)}
          </select>
        </div>
      </div>
    </div>
    <div style={{display:'grid',gridTemplateColumns:'238px 1fr',gap:32,alignItems:'start'}} className="ax-shop-grid">
      <aside style={{display:'flex',flexDirection:'column',gap:26,position:'sticky',top:88}} className="ax-filters">
        <FilterBlock title="Category">
          {cats.map(c=><label key={c} style={{display:'flex',alignItems:'center',gap:10,cursor:'pointer',fontSize:'var(--fs-base)',color:'var(--text-body)'}}>
            <span onClick={()=>toggle(c)} style={{width:20,height:20,borderRadius:6,border:`1.5px solid ${selCats.includes(c)?'var(--blue-600)':'var(--border-strong)'}`,background:selCats.includes(c)?'var(--blue-600)':'#fff',display:'inline-flex',alignItems:'center',justifyContent:'center',color:'#fff',flex:'0 0 auto'}}>{selCats.includes(c)&&React.createElement(i.Check,{size:13,sw:3})}</span>
            <span onClick={()=>toggle(c)}>{c}</span>
          </label>)}
        </FilterBlock>
        <FilterBlock title={`Max price · $${maxPrice}`}>
          <input type="range" min="20" max="150" step="5" value={maxPrice} onChange={e=>setMaxPrice(+e.target.value)} style={{width:'100%',accentColor:'var(--blue-600)'}}/>
          <div style={{display:'flex',justifyContent:'space-between',fontFamily:'var(--font-mono)',fontSize:'var(--fs-xs)',color:'var(--text-faint)'}}><span>$20</span><span>$150+</span></div>
        </FilterBlock>
        <FilterBlock title="Rating">
          {[4,3,0].map(r=><label key={r} style={{display:'flex',alignItems:'center',gap:10,cursor:'pointer'}} onClick={()=>setMinRating(r)}>
            <span style={{width:18,height:18,borderRadius:'999px',border:`1.5px solid ${minRating===r?'var(--blue-600)':'var(--border-strong)'}`,display:'inline-flex',alignItems:'center',justifyContent:'center',flex:'0 0 auto'}}>{minRating===r&&<span style={{width:9,height:9,borderRadius:'999px',background:'var(--blue-600)'}}/>}</span>
            <span style={{fontSize:'var(--fs-base)',color:'var(--text-body)'}}>{r===0?'All ratings':`${r}.0 & up`}</span>
          </label>)}
        </FilterBlock>
      </aside>
      <div>
        {list.length===0 ? <div style={{padding:'80px 0',textAlign:'center',color:'var(--text-muted)'}}>No products match your filters.</div>
        : <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:22}} className="ax-prod-grid">
          {list.map(p=><ProductCard key={p.id} product={p} onAdd={onAdd} onView={onView}/>)}
        </div>}
      </div>
    </div>
  </div>;
}
function FilterBlock({ title, children }){
  return <div style={{display:'flex',flexDirection:'column',gap:12}}>
    <span style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-base)',fontWeight:600,color:'var(--text-strong)'}}>{title}</span>
    <div style={{display:'flex',flexDirection:'column',gap:10}}>{children}</div>
  </div>;
}

/* ---------------- PRODUCT DETAIL ---------------- */
function ProductDetail({ product, onAdd, onBuy, onView, onNav }){
  const [qty,setQty]=React.useState(1);
  const [tab,setTab]=React.useState('Description');
  const [active,setActive]=React.useState(0);
  const i=Ic();
  const tiles=[product.image || product.accent,'linear-gradient(135deg,#EEF2FF,#E0F7FB)','linear-gradient(135deg,#F4F7FF,#FDEFF6)','linear-gradient(135deg,#EAFBF2,#E7F1FF)'];
  const related=D().products.filter(p=>p.category===product.category&&p.id!==product.id).slice(0,4);
  const tabs=['Description','Features','Specifications','Shipping & Returns','Reviews'];
  return <div style={{...wrap,padding:'30px var(--gutter) 0'}}>
    <nav style={{fontSize:'var(--fs-sm)',color:'var(--text-muted)',marginBottom:20,display:'flex',gap:6,alignItems:'center',flexWrap:'wrap'}}>
      <a href="#" onClick={e=>{e.preventDefault();onNav({type:'home'});}} style={{color:'var(--text-muted)'}}>Home</a>
      {React.createElement(i.ChevronRight,{size:14})}<a href="#" onClick={e=>{e.preventDefault();onNav({type:'products',label:product.category});}} style={{color:'var(--text-muted)'}}>{product.category}</a>
      {React.createElement(i.ChevronRight,{size:14})}<span style={{color:'var(--text-strong)',fontWeight:500}}>{product.name}</span>
    </nav>
    <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:48,alignItems:'start'}} className="ax-pdp-grid">
      <div style={{display:'flex',flexDirection:'column',gap:14,position:'sticky',top:90}} className="ax-pdp-gallery">
        <div style={{position:'relative',aspectRatio:'1/1',borderRadius:'var(--radius-2xl)',background:active===0&&product.image?'var(--surface-card)':tiles[active],display:'flex',alignItems:'center',justifyContent:'center',border:'1px solid var(--border-subtle)',overflow:'hidden'}}>
          {product.badge && <div style={{position:'absolute',top:18,left:18}}><Badge tone={product.badge}>{product.badge}</Badge></div>}
          {active===0&&product.image
            ? <img src={product.image} alt={product.name} style={{width:'100%',height:'100%',objectFit:'cover',display:'block'}}/>
            : <span style={{fontFamily:'var(--font-display)',fontWeight:700,fontSize:120,color:'rgba(10,17,36,0.10)'}}>{product.name.charAt(0)}</span>}
        </div>
        <div style={{display:'flex',gap:12}}>
          {tiles.map((t,k)=><button key={k} onClick={()=>setActive(k)} style={{flex:1,aspectRatio:'1/1',borderRadius:'var(--radius-lg)',background:k===0&&product.image?'var(--surface-card)':t,border:`2px solid ${active===k?'var(--blue-600)':'var(--border-subtle)'}`,cursor:'pointer',overflow:'hidden',padding:0}}>
            {k===0&&product.image ? <img src={product.image} alt="" aria-hidden="true" style={{width:'100%',height:'100%',objectFit:'cover',display:'block'}}/> : null}
          </button>)}
        </div>
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:18}}>
        <div style={{display:'flex',flexDirection:'column',gap:10}}>
          <Eyebrow>{product.category}</Eyebrow>
          <h1 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-3xl)',fontWeight:700,color:'var(--text-strong)',letterSpacing:'-0.02em',lineHeight:1.1,margin:0}}>{product.name}</h1>
          <div style={{display:'flex',alignItems:'center',gap:12,flexWrap:'wrap'}}>
            <Rating value={product.rating} count={product.reviewCount} showValue/>
            <span style={{color:'var(--border-default)'}}>·</span>
            <span style={{display:'inline-flex',alignItems:'center',gap:5,color:'var(--status-success)',fontWeight:600,fontSize:'var(--fs-sm)'}}>{React.createElement(i.Check,{size:15})} In stock · {product.stock} left</span>
          </div>
        </div>
        <PriceTag price={product.price} compareAt={product.compareAt} size="xl"/>
        <p style={{fontSize:'var(--fs-md)',color:'var(--text-body)',lineHeight:1.65,margin:0,maxWidth:520}}>{product.description}</p>
        <div style={{display:'flex',gap:14,alignItems:'center',marginTop:4,flexWrap:'wrap'}}>
          <QuantityStepper value={qty} onChange={setQty} max={product.stock}/>
          <Button variant="primary" size="lg" iconLeft={React.createElement(i.Cart,{size:18})} onClick={()=>onAdd(product,qty)} style={{flex:1,minWidth:180}}>Add to Cart</Button>
        </div>
        <Button variant="accent" size="lg" full iconLeft={React.createElement(i.Bolt,{size:18})} onClick={()=>onBuy(product,qty)}>Buy Now</Button>
        <div style={{display:'flex',gap:18,padding:'16px 0',borderTop:'1px solid var(--border-subtle)',borderBottom:'1px solid var(--border-subtle)',marginTop:4,flexWrap:'wrap'}}>
          {[['Truck','Free shipping over $49'],['Refresh','30-day returns'],['Shield','2-year warranty']].map(([ic,t])=><span key={t} style={{display:'inline-flex',alignItems:'center',gap:7,fontSize:'var(--fs-sm)',color:'var(--text-body)',fontWeight:500}}>{React.createElement(i[ic],{size:17,style:{color:'var(--blue-600)'}})}{t}</span>)}
        </div>
        <div>
          <div style={{display:'flex',gap:4,borderBottom:'1px solid var(--border-subtle)',overflowX:'auto'}}>
            {tabs.map(t=><button key={t} onClick={()=>setTab(t)} style={{padding:'12px 14px',background:'none',border:'none',borderBottom:`2px solid ${tab===t?'var(--blue-600)':'transparent'}`,color:tab===t?'var(--text-strong)':'var(--text-muted)',fontFamily:'var(--font-body)',fontWeight:600,fontSize:'var(--fs-sm)',cursor:'pointer',whiteSpace:'nowrap',marginBottom:-1}}>{t}</button>)}
          </div>
          <div style={{padding:'20px 2px',fontSize:'var(--fs-base)',color:'var(--text-body)',lineHeight:1.65}}>
            {tab==='Description' && <p style={{margin:0}}>{product.description} Designed and quality-checked by AshopNexa, every order ships carbon-neutral and is backed by our satisfaction guarantee.</p>}
            {tab==='Features' && <ul style={{margin:0,paddingLeft:0,listStyle:'none',display:'flex',flexDirection:'column',gap:10}}>{product.features.map(f=><li key={f} style={{display:'flex',gap:10,alignItems:'flex-start'}}><span style={{color:'var(--blue-600)',marginTop:2}}>{React.createElement(i.Check,{size:16,sw:2.5})}</span>{f}</li>)}</ul>}
            {tab==='Specifications' && <table style={{width:'100%',borderCollapse:'collapse'}}><tbody>{Object.entries(product.specifications).map(([k,v])=><tr key={k} style={{borderBottom:'1px solid var(--border-subtle)'}}><td style={{padding:'10px 0',color:'var(--text-muted)',width:'40%'}}>{k}</td><td style={{padding:'10px 0',color:'var(--text-strong)',fontWeight:500,fontFamily:'var(--font-mono)',fontSize:'var(--fs-sm)'}}>{v}</td></tr>)}</tbody></table>}
            {tab==='Shipping & Returns' && <p style={{margin:0}}>Free standard shipping on orders over $49 (3–5 business days). Express options at checkout. Not the right fit? Return any unused item within 30 days for a full refund — we even cover return shipping on your first order.</p>}
            {tab==='Reviews' && <div style={{display:'flex',flexDirection:'column',gap:16}}>{D().reviews.map((r,k)=><div key={k} style={{display:'flex',flexDirection:'column',gap:6}}><div style={{display:'flex',alignItems:'center',gap:10}}><Rating value={r.rating} size={14}/><span style={{fontWeight:600,color:'var(--text-strong)',fontSize:'var(--fs-sm)'}}>{r.name}</span></div><p style={{margin:0}}>“{r.body}”</p></div>)}</div>}
          </div>
        </div>
      </div>
    </div>
    <section style={{padding:'72px 0 0'}}>
      <h2 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-2xl)',fontWeight:700,color:'var(--text-strong)',letterSpacing:'-0.02em',marginBottom:24}}>Related products</h2>
      <div style={{display:'grid',gridTemplateColumns:'repeat(4,1fr)',gap:22}} className="ax-prod-grid">
        {related.map(p=><ProductCard key={p.id} product={p} onAdd={pp=>onAdd(pp,1)} onView={onView}/>)}
      </div>
    </section>
  </div>;
}

/* ---------------- CART ---------------- */
function Cart({ items, onQty, onRemove, onNav, onCheckout }){
  const i=Ic();
  const sub=items.reduce((s,it)=>s+it.price*it.qty,0);
  const ship=sub>49||sub===0?0:6.99;
  const tax=+(sub*0.08).toFixed(2);
  const total=+(sub+ship+tax).toFixed(2);
  if(items.length===0) return <div style={{...wrap,padding:'80px var(--gutter)',textAlign:'center',display:'flex',flexDirection:'column',alignItems:'center',gap:18}}>
    <span style={{width:72,height:72,borderRadius:'999px',background:'var(--surface-sunken)',color:'var(--text-faint)',display:'inline-flex',alignItems:'center',justifyContent:'center'}}>{React.createElement(i.Cart,{size:32})}</span>
    <h1 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-2xl)',fontWeight:700,color:'var(--text-strong)',margin:0}}>Your cart is empty</h1>
    <p style={{color:'var(--text-muted)',margin:0}}>Looks like you haven't added anything yet.</p>
    <Button variant="primary" size="lg" onClick={()=>onNav({type:'products',label:'Best Sellers'})}>Start shopping</Button>
  </div>;
  return <div style={{...wrap,padding:'36px var(--gutter) 0'}}>
    <h1 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-3xl)',fontWeight:700,color:'var(--text-strong)',letterSpacing:'-0.02em',margin:'0 0 24px'}}>Shopping cart <span style={{color:'var(--text-faint)',fontWeight:500,fontSize:'var(--fs-xl)'}}>({items.length})</span></h1>
    <div style={{display:'grid',gridTemplateColumns:'1fr 360px',gap:32,alignItems:'start'}} className="ax-cart-grid">
      <div style={{display:'flex',flexDirection:'column',gap:14}}>
        {items.map(it=><div key={it.id} style={{display:'flex',gap:18,background:'var(--surface-card)',border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-xl)',padding:16,alignItems:'center'}} className="ax-cart-row">
          <div style={{width:96,height:96,borderRadius:'var(--radius-lg)',background:it.accent,flex:'0 0 auto',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',fontWeight:700,fontSize:34,color:'rgba(10,17,36,0.10)'}}>{it.name.charAt(0)}</div>
          <div style={{flex:1,minWidth:0,display:'flex',flexDirection:'column',gap:6}}>
            <span style={{fontSize:'var(--fs-xs)',fontWeight:700,letterSpacing:'.02em',textTransform:'uppercase',color:'var(--text-faint)'}}>{it.category}</span>
            <span style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-md)',fontWeight:600,color:'var(--text-strong)'}}>{it.name}</span>
            <PriceTag price={it.price} size="sm"/>
          </div>
          <div style={{display:'flex',flexDirection:'column',gap:10,alignItems:'flex-end'}}>
            <QuantityStepper value={it.qty} onChange={q=>onQty(it.id,q)} max={it.stock}/>
            <button onClick={()=>onRemove(it.id)} style={{display:'inline-flex',alignItems:'center',gap:5,background:'none',border:'none',cursor:'pointer',color:'var(--text-faint)',fontSize:'var(--fs-sm)'}} onMouseEnter={e=>e.currentTarget.style.color='var(--status-danger)'} onMouseLeave={e=>e.currentTarget.style.color='var(--text-faint)'}>{React.createElement(i.Trash,{size:15})} Remove</button>
          </div>
        </div>)}
        <button onClick={()=>onNav({type:'products',label:'Best Sellers'})} style={{alignSelf:'flex-start',display:'inline-flex',alignItems:'center',gap:6,background:'none',border:'none',cursor:'pointer',color:'var(--blue-600)',fontWeight:600,fontSize:'var(--fs-base)',marginTop:6}}>← Continue shopping</button>
      </div>
      <OrderSummary sub={sub} ship={ship} tax={tax} total={total} onCheckout={onCheckout}/>
    </div>
  </div>;
}

function OrderSummary({ sub, ship, tax, total, onCheckout, cta='Proceed to Checkout' }){
  const i=Ic();
  const row=(l,v,strong)=><div style={{display:'flex',justifyContent:'space-between',fontSize:strong?'var(--fs-lg)':'var(--fs-base)',color:strong?'var(--text-strong)':'var(--text-body)',fontWeight:strong?700:400}}><span style={strong?{fontFamily:'var(--font-display)'}:{}}>{l}</span><span style={{fontFamily:'var(--font-mono)',fontWeight:strong?700:500}}>{v}</span></div>;
  return <div style={{position:'sticky',top:90,background:'var(--surface-card)',border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-xl)',padding:24,display:'flex',flexDirection:'column',gap:14,boxShadow:'var(--shadow-sm)'}}>
    <span style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-lg)',fontWeight:700,color:'var(--text-strong)'}}>Order summary</span>
    {row('Subtotal','$'+sub.toFixed(2))}
    {row('Shipping',ship===0?'Free':'$'+ship.toFixed(2))}
    {row('Estimated tax','$'+tax.toFixed(2))}
    {sub>0 && sub<49 && <div style={{fontSize:'var(--fs-sm)',color:'var(--blue-600)',background:'var(--surface-accent-soft)',padding:'8px 12px',borderRadius:'var(--radius-sm)'}}>Add ${(49-sub).toFixed(2)} more for free shipping</div>}
    <div style={{borderTop:'1px solid var(--border-subtle)',paddingTop:14}}>{row('Total','$'+total.toFixed(2),true)}</div>
    <Button variant="primary" size="lg" full iconRight={React.createElement(i.ArrowRight,{size:18})} onClick={onCheckout}>{cta}</Button>
    <div style={{display:'flex',alignItems:'center',justifyContent:'center',gap:6,color:'var(--text-faint)',fontSize:'var(--fs-sm)'}}>{React.createElement(i.Lock,{size:14})} Secure 256-bit checkout</div>
  </div>;
}

/* ---------------- ORDER SUCCESS ---------------- */
function OrderSuccess({ orderNo, onNav }){
  const i=Ic();
  return <div style={{...wrap,padding:'72px var(--gutter)',display:'flex',flexDirection:'column',alignItems:'center',textAlign:'center',gap:18,maxWidth:560}}>
    <span style={{width:80,height:80,borderRadius:'999px',background:'var(--status-success-soft)',color:'var(--status-success)',display:'inline-flex',alignItems:'center',justifyContent:'center'}}>{React.createElement(i.CheckCircle,{size:42})}</span>
    <h1 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-3xl)',fontWeight:700,color:'var(--text-strong)',letterSpacing:'-0.02em',margin:0}}>Thank you for your order!</h1>
    <p style={{color:'var(--text-body)',fontSize:'var(--fs-md)',margin:0,lineHeight:1.6}}>Your order is confirmed. A receipt is on its way to <strong style={{color:'var(--text-strong)'}}>you@example.com</strong>.</p>
    <div style={{background:'var(--surface-card)',border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-lg)',padding:'16px 28px'}}>
      <span style={{fontSize:'var(--fs-sm)',color:'var(--text-muted)'}}>Order number</span>
      <div style={{fontFamily:'var(--font-mono)',fontSize:'var(--fs-xl)',fontWeight:600,color:'var(--text-strong)',letterSpacing:'.02em'}}>{orderNo}</div>
    </div>
    <div style={{display:'flex',gap:12,marginTop:6,flexWrap:'wrap',justifyContent:'center'}}>
      <Button variant="outline" size="lg" onClick={()=>onNav({type:'track',order:orderNo})}>Track Order</Button>
      <Button variant="primary" size="lg" onClick={()=>onNav({type:'home'})}>Continue Shopping</Button>
    </div>
  </div>;
}

window.AXShop = { Products, ProductDetail, Cart, OrderSummary, OrderSuccess };
})();
