/* AshopNexa storefront kit — primitives + ProductCard, styled from design tokens.
   Cosmetic versions faithful to the real DS components (so the kit verifies
   standalone). Exposes window.AXUI. */
const I = () => window.AXIcons;

function Button({ variant='primary', size='md', full=false, iconLeft, iconRight, children, style={}, ...rest }) {
  const sizes = { sm:{height:36,padding:'0 14px',fontSize:'var(--fs-sm)',radius:'var(--radius-sm)'}, md:{height:44,padding:'0 20px',fontSize:'var(--fs-base)',radius:'var(--radius-md)'}, lg:{height:54,padding:'0 28px',fontSize:'var(--fs-md)',radius:'var(--radius-md)'} };
  const s = sizes[size]||sizes.md;
  const v = {
    primary:{background:'var(--action-primary)',color:'#fff',border:'1px solid transparent',boxShadow:'var(--shadow-accent-glow)'},
    accent:{background:'linear-gradient(120deg,var(--blue-600),var(--cyan-500))',color:'#fff',border:'1px solid transparent',boxShadow:'var(--shadow-accent-glow)'},
    dark:{background:'var(--action-dark)',color:'var(--text-on-dark)',border:'1px solid transparent',boxShadow:'var(--shadow-md)'},
    soft:{background:'var(--surface-accent-soft)',color:'var(--blue-700)',border:'1px solid var(--blue-100)'},
    outline:{background:'var(--surface-card)',color:'var(--text-strong)',border:'1px solid var(--border-strong)',boxShadow:'var(--shadow-xs)'},
    ghost:{background:'transparent',color:'var(--text-strong)',border:'1px solid transparent'},
  }[variant]||{};
  return <button {...rest} style={{display:'inline-flex',alignItems:'center',justifyContent:'center',gap:8,width:full?'100%':'auto',height:s.height,padding:s.padding,fontFamily:'var(--font-body)',fontWeight:600,fontSize:s.fontSize,borderRadius:s.radius,cursor:'pointer',whiteSpace:'nowrap',transition:'transform .12s var(--ease-out),filter .2s',...v,...style}}
    onMouseEnter={e=>e.currentTarget.style.filter='brightness(1.06)'}
    onMouseLeave={e=>{e.currentTarget.style.filter='none';e.currentTarget.style.transform='none';}}
    onMouseDown={e=>e.currentTarget.style.transform='translateY(1px) scale(.99)'}
    onMouseUp={e=>e.currentTarget.style.transform='none'}>
    {iconLeft}{children}{iconRight}
  </button>;
}

function IconButton({ variant='ghost', badge, label, children, style={}, ...rest }) {
  const v = { ghost:{background:'transparent'}, soft:{background:'var(--surface-sunken)',border:'1px solid var(--border-subtle)'} }[variant]||{};
  return <button aria-label={label} title={label} {...rest} style={{position:'relative',width:42,height:42,borderRadius:'var(--radius-md)',display:'inline-flex',alignItems:'center',justifyContent:'center',color:'var(--text-strong)',cursor:'pointer',border:'1px solid transparent',transition:'background .12s',...v,...style}}
    onMouseEnter={e=>e.currentTarget.style.background='var(--surface-sunken)'}
    onMouseLeave={e=>e.currentTarget.style.background=v.background}>
    {children}
    {badge!=null && badge>0 && <span style={{position:'absolute',top:-4,right:-4,minWidth:18,height:18,padding:'0 5px',background:'var(--blue-600)',color:'#fff',borderRadius:'999px',fontFamily:'var(--font-mono)',fontSize:10,fontWeight:700,display:'inline-flex',alignItems:'center',justifyContent:'center',border:'2px solid var(--surface-card)'}}>{badge}</span>}
  </button>;
}

const badgeTone = {
  'Best Seller':['var(--star-on)','#3a2400'], New:['linear-gradient(120deg,var(--blue-600),var(--cyan-500))','#fff'],
  Sale:['var(--sale)','#fff'], Limited:['var(--blue-600)','#fff'],
};
function Badge({ children, tone, soft=false, style={} }) {
  let bg='var(--slate-100)', fg='var(--slate-700)';
  if (tone && badgeTone[tone]) { bg=badgeTone[tone][0]; fg=badgeTone[tone][1]; }
  else if (tone==='success'){bg='var(--status-success-soft)';fg='var(--status-success)';}
  else if (tone==='danger'){bg='var(--status-danger-soft)';fg='var(--status-danger)';}
  else if (tone==='sale'){bg='var(--sale-100)';fg='var(--sale)';}
  return <span style={{display:'inline-flex',alignItems:'center',gap:4,background:bg,color:fg,fontFamily:'var(--font-body)',fontWeight:700,fontSize:'var(--fs-xs)',letterSpacing:'.02em',textTransform:'uppercase',padding:'3px 9px',borderRadius:'999px',lineHeight:1.4,whiteSpace:'nowrap',...style}}>{children}</span>;
}

