/* App shell — state, cart (localStorage), routing, Checkout. Mounts the storefront. */
(function(){
const { AnnouncementBar, Header, Footer, Toast } = window.AXChrome;
const { Home } = window.AXScreens;
const { Products, ProductDetail, Cart, OrderSummary, OrderSuccess } = window.AXShop;
const { Login, Register, Forgot, Account } = window.AXAuth;
const { About, Contact, FAQ, ShippingReturns, Privacy, Terms } = window.AXPages;
const { Button, Input, Eyebrow } = 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 LS='ax_cart_v1';

function Checkout({ items, onPlace, onNav }){
  const i=Ic();
  const [method,setMethod]=React.useState('standard');
  const [pay,setPay]=React.useState('card');
  const sub=items.reduce((s,it)=>s+it.price*it.qty,0);
  const ship=method==='express'?14.99:(sub>49?0:6.99);
  const tax=+(sub*0.08).toFixed(2); const total=+(sub+ship+tax).toFixed(2);
  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'}}>Checkout</h1>
    <div style={{display:'grid',gridTemplateColumns:'1fr 360px',gap:32,alignItems:'start'}} className="ax-cart-grid">
      <form onSubmit={e=>{e.preventDefault();onPlace();}} style={{display:'flex',flexDirection:'column',gap:28}}>
        <Section title="Contact information">
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}} className="ax-form-2">
            <Input label="Email" type="email" required placeholder="you@example.com" containerStyle={{gridColumn:'span 2'}}/>
            <Input label="First name" required placeholder="Jordan"/>
            <Input label="Last name" required placeholder="Vale"/>
          </div>
        </Section>
        <Section title="Shipping address">
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}} className="ax-form-2">
            <Input label="Address" required placeholder="123 Market St" containerStyle={{gridColumn:'span 2'}}/>
            <Input label="City" required placeholder="San Francisco"/>
            <Input label="State / Region" required placeholder="CA"/>
            <Input label="ZIP / Postal code" required placeholder="94103"/>
            <Input label="Country" required defaultValue="United States"/>
          </div>
        </Section>
        <Section title="Shipping method">
          {[['standard','Standard','3–5 business days',sub>49?'Free':'$6.99'],['express','Express','1–2 business days','$14.99']].map(([v,t,d,p])=>
            <label key={v} onClick={()=>setMethod(v)} style={{display:'flex',alignItems:'center',gap:14,padding:'14px 16px',border:`1.5px solid ${method===v?'var(--blue-600)':'var(--border-default)'}`,borderRadius:'var(--radius-md)',cursor:'pointer',background:method===v?'var(--surface-accent-soft)':'var(--surface-card)'}}>
              <span style={{width:18,height:18,borderRadius:'999px',border:`1.5px solid ${method===v?'var(--blue-600)':'var(--border-strong)'}`,display:'inline-flex',alignItems:'center',justifyContent:'center',flex:'0 0 auto'}}>{method===v&&<span style={{width:9,height:9,borderRadius:'999px',background:'var(--blue-600)'}}/>}</span>
              <div style={{flex:1}}><div style={{fontWeight:600,color:'var(--text-strong)'}}>{t}</div><div style={{fontSize:'var(--fs-sm)',color:'var(--text-muted)'}}>{d}</div></div>
              <span style={{fontFamily:'var(--font-mono)',fontWeight:600,color:'var(--text-strong)'}}>{p}</span>
            </label>)}
        </Section>
        <Section title="Payment">
          <div style={{display:'flex',gap:10,marginBottom:4,flexWrap:'wrap'}}>
            {[['card','Card'],['paypal','PayPal'],['applepay','Apple Pay']].map(([v,t])=><button key={v} type="button" onClick={()=>setPay(v)} style={{padding:'9px 16px',borderRadius:'var(--radius-md)',border:`1.5px solid ${pay===v?'var(--blue-600)':'var(--border-default)'}`,background:pay===v?'var(--surface-accent-soft)':'var(--surface-card)',color:pay===v?'var(--blue-700)':'var(--text-body)',fontFamily:'var(--font-body)',fontWeight:600,fontSize:'var(--fs-sm)',cursor:'pointer'}}>{t}</button>)}
          </div>
          {pay==='card' ? <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}} className="ax-form-2">
            <Input label="Card number" placeholder="1234 5678 9012 3456" iconRight={React.createElement(i.Lock,{size:15})} containerStyle={{gridColumn:'span 2'}}/>
            <Input label="Expiry" placeholder="MM / YY"/>
            <Input label="CVC" placeholder="123"/>
          </div> : <div style={{padding:'18px',background:'var(--surface-sunken)',borderRadius:'var(--radius-md)',fontSize:'var(--fs-sm)',color:'var(--text-muted)',textAlign:'center'}}>You'll be redirected to {pay==='paypal'?'PayPal':'Apple Pay'} to complete payment. <em>(Demo — no real payment.)</em></div>}
          <div style={{display:'flex',alignItems:'center',gap:7,fontSize:'var(--fs-sm)',color:'var(--text-faint)',marginTop:10}}>{React.createElement(i.Shield,{size:15})} This is a demo storefront — payment is not collected. <code style={{fontFamily:'var(--font-mono)',fontSize:'var(--fs-xs)'}}>createPaymentIntent()</code> is stubbed.</div>
        </Section>
        <Button variant="accent" size="lg" full type="submit" iconRight={React.createElement(i.ArrowRight,{size:18})}>Place Order · ${total.toFixed(2)}</Button>
      </form>
      <div style={{display:'flex',flexDirection:'column',gap:14}}>
        <div style={{background:'var(--surface-card)',border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-xl)',padding:20,display:'flex',flexDirection:'column',gap:12,boxShadow:'var(--shadow-sm)'}}>
          {items.map(it=><div key={it.id} style={{display:'flex',gap:12,alignItems:'center'}}>
            <div style={{position:'relative',width:54,height:54,borderRadius:'var(--radius-md)',background:it.accent,flex:'0 0 auto',display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'var(--font-display)',fontWeight:700,color:'rgba(10,17,36,0.12)'}}>{it.name.charAt(0)}<span style={{position:'absolute',top:-7,right:-7,minWidth:20,height:20,padding:'0 5px',background:'var(--slate-600)',color:'#fff',borderRadius:'999px',fontFamily:'var(--font-mono)',fontSize:11,fontWeight:700,display:'inline-flex',alignItems:'center',justifyContent:'center'}}>{it.qty}</span></div>
            <span style={{flex:1,fontSize:'var(--fs-sm)',fontWeight:500,color:'var(--text-strong)'}}>{it.name}</span>
            <span style={{fontFamily:'var(--font-mono)',fontSize:'var(--fs-sm)',fontWeight:600,color:'var(--text-strong)'}}>${(it.price*it.qty).toFixed(2)}</span>
          </div>)}
        </div>
        <OrderSummary sub={sub} ship={ship} tax={tax} total={total} onCheckout={()=>onPlace()} cta="Place Order"/>
      </div>
    </div>
  </div>;
}
function Section({ title, children }){
  return <div style={{display:'flex',flexDirection:'column',gap:14}}>
    <h2 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-lg)',fontWeight:600,color:'var(--text-strong)',margin:0}}>{title}</h2>
    {children}
  </div>;
}