function Stars({ value=0, size=15 }) {
  return <span style={{display:'inline-flex',gap:1}}>{[0,1,2,3,4].map(i=>{
    const f=Math.max(0,Math.min(1,value-i));
    return <svg key={i} width={size} height={size} viewBox="0 0 20 20" style={{display:'block'}}>
      <defs><linearGradient id={`s${i}-${Math.round(value*10)}`}><stop offset="50%" stopColor="var(--star-on)"/><stop offset="50%" stopColor="var(--star-off)"/></linearGradient></defs>
      <path d="M10 1.6l2.47 5.01 5.53.8-4 3.9.94 5.5L10 14.9l-4.95 2.6.94-5.5-4-3.9 5.53-.8L10 1.6z" fill={f>=0.75?'var(--star-on)':f>=0.25?`url(#s${i}-${Math.round(value*10)})`:'var(--star-off)'}/>
    </svg>;
  })}</span>;
}
function Rating({ value=0, count, showValue=false, size=15 }) {
  return <span style={{display:'inline-flex',alignItems:'center',gap:6}}>
    <Stars value={value} size={size}/>
    {showValue && <span style={{fontFamily:'var(--font-mono)',fontSize:'var(--fs-sm)',fontWeight:600,color:'var(--text-strong)'}}>{value.toFixed(1)}</span>}
    {count!=null && <span style={{fontFamily:'var(--font-body)',fontSize:'var(--fs-sm)',color:'var(--text-muted)'}}>({count.toLocaleString()})</span>}
  </span>;
}

function PriceTag({ price, compareAt, size='md' }) {
  const sz={sm:['var(--fs-base)','var(--fs-xs)'],md:['var(--fs-lg)','var(--fs-sm)'],lg:['var(--fs-2xl)','var(--fs-md)'],xl:['var(--fs-3xl)','var(--fs-lg)']}[size];
  const sale=compareAt&&compareAt>price; const pct=sale?Math.round((1-price/compareAt)*100):0;
  const fmt=n=>'$'+n.toFixed(2);
  return <span style={{display:'inline-flex',alignItems:'baseline',gap:8,flexWrap:'wrap'}}>
    <span style={{fontFamily:'var(--font-mono)',fontWeight:600,fontSize:sz[0],color:sale?'var(--sale)':'var(--text-strong)',fontFeatureSettings:"'tnum'"}}>{fmt(price)}</span>
    {sale && <span style={{fontFamily:'var(--font-mono)',fontSize:sz[1],color:'var(--text-faint)',textDecoration:'line-through'}}>{fmt(compareAt)}</span>}
    {sale && <span style={{fontFamily:'var(--font-body)',fontSize:'var(--fs-xs)',fontWeight:700,color:'var(--sale)',background:'var(--sale-100)',padding:'2px 7px',borderRadius:'999px'}}>−{pct}%</span>}
  </span>;
}

function QuantityStepper({ value, onChange, min=1, max=99 }) {
  const set=n=>onChange&&onChange(Math.max(min,Math.min(max,n)));
  const btn=(lbl,fn,dis)=> <button onClick={fn} disabled={dis} style={{width:42,height:44,border:'none',background:'transparent',color:dis?'var(--text-faint)':'var(--text-strong)',fontSize:18,cursor:dis?'not-allowed':'pointer',display:'inline-flex',alignItems:'center',justifyContent:'center'}}>{lbl}</button>;
  return <div style={{display:'inline-flex',alignItems:'center',height:44,border:'1px solid var(--border-default)',borderRadius:'var(--radius-md)',background:'var(--surface-card)',overflow:'hidden'}}>
    {btn('−',()=>set(value-1),value<=min)}
    <span style={{minWidth:38,textAlign:'center',fontFamily:'var(--font-mono)',fontWeight:600,color:'var(--text-strong)',borderLeft:'1px solid var(--border-subtle)',borderRight:'1px solid var(--border-subtle)',height:'100%',display:'inline-flex',alignItems:'center',justifyContent:'center'}}>{value}</span>
    {btn('+',()=>set(value+1),value>=max)}
  </div>;
}