function TrackOrder({ presetOrder, onNav }){
  const i=Ic();
  const [num,setNum]=React.useState(presetOrder||'');
  const [email,setEmail]=React.useState('');
  const [result,setResult]=React.useState(presetOrder?'ok':null);
  const steps=['Order Placed','Processing','Shipped','Out for Delivery','Delivered'];
  const current=2;
  return <div style={{...wrap,padding:'36px var(--gutter) 0',maxWidth:720}}>
    <Eyebrow>Order tracking</Eyebrow>
    <h1 style={{fontFamily:'var(--font-display)',fontSize:'var(--fs-3xl)',fontWeight:700,color:'var(--text-strong)',letterSpacing:'-0.02em',margin:'8px 0 22px'}}>Track your order</h1>
    <form onSubmit={e=>{e.preventDefault();setResult('ok');}} style={{display:'flex',gap:12,alignItems:'flex-end',flexWrap:'wrap',background:'var(--surface-card)',border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-xl)',padding:20,boxShadow:'var(--shadow-sm)'}}>
      <Input label="Order number" value={num} onChange={e=>setNum(e.target.value)} placeholder="ORD-2026-XXXXX" containerStyle={{flex:1,minWidth:180}}/>
      <Input label="Email" value={email} onChange={e=>setEmail(e.target.value)} placeholder="you@example.com" containerStyle={{flex:1,minWidth:180}}/>
      <Button variant="primary" size="lg" type="submit">Track</Button>
    </form>
    {result==='ok' && <div style={{marginTop:24,background:'var(--surface-card)',border:'1px solid var(--border-subtle)',borderRadius:'var(--radius-xl)',padding:28,boxShadow:'var(--shadow-sm)'}}>
      <div style={{display:'flex',justifyContent:'space-between',marginBottom:24,flexWrap:'wrap',gap:8}}>
        <div><span style={{fontSize:'var(--fs-sm)',color:'var(--text-muted)'}}>Order</span><div style={{fontFamily:'var(--font-mono)',fontWeight:600,color:'var(--text-strong)'}}>{num||'ORD-2026-04817'}</div></div>
        <div style={{textAlign:'right'}}><span style={{fontSize:'var(--fs-sm)',color:'var(--text-muted)'}}>Est. delivery</span><div style={{fontWeight:600,color:'var(--text-strong)'}}>Jun 19, 2026</div></div>
      </div>
      <div style={{display:'flex',flexDirection:'column',gap:0}}>
        {steps.map((s,k)=><div key={s} style={{display:'flex',gap:14,alignItems:'flex-start'}}>
          <div style={{display:'flex',flexDirection:'column',alignItems:'center'}}>
            <span style={{width:28,height:28,borderRadius:'999px',background:k<=current?'var(--blue-600)':'var(--surface-sunken)',color:'#fff',border:k<=current?'none':'1.5px solid var(--border-default)',display:'inline-flex',alignItems:'center',justifyContent:'center',flex:'0 0 auto'}}>{k<=current?React.createElement(i.Check,{size:15,sw:3}):''}</span>
            {k<steps.length-1 && <span style={{width:2,height:32,background:k<current?'var(--blue-600)':'var(--border-default)'}}/>}
          </div>
          <div style={{paddingBottom:k<steps.length-1?14:0,paddingTop:3}}>
            <div style={{fontWeight:600,color:k<=current?'var(--text-strong)':'var(--text-faint)'}}>{s}</div>
            {k===current && <div style={{fontSize:'var(--fs-sm)',color:'var(--blue-600)'}}>In transit · expected soon</div>}
          </div>
        </div>)}
      </div>
    </div>}
  </div>;
}

function App(){
  const [route,setRoute]=React.useState({type:'home'});
  const [cart,setCart]=React.useState(()=>{try{return JSON.parse(localStorage.getItem(LS))||[];}catch(e){return [];}});
  const [toast,setToast]=React.useState(null);
  const [query,setQuery]=React.useState('');
  const [orderNo,setOrderNo]=React.useState('');
  const [authed,setAuthed]=React.useState(false);
  const toastT=React.useRef();
  React.useEffect(()=>{try{localStorage.setItem(LS,JSON.stringify(cart));}catch(e){}},[cart]);
  React.useEffect(()=>{window.scrollTo(0,0);},[route]);
  const showToast=(m)=>{setToast(m);clearTimeout(toastT.current);toastT.current=setTimeout(()=>setToast(null),2200);};
  const cartCount=cart.reduce((s,i)=>s+i.qty,0);
  const add=(p,qty=1)=>{setCart(c=>{const e=c.find(x=>x.id===p.id);if(e)return c.map(x=>x.id===p.id?{...x,qty:Math.min(x.qty+qty,p.stock)}:x);return [...c,{id:p.id,name:p.name,category:p.category,price:p.price,compareAt:p.compareAt,accent:p.accent,stock:p.stock,qty}];});showToast(`Added ${p.name} to cart`);};
  const setQty=(id,q)=>setCart(c=>c.map(x=>x.id===id?{...x,qty:q}:x));
  const remove=(id)=>setCart(c=>c.filter(x=>x.id!==id));
  const pageMap={'Track Order':{type:'track'},'Shipping & Returns':{type:'shipping'},'FAQ':{type:'faq'},'Contact Us':{type:'contact'},'About AshopNexa':{type:'about'},'Privacy Policy':{type:'privacy'},'Terms of Service':{type:'terms'},'Best Sellers':{type:'products',label:'Best Sellers'},'New Arrivals':{type:'products',label:'New Arrivals'},'Collections':{type:'products',label:'All Products'},'Gift Cards':{type:'products',label:'All Products'},'Careers':{type:'about'}};
  const nav=(r)=>{ if(r.type==='page'){ setRoute(pageMap[r.label]||{type:'home'}); } else setRoute(r); };
  const place=()=>{const n='ORD-2026-'+Math.floor(10000+Math.random()*89999);setOrderNo(n);setCart([]);setRoute({type:'success'});};

  let view;
  if(route.type==='home') view=<Home onNav={nav} onAdd={add} onView={p=>setRoute({type:'detail',product:p})}/>;
  else if(route.type==='products') view=<Products initialLabel={route.label} query={query} onAdd={add} onView={p=>setRoute({type:'detail',product:p})} onNav={nav}/>;
  else if(route.type==='detail') view=<ProductDetail product={route.product} onAdd={add} onBuy={(p,q)=>{add(p,q);setRoute({type:'checkout'});}} onView={p=>setRoute({type:'detail',product:p})} onNav={nav}/>;
  else if(route.type==='cart') view=<Cart items={cart} onQty={setQty} onRemove={remove} onNav={nav} onCheckout={()=>setRoute({type:'checkout'})}/>;
  else if(route.type==='checkout') view=cart.length?<Checkout items={cart} onPlace={place} onNav={nav}/>:<Cart items={cart} onNav={nav}/>;
  else if(route.type==='success') view=<OrderSuccess orderNo={orderNo} onNav={nav}/>;
  else if(route.type==='track') view=<TrackOrder presetOrder={route.order} onNav={nav}/>;
  else if(route.type==='login') view=<Login onNav={nav} onAuth={()=>{setAuthed(true);showToast('Signed in — welcome back!');setRoute({type:'account'});}}/>;
  else if(route.type==='register') view=<Register onNav={nav} onAuth={()=>{setAuthed(true);showToast('Account created — welcome to AshopNexa!');setRoute({type:'account'});}}/>;
  else if(route.type==='forgot') view=<Forgot onNav={nav}/>;
  else if(route.type==='account') view=authed?<Account onNav={nav} onLogout={()=>{setAuthed(false);showToast('Signed out');setRoute({type:'home'});}}/>:<Login onNav={nav} onAuth={()=>{setAuthed(true);showToast('Signed in — welcome back!');setRoute({type:'account'});}}/>;
  else if(route.type==='about') view=<About onNav={nav}/>;
  else if(route.type==='contact') view=<Contact onNav={nav}/>;
  else if(route.type==='faq') view=<FAQ onNav={nav}/>;
  else if(route.type==='shipping') view=<ShippingReturns onNav={nav}/>;
  else if(route.type==='privacy') view=<Privacy/>;
  else if(route.type==='terms') view=<Terms/>;
  else view=<Home onNav={nav} onAdd={add} onView={p=>setRoute({type:'detail',product:p})}/>;

  return <div style={{minHeight:'100vh',display:'flex',flexDirection:'column'}}>
    <AnnouncementBar/>
    <Header cartCount={cartCount} authed={authed} onNav={nav} onAccount={()=>setRoute({type:authed?'account':'login'})} onCart={()=>setRoute({type:'cart'})} query={query} onQuery={setQuery} onSearch={()=>setRoute({type:'products',label:'All Products'})}/>
    <main style={{flex:1,paddingBottom:40}}>{view}</main>
    <Footer onNav={nav}/>
    <Toast toast={toast}/>
  </div>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
})();