function Input({ label, hint, error, iconLeft, iconRight, style={}, containerStyle={}, ...rest }) {
  const [f,setF]=React.useState(false);
  const bc=error?'var(--status-danger)':f?'var(--border-focus)':'var(--border-default)';
  return <div style={{display:'flex',flexDirection:'column',gap:6,...containerStyle}}>
    {label && <label style={{fontSize:'var(--fs-sm)',fontWeight:600,color:'var(--text-strong)'}}>{label}</label>}
    <div style={{display:'flex',alignItems:'center',gap:8,height:46,padding:'0 14px',background:'var(--surface-card)',border:`1px solid ${bc}`,borderRadius:'var(--radius-md)',boxShadow:f?'var(--shadow-focus)':'var(--shadow-xs)',transition:'border-color .2s,box-shadow .2s'}}>
      {iconLeft && <span style={{color:'var(--text-faint)',display:'inline-flex'}}>{iconLeft}</span>}
      <input {...rest} onFocus={e=>{setF(true);rest.onFocus&&rest.onFocus(e);}} onBlur={e=>{setF(false);rest.onBlur&&rest.onBlur(e);}} style={{flex:1,minWidth:0,border:'none',outline:'none',background:'transparent',fontFamily:'var(--font-body)',fontSize:'var(--fs-base)',color:'var(--text-strong)',...style}}/>
      {iconRight && <span style={{color:'var(--text-faint)',display:'inline-flex'}}>{iconRight}</span>}
    </div>
    {(error||hint) && <span style={{fontSize:'var(--fs-sm)',color:error?'var(--status-danger)':'var(--text-muted)'}}>{error||hint}</span>}
  </div>;
}

function Eyebrow({ children, style={} }) {
  return <span style={{fontSize:'var(--fs-xs)',fontWeight:700,letterSpacing:'.08em',textTransform:'uppercase',color:'var(--blue-600)',...style}}>{children}</span>;
}
function SectionHeader({ eyebrow, title, action, onAction }) {
  return <div style={{display:'flex',alignItems:'flex-end',justifyContent:'space-between',gap:16,marginBottom:28,flexWrap:'wrap'}}>
    <div style={{display:'flex',flexDirection:'column',gap:8}}>
      {eyebrow && <Eyebrow>{eyebrow}</Eyebrow>}
      <h2 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-2xl)',fontWeight:700,color:'var(--text-strong)',letterSpacing:'-0.02em',margin:0}}>{title}</h2>
    </div>
    {action && <button onClick={onAction} style={{display:'inline-flex',alignItems:'center',gap:6,background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font-body)',fontWeight:600,fontSize:'var(--fs-base)',color:'var(--blue-600)'}}>{action} {React.createElement(I().ArrowRight,{size:16})}</button>}
  </div>;
}

function ProductCard({ product, onAdd, onView }) {
  const [hover,setHover]=React.useState(false);
  const Ic=I();
  return <article onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}
    style={{display:'flex',flexDirection:'column',background:'var(--surface-card)',border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-xl)',overflow:'hidden',boxShadow:hover?'var(--shadow-card-hover)':'var(--shadow-sm)',transform:hover?'translateY(-4px)':'none',transition:'transform .2s var(--ease-out),box-shadow .2s var(--ease-out)'}}>
    <div style={{position:'relative',aspectRatio:'1/1',background:product.accent,overflow:'hidden',cursor:'pointer'}} onClick={()=>onView&&onView(product)}>
      {product.image
        ? <img src={product.image} alt={product.name} loading="lazy" style={{width:'100%',height:'100%',objectFit:'cover',display:'block',transform:hover?'scale(1.04)':'scale(1)',transition:'transform .28s var(--ease-out)'}}/>
        : <div style={{position:'absolute',inset:0,display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',fontWeight:700,fontSize:64,color:'rgba(10,17,36,0.10)'}}>{product.name.charAt(0)}</div>}
      {product.badge && <div style={{position:'absolute',top:12,left:12}}><Badge tone={product.badge}>{product.badge}</Badge></div>}
      <div style={{position:'absolute',left:12,right:12,bottom:12,opacity:hover?1:0,transform:hover?'translateY(0)':'translateY(8px)',transition:'opacity .2s,transform .2s',pointerEvents:hover?'auto':'none'}}>
        <Button variant="dark" size="sm" full iconLeft={React.createElement(Ic.Cart,{size:16})} onClick={e=>{e.stopPropagation();onAdd&&onAdd(product);}}>Add to Cart</Button>
      </div>
    </div>
    <div style={{display:'flex',flexDirection:'column',gap:8,padding:'var(--space-5)'}}>
      <span style={{fontSize:'var(--fs-xs)',fontWeight:700,letterSpacing:'.02em',textTransform:'uppercase',color:'var(--text-faint)'}}>{product.category}</span>
      <h3 onClick={()=>onView&&onView(product)} style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-md)',fontWeight:600,color:'var(--text-strong)',lineHeight:1.3,cursor:'pointer',margin:0,letterSpacing:'-0.01em'}}>{product.name}</h3>
      <Rating value={product.rating} count={product.reviewCount} size={14}/>
      <div style={{marginTop:4}}><PriceTag price={product.price} compareAt={product.compareAt}/></div>
    </div>
  </article>;
}

window.AXUI = { Button, IconButton, Badge, Stars, Rating, PriceTag, QuantityStepper, Input, Eyebrow, SectionHeader, ProductCard };
