const SAREE_PHOTOS=['photo-1641699862936-be9f49b1c38d','photo-1727430228383-aa1fb59db8bf','photo-1618901185975-d59f7091bcfe','photo-1617627143750-d86bc21e42bb','photo-1610189012906-4c0aa9b9781e','flagged/photo-1551854716-8b811be39e7e','photo-1692992193981-d3d92fabd9cb','photo-1588140686379-1b76a52103dc','photo-1618489335755-e3aa2b16cd7a','photo-1616756141603-6d37d5cde2a2','photo-1654764746242-7592b9c6ce2e','photo-1640880085999-2e9ea9330d7f','photo-1610189013429-a703f4b245cf','photo-1614881064213-180b1c28f743','photo-1610189026205-27510cfc52f8','photo-1521572163474-6864f9cf17ab','photo-1622445275463-afa2ab738c34','photo-1611591437281-460bfbe1220a','photo-1515562141207-7a88fb7ce338','photo-1608571423902-eed4a5ad8108','photo-1602928321679-560bb453f190'];
const MEN_PHOTOS=['photo-1521572163474-6864f9cf17ab','photo-1602810318383-e386cc2a3ccf','photo-1473966968600-fa801b869a1a','photo-1624378439575-d8705ad7ae80'];
function menPhoto(i,w=1400){const n=((i%MEN_PHOTOS.length)+MEN_PHOTOS.length)%MEN_PHOTOS.length;return `https://images.unsplash.com/${MEN_PHOTOS[n]}?auto=format&fit=crop&w=${w}&q=80`;}
function photo(i,w=1400){ if(typeof i==='string'&&i.startsWith('men:'))return menPhoto(parseInt(i.slice(4),10),w); const n=((i%SAREE_PHOTOS.length)+SAREE_PHOTOS.length)%SAREE_PHOTOS.length;return `https://images.unsplash.com/${SAREE_PHOTOS[n]}?auto=format&fit=crop&w=${w}&q=80`;}
function money(n){return '₹'+n.toLocaleString('en-IN');}
const CATEGORY_LABELS={sarees:'Saree',tshirts:'T-Shirts',jewellery:'Jewellery',perfumes:'Fragrances',bottomwear:'Trousers'};
const BB_PRODUCT_LINK_TARGET=(function(){
  try{
    const h=location.hostname;
    const isProd=/^(www\.)?boldbee\.store$/.test(h);
    return isProd?'_blank':'_self';
  }catch(e){}
  return '_self';
})();
function productLinkProps(){ return BB_PRODUCT_LINK_TARGET==='_blank'?{target:'_blank',rel:'noopener noreferrer'}:{}; }
const AVAILABILITY_LABELS={'in-stock':'Available','low-stock':'Limited Availability','critical':'Limited Availability','out-of-stock':'Sold Out'};
function availabilityLabel(status){ return AVAILABILITY_LABELS[status]||'Available'; }
function triggerCollectionToast(msg){ window.dispatchEvent(new CustomEvent('bb-collection-toast',{detail:msg})); }
function CollectionToast(){
  const [msg,setMsg]=React.useState(null);
  const [visible,setVisible]=React.useState(false);
  React.useEffect(()=>{
    function onToast(e){
      setMsg(e.detail);
      setVisible(true);
      const t1=setTimeout(()=>setVisible(false),2200);
      const t2=setTimeout(()=>setMsg(null),2600);
      return ()=>{clearTimeout(t1);clearTimeout(t2);};
    }
    window.addEventListener('bb-collection-toast',onToast);
    return ()=>window.removeEventListener('bb-collection-toast',onToast);
  },[]);
  if(!msg)return null;
  return (<div role="status" aria-live="polite" style={{position:'fixed',left:'50%',bottom:36,transform:'translateX(-50%)',background:'var(--charcoal)',color:'var(--ivory)',padding:'14px 26px',borderRadius:'var(--radius-pill)',fontSize:13,letterSpacing:'0.04em',boxShadow:'var(--shadow-card)',zIndex:1000,opacity:visible?1:0,transition:'opacity 420ms var(--ease-out)',pointerEvents:'none'}}>{msg}</div>);
}
function categoryLabel(p){ return p.weave||CATEGORY_LABELS[p.category]||'Bold Bee'; }
function filterLabel(p){ return p.weave||categoryLabel(p); }
function productBlurb(p){
  if(!p.category||p.category==='sarees')return `Hand-woven in a ${p.weave} tradition, this saree carries six weeks of a single weaver's work in every length. ${p.sub}, finished with a hand-checked border.`;
  if(p.category==='tshirts')return `Cut from heavyweight combed cotton and garment-dyed for depth, this tee is built for everyday wear. ${p.sub}.`;
  if(p.category==='jewellery')return `Finished by hand and designed to layer effortlessly. ${p.sub}.`;
  if(p.category==='perfumes')return `A composition built in layers, designed to develop over the day. ${p.sub}.`;
  return p.sub||'';
}
function productSchemaDescription(p){
  if(!p.category||p.category==='sarees')return `Hand-woven ${p.weave} silk saree, ${p.sub}.`;
  return `${p.name} — ${p.sub}.`;
}
const COLLECTIONS=[
{slug:'bridal-kanjivaram',name:'Bridal Kanjivaram',desc:'Heirloom weight, temple motifs, woven for ceremony.',hero:1},
{slug:'everyday-linen-silk',name:'Everyday Linen Silk',desc:'Light drape for daily grace.',hero:2},
{slug:'festive-banarasi',name:'Festive Banarasi',desc:'Gold zari, ceremonial gleam.',hero:3},
{slug:'signature-essentials',name:'Signature Essentials',desc:'Beyond the saree — everyday luxury essentials.',hero:16}
];
const PRODUCTS=(typeof ProductStore!=='undefined'&&ProductStore.publicList().length)?ProductStore.publicList():[
{id:'temple-border-kanjivaram',name:'Temple Border Kanjivaram',collection:'bridal-kanjivaram',weave:'Kanjivaram',sub:'Deep Maroon · Gold Zari',price:42500,imgs:[4,5,6],gender:'women'},
{id:'sheer-organza-drape',name:'Sheer Organza Drape',collection:'everyday-linen-silk',weave:'Organza',sub:'Ivory · Silver Thread',price:28900,imgs:[6,7,8],gender:'women'},
{id:'woven-tussar-saree',name:'Woven Tussar Saree',collection:'festive-banarasi',weave:'Tussar',sub:'Rust · Natural Silk',price:24500,imgs:[8,9,10],gender:'women'},
{id:'handloom-linen-silk',name:'Handloom Linen Silk',collection:'everyday-linen-silk',weave:'Linen Silk',sub:'Sage · Minimal Border',price:19800,imgs:[10,11,12],gender:'women'},
{id:'zari-brocade-banarasi',name:'Zari Brocade Banarasi',collection:'festive-banarasi',weave:'Banarasi',sub:'Wine · Gold Brocade',price:38900,imgs:[0,1,2],gender:'women'},
{id:'temple-motif-kanjivaram-ivory',name:'Temple Motif Kanjivaram, Ivory',collection:'bridal-kanjivaram',weave:'Kanjivaram',sub:'Ivory · Gold Border',price:45900,imgs:[2,3,4],gender:'women'},
{id:'handwoven-tussar-natural',name:'Handwoven Tussar, Natural',collection:'festive-banarasi',weave:'Tussar',sub:'Natural · Copper Zari',price:26500,imgs:[9,10,11],gender:'women'},
{id:'organza-blush-drape',name:'Organza Blush Drape',collection:'everyday-linen-silk',weave:'Organza',sub:'Blush · Silver Thread',price:27500,imgs:[7,8,9],gender:'women'},
{id:'handwoven-silk-classic',name:'Handwoven Silk Classic',collection:'bridal-kanjivaram',weave:'Handwoven Silk',sub:'Emerald · Gold Trim',price:36500,imgs:[1,2,3],gender:'women'},
{id:'classic-crew-tshirt',name:'Classic Crew T-Shirt',category:'tshirts',collection:'signature-essentials',sub:'White · 100% Cotton',price:1899,imgs:[15,16],gender:'women'},
{id:'gold-vermeil-chain-necklace',name:'Gold Vermeil Chain Necklace',category:'jewellery',collection:'signature-essentials',sub:'18K Gold Vermeil · Adjustable',price:12500,imgs:[17,18]},
{id:'oud-amber-eau-de-parfum',name:'Oud & Amber Eau de Parfum',category:'perfumes',collection:'signature-essentials',sub:'Eau de Parfum',price:6800,imgs:[19,20]},
{id:'classic-crew-tshirt-men',name:'Classic Crew T-Shirt',category:'tshirts',collection:'signature-essentials',sub:'Charcoal · 100% Cotton',price:1999,imgs:['men:0','men:1'],gender:'men'},
{id:'tailored-chino-trouser',name:'Tailored Chino Trouser',category:'bottomwear',collection:'signature-essentials',sub:'Stone · Cotton Twill',price:3800,imgs:['men:2','men:3'],gender:'men'}
];
function productBySlug(id){return PRODUCTS.find(p=>p.id===id);}
let _bbStockLinked=false;
function ensureStockLinked(){
  if(typeof ProductStore==='undefined'||typeof InventoryStore==='undefined')return;
  if(_bbStockLinked)return;
  const seedStock=[25,3,0,40,8,60,0,15,30,5];
  let created=false;
  PRODUCTS.forEach((p,i)=>{
    if(ProductStore.get(p.id))return;
    ProductStore.save({id:p.id,sku:p.id,name:p.name,category:'Sarees',collection:p.collection,sellingPrice:p.price,mrp:p.price,stock:seedStock[i%seedStock.length],lowStockAlert:10,status:'published'});
    created=true;
  });
  InventoryStore.all();
  _bbStockLinked=true;
}
function stockInfo(productId,excludeSessionId){
  if(typeof InventoryStore==='undefined')return {status:'in-stock',availableStock:99};
  ensureStockLinked();
  const rec=InventoryStore.get(productId);
  if(!rec)return {status:'in-stock',availableStock:99};
  let avail=rec.availableStock;
  // EIRCE: close the pre-order concurrency window additively — never mutates InventoryStore or
  // OrderStore. Subtracts (a) other customers' active temporary reservations and (b) quantities
  // sitting in just-created orders that haven't yet reached "Order Confirmed" (the point at which
  // the existing InventoryStore reservedStock bump already takes over).
  if(typeof ReservationStore!=='undefined'){
    const sid=excludeSessionId!==undefined?excludeSessionId:(typeof BB_STORE!=='undefined'?BB_STORE.sessionId():null);
    avail-=ReservationStore.activeQtyExcludingSession(productId,undefined,sid);
  }
  if(typeof OrderStore!=='undefined'){
    OrderStore.all().filter(o=>o.status==='Order Received').forEach(o=>{
      (o.items||[]).forEach(it=>{ if(it.productId===productId)avail-=(it.qty||0); });
    });
  }
  avail=Math.max(0,avail);
  let status=rec.status;
  if(avail<=0)status='out-of-stock'; else if(status==='out-of-stock')status=avail<=(rec.criticalStockAlert||5)?'critical':(avail<=(rec.lowStockAlert||10)?'low-stock':'in-stock');
  return {status,availableStock:avail};
}
const BB_STORE={
  ckey:'bb_cart',wkey:'bb_wishlist',rkey:'bb_recent',okey:'bb_orders',skey:'bb_save_for_later',
  sessionId(){
    let id=sessionStorage.getItem('bb_session_id');
    if(!id){ id='SESS-'+Date.now().toString(36).toUpperCase()+'-'+Math.floor(Math.random()*9000+1000); sessionStorage.setItem('bb_session_id',id); }
    return id;
  },
  getCart(){try{return JSON.parse(localStorage.getItem(this.ckey)||'[]');}catch(e){return [];}},
  setCart(c){localStorage.setItem(this.ckey,JSON.stringify(c));window.dispatchEvent(new Event('bb-cart-update'));},
  addToCart(id,size,qty){
    const c=this.getCart();
    const avail=stockInfo(id).availableStock;
    const ex=c.find(i=>i.id===id&&i.size===size);
    const before=ex?ex.qty:0;
    let after=Math.min(before+qty,avail);
    after=Math.max(0,after);
    if(ex)ex.qty=after; else if(after>0)c.push({id,size,qty:after});
    this.setCart(c);
    return {requested:before+qty,applied:after,availableStock:avail,adjusted:after<before+qty};
  },
  updateQty(idx,qty){
    const c=this.getCart();
    if(qty<=0){c.splice(idx,1);this.setCart(c);return {applied:0,adjusted:false};}
    const item=c[idx];
    const avail=item?stockInfo(item.id).availableStock:qty;
    const applied=Math.min(qty,avail);
    if(item)item.qty=applied;
    this.setCart(c);
    return {applied,availableStock:avail,adjusted:applied<qty};
  },
  removeFromCart(idx){const c=this.getCart();c.splice(idx,1);this.setCart(c);},
  cartCount(){return this.getCart().reduce((a,i)=>a+i.qty,0);},
  cartTotal(){return this.getCart().reduce((a,i)=>{const p=productBySlug(i.id);return a+(p?p.price*i.qty:0);},0);},
  getWishlist(){try{return JSON.parse(localStorage.getItem(this.wkey)||'[]');}catch(e){return [];}},
  wishEntries(){ return this.getWishlist().map(e=>typeof e==='string'?{id:e,size:null,priceAtAdd:null,addedAt:null}:e); },
  toggleWishlist(id){const w=this.getWishlist();const idx=w.findIndex(e=>(typeof e==='string'?e:e.id)===id);const adding=idx<0;if(idx>=0)w.splice(idx,1);else w.push(id);localStorage.setItem(this.wkey,JSON.stringify(w));if(adding&&typeof NotificationStore!=='undefined'){const u=typeof BB_AUTH!=='undefined'?BB_AUTH.currentUser():null;NotificationStore.publish('wishlist.created',{name:u?u.name:'Guest',customerId:u?u.id:''});}window.dispatchEvent(new Event('bb-wish-update'));},
  addCollectionEntry(id,size,price){const w=this.getWishlist().filter(e=>(typeof e==='string'?e:e.id)!==id);w.push({id,size:size||null,priceAtAdd:price,addedAt:new Date().toISOString()});localStorage.setItem(this.wkey,JSON.stringify(w));window.dispatchEvent(new Event('bb-wish-update'));},
  isWished(id){return this.getWishlist().some(e=>(typeof e==='string'?e:e.id)===id);},
  getSaveForLater(){try{return JSON.parse(localStorage.getItem(this.skey)||'[]');}catch(e){return [];}},
  setSaveForLater(s){localStorage.setItem(this.skey,JSON.stringify(s));},
  moveCartToSaveForLater(idx){
    const c=this.getCart(); const item=c[idx]; if(!item)return;
    c.splice(idx,1); this.setCart(c);
    const s=this.getSaveForLater().filter(x=>!(x.id===item.id&&x.size===item.size));
    s.push({id:item.id,size:item.size,qty:item.qty,savedAt:new Date().toISOString()});
    this.setSaveForLater(s);
  },
  moveSaveForLaterToCart(idx){
    const s=this.getSaveForLater(); const item=s[idx]; if(!item)return;
    s.splice(idx,1); this.setSaveForLater(s);
    return this.addToCart(item.id,item.size,item.qty||1);
  },
  removeSaveForLater(idx){ const s=this.getSaveForLater(); s.splice(idx,1); this.setSaveForLater(s); },
  moveWishlistToCart(id,size){
    const w=this.getWishlist(); const idx=w.findIndex(e=>(typeof e==='string'?e:e.id)===id);
    const result=this.addToCart(id,size||null,1);
    if(idx>=0){ w.splice(idx,1); localStorage.setItem(this.wkey,JSON.stringify(w)); }
    if(typeof WishlistStore!=='undefined'&&typeof BB_AUTH!=='undefined'){
      const u=BB_AUTH.currentUser();
      if(u)WishlistStore.markConverted(u.id,id,size||null);
    }
    return result;
  },
  pushRecent(id){let r=this.getRecent().filter(x=>x!==id);r.unshift(id);r=r.slice(0,6);localStorage.setItem(this.rkey,JSON.stringify(r));},
  getRecent(){try{return JSON.parse(localStorage.getItem(this.rkey)||'[]');}catch(e){return [];}},
  placeOrder(order){const o=this.getOrders();o.unshift(order);localStorage.setItem(this.okey,JSON.stringify(o));this.setCart([]);},
  getOrders(){try{return JSON.parse(localStorage.getItem(this.okey)||'[]');}catch(e){return [];}},
  getOrder(id){return this.getOrders().find(o=>o.id===id)||null;}
};
function useCartCount(){
  const [n,setN]=React.useState(0);
  React.useEffect(()=>{
    const upd=()=>setN(BB_STORE.cartCount());
    upd();
    window.addEventListener('bb-cart-update',upd);
    window.addEventListener('storage',upd);
    return ()=>{window.removeEventListener('bb-cart-update',upd);window.removeEventListener('storage',upd);};
  },[]);
  return n;
}
const BB_OAUTH_CONFIG={
  google:{clientId:'',configured:false},
  apple:{clientId:'',configured:false}
};
const BB_AUTH={
  ukey:'bb_customers',skey:'bb_session',
  _hash(pw){let h=0;for(let i=0;i<pw.length;i++){h=(h*31+pw.charCodeAt(i))|0;}return 'h'+h;},
  getCustomers(){try{return JSON.parse(localStorage.getItem(this.ukey)||'[]');}catch(e){return [];}},
  saveCustomers(c){localStorage.setItem(this.ukey,JSON.stringify(c));},
  register({name,email,mobile,password,marketing}){
    const customers=this.getCustomers();
    if(customers.find(c=>c.email.toLowerCase()===email.toLowerCase()))return {ok:false,error:'An account with this email already exists.'};
    const customer={id:'CUST'+Date.now(),name,email,mobile:mobile||'',passwordHash:this._hash(password),provider:'email',registeredAt:new Date().toISOString(),lastLogin:new Date().toISOString(),addresses:[],preferredCategories:[],marketing:{newsletter:!!marketing,newArrivals:!!marketing,collectionLaunches:!!marketing,festivalOffers:!!marketing,memberEvents:!!marketing,restock:!!marketing}};
    customers.push(customer);
    this.saveCustomers(customers);
    localStorage.setItem(this.skey,customer.id);
    window.dispatchEvent(new Event('bb-auth-update'));
    if(typeof NotificationStore!=='undefined')NotificationStore.publish('customer.registered',{name:customer.name,email:customer.email,customerId:customer.id});
    return {ok:true,customer};
  },
  login(email,password){
    const customers=this.getCustomers();
    const c=customers.find(x=>x.email.toLowerCase()===email.toLowerCase());
    if(typeof SecurityStore!=='undefined'&&SecurityStore.isLocked('customer',email))return {ok:false,error:'This account is temporarily locked after too many failed attempts. Please try again later.'};
    if(!c||c.passwordHash!==this._hash(password)){
      if(typeof SecurityStore!=='undefined')SecurityStore.recordAttempt('customer',email,false);
      return {ok:false,error:'Incorrect email or password.'};
    }
    c.lastLogin=new Date().toISOString();
    this.saveCustomers(customers);
    localStorage.setItem(this.skey,c.id);
    if(typeof SecurityStore!=='undefined'){
      SecurityStore.recordAttempt('customer',email,true);
      const sess=SecurityStore.createSession('customer',c.id,c.name||c.email);
      localStorage.setItem('bb_customer_session_id',sess.id);
    }
    window.dispatchEvent(new Event('bb-auth-update'));
    if(typeof NotificationStore!=='undefined')NotificationStore.publish('customer.login',{name:c.name,customerId:c.id,time:new Date().toLocaleString('en-IN')});
    return {ok:true,customer:c};
  },
  loginWithProvider(provider,profile){
    if(!profile||!profile.email)return {ok:false,error:'The provider did not return an email address.'};
    const customers=this.getCustomers();
    let c=customers.find(x=>x.email.toLowerCase()===profile.email.toLowerCase());
    if(c){
      c.lastLogin=new Date().toISOString();
      if(!c.provider||c.provider==='email')c.provider=provider;
    }else{
      c={id:'CUST'+Date.now(),name:profile.name||profile.email.split('@')[0],email:profile.email,mobile:'',passwordHash:null,provider,registeredAt:new Date().toISOString(),lastLogin:new Date().toISOString(),addresses:[],preferredCategories:[],marketing:{newsletter:true,newArrivals:true,collectionLaunches:true,festivalOffers:true,memberEvents:true,restock:true}};
      customers.push(c);
      if(typeof NotificationStore!=='undefined')NotificationStore.publish('customer.registered',{name:c.name,email:c.email,customerId:c.id});
    }
    this.saveCustomers(customers);
    localStorage.setItem(this.skey,c.id);
    window.dispatchEvent(new Event('bb-auth-update'));
    return {ok:true,customer:c};
  },
  logout(){
    if(typeof SecurityStore!=='undefined'){
      const sid=localStorage.getItem('bb_customer_session_id');
      if(sid)SecurityStore.terminateSession(sid);
      localStorage.removeItem('bb_customer_session_id');
    }
    localStorage.removeItem(this.skey);window.dispatchEvent(new Event('bb-auth-update'));
  },
  currentUser(){
    const id=localStorage.getItem(this.skey);
    if(!id)return null;
    return this.getCustomers().find(c=>c.id===id)||null;
  },
  changePassword(id,currentPassword,newPassword){
    const customers=this.getCustomers();
    const c=customers.find(x=>x.id===id);
    if(!c)return {ok:false,error:'Account not found.'};
    if(c.passwordHash!==this._hash(currentPassword))return {ok:false,error:'Current password is incorrect.'};
    if(typeof SecurityStore!=='undefined'){
      const check=SecurityStore.validatePassword(newPassword);
      if(!check.valid)return {ok:false,error:'Password must include: '+check.errors.join(', ')+'.'};
      if(SecurityStore.checkPasswordReuse(id,newPassword))return {ok:false,error:'Please choose a password you haven\'t used recently.'};
    }
    c.passwordHash=this._hash(newPassword);
    this.saveCustomers(customers);
    if(typeof SecurityStore!=='undefined')SecurityStore.recordPasswordHistory(id,newPassword);
    if(typeof NotificationStore!=='undefined')NotificationStore.publish('customer.password_changed',{name:c.name,customerId:c.id,email:c.email});
    return {ok:true};
  },
  resetPassword(email,newPassword){
    const customers=this.getCustomers();
    const c=customers.find(x=>x.email.toLowerCase()===email.toLowerCase());
    if(!c)return {ok:false};
    c.passwordHash=this._hash(newPassword);
    this.saveCustomers(customers);
    return {ok:true};
  },
  updateProfile(id,patch){
    const customers=this.getCustomers();
    const c=customers.find(x=>x.id===id);
    if(!c)return null;
    Object.assign(c,patch);
    this.saveCustomers(customers);
    window.dispatchEvent(new Event('bb-auth-update'));
    if(typeof NotificationStore!=='undefined')NotificationStore.publish('customer.profile_updated',{name:c.name,customerId:c.id});
    return c;
  },
  passwordStrength(pw){
    let score=0;
    if(pw.length>=8)score++;
    if(/[A-Z]/.test(pw))score++;
    if(/[0-9]/.test(pw))score++;
    if(/[^A-Za-z0-9]/.test(pw))score++;
    return score;
  },
  addAddress(id,addr){
    const customers=this.getCustomers();
    const c=customers.find(x=>x.id===id);
    if(!c)return null;
    c.addresses=c.addresses||[];
    const record=Object.assign({id:'ADDR'+Date.now(),label:'Home',line1:'',city:'',state:'',pincode:'',country:'India',isDefaultShipping:false,isDefaultBilling:false},addr);
    if(record.isDefaultShipping)c.addresses.forEach(a=>a.isDefaultShipping=false);
    if(record.isDefaultBilling)c.addresses.forEach(a=>a.isDefaultBilling=false);
    c.addresses.push(record);
    this.saveCustomers(customers);
    window.dispatchEvent(new Event('bb-auth-update'));
    if(typeof NotificationStore!=='undefined')NotificationStore.publish('customer.address_updated',{name:c.name,customerId:c.id});
    return record;
  },
  updateAddress(id,addrId,patch){
    const customers=this.getCustomers();
    const c=customers.find(x=>x.id===id);
    if(!c)return null;
    const a=c.addresses.find(x=>x.id===addrId);
    if(!a)return null;
    if(patch.isDefaultShipping)c.addresses.forEach(x=>x.isDefaultShipping=false);
    if(patch.isDefaultBilling)c.addresses.forEach(x=>x.isDefaultBilling=false);
    Object.assign(a,patch);
    this.saveCustomers(customers);
    window.dispatchEvent(new Event('bb-auth-update'));
    if(typeof NotificationStore!=='undefined')NotificationStore.publish('customer.address_updated',{name:c.name,customerId:c.id});
    return a;
  },
  deleteAddress(id,addrId){
    const customers=this.getCustomers();
    const c=customers.find(x=>x.id===id);
    if(!c)return;
    c.addresses=(c.addresses||[]).filter(a=>a.id!==addrId);
    this.saveCustomers(customers);
    window.dispatchEvent(new Event('bb-auth-update'));
  }
};
function useAuth(){
  const [user,setUser]=React.useState(null);
  React.useEffect(()=>{
    const upd=()=>setUser(BB_AUTH.currentUser());
    upd();
    window.addEventListener('bb-auth-update',upd);
    window.addEventListener('storage',upd);
    return ()=>{window.removeEventListener('bb-auth-update',upd);window.removeEventListener('storage',upd);};
  },[]);
  return user;
}
function Eyebrow({children,style}){return <div style={{fontSize:12,letterSpacing:'var(--tracking-widest)',textTransform:'uppercase',color:'var(--text-muted)',marginBottom:16,...style}}>{children}</div>;}
function H2({children,style,as:Tag='h2'}){return <Tag style={{fontFamily:'var(--font-serif)',fontWeight:400,fontSize:'clamp(26px,3vw,42px)',color:'var(--text-primary)',margin:0,...style}}>{children}</Tag>;}
function Breadcrumbs({trail}){
  return (
    <nav aria-label="Breadcrumb" style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'20px var(--container-pad) 0',fontSize:12,letterSpacing:'var(--tracking-wide)',color:'var(--text-muted)',textTransform:'uppercase'}}>
      {trail.map((t,i)=>(<span key={i}>{i>0&&<span style={{margin:'0 8px'}}>/</span>}{t.href?<a href={t.href} style={{color:'var(--text-muted)'}}>{t.label}</a>:<span style={{color:'var(--text-primary)'}}>{t.label}</span>}</span>))}
    </nav>
  );
}
function ProductTile({p}){
  const [hover,setHover]=React.useState(false);
  const [wished,setWished]=React.useState(false);
  const [stock,setStock]=React.useState(null);
  React.useEffect(()=>{setWished(BB_STORE.isWished(p.id));setStock(stockInfo(p.id));},[]);
  const oos=stock&&stock.status==='out-of-stock';
  const low=stock&&(stock.status==='low-stock'||stock.status==='critical');
  return (
    <div style={{cursor:'pointer'}} onMouseEnter={()=>setHover(true)} onMouseLeave={()=>setHover(false)}>
      <a href={`Product.html?id=${p.id}`} {...productLinkProps()} style={{display:'block'}}>
        <div style={{position:'relative',aspectRatio:'4/5',borderRadius:'var(--radius-lg)',overflow:'hidden',marginBottom:16,boxShadow:'var(--shadow-card)'}}>
          <img src={photo(p.imgs[0])} loading="lazy" alt={p.name} style={{position:'absolute',inset:0,width:'100%',height:'100%',objectFit:'cover',opacity:hover?0:1,filter:oos?'grayscale(0.6)':'none',transition:'opacity 500ms var(--ease-out)'}}/>
          <img src={photo(p.imgs[1])} loading="lazy" alt="" style={{position:'absolute',inset:0,width:'100%',height:'100%',objectFit:'cover',opacity:hover?1:0,filter:oos?'grayscale(0.6)':'none',transition:'opacity 500ms var(--ease-out)'}}/>
          {oos&&<div style={{position:'absolute',top:14,left:14,background:'var(--charcoal)',color:'var(--ivory)',fontSize:10,letterSpacing:'0.06em',textTransform:'uppercase',padding:'5px 12px',borderRadius:'var(--radius-pill)'}}>Out of Stock</div>}
          {!oos&&low&&<div style={{position:'absolute',top:14,left:14,background:'#9A4A3C',color:'#fff',fontSize:10,letterSpacing:'0.06em',textTransform:'uppercase',padding:'5px 12px',borderRadius:'var(--radius-pill)'}}>Only {stock.availableStock} Left</div>}
          <div onClick={e=>{e.preventDefault();e.stopPropagation();BB_STORE.toggleWishlist(p.id);const nowWished=BB_STORE.isWished(p.id);setWished(nowWished);if(nowWished)triggerCollectionToast('Added to My Collection');}} style={{position:'absolute',top:14,right:14,width:34,height:34,borderRadius:'50%',background:'rgba(248,245,240,0.9)',display:'flex',alignItems:'center',justifyContent:'center'}}>
            <i data-lucide="heart" style={{width:15,height:15,color:wished?'var(--gold-deep)':'var(--charcoal)',fill:wished?'var(--gold-deep)':'none'}}></i>
          </div>
        </div>
        <div style={{fontFamily:'var(--font-serif)',fontSize:19,color:oos?'var(--text-muted)':'var(--text-primary)'}}>{p.name}</div>
        <div style={{fontSize:13,color:'var(--text-muted)',marginTop:2}}>{p.sub}</div>
        <div style={{fontSize:15,color:'var(--text-primary)',marginTop:8}}>{money(p.price)}</div>
      </a>
    </div>
  );
}
function QtyStepper({qty,onChange,min=1,max}){
  const atMax=typeof max==='number'&&qty>=max;
  function commit(v){
    v=parseInt(v,10);
    if(isNaN(v))v=min;
    v=Math.max(min,v);
    if(typeof max==='number')v=Math.min(max,v);
    onChange(v);
  }
  return (
    <div style={{display:'inline-flex',alignItems:'center',border:'1px solid var(--border-default)',borderRadius:'var(--radius-md)'}}>
      <button aria-label="Decrease quantity" onClick={()=>commit(qty-1)} disabled={qty<=min} style={{width:38,height:38,border:'none',background:'none',cursor:qty<=min?'default':'pointer',fontSize:16,color:qty<=min?'var(--text-muted)':'var(--text-primary)'}}>−</button>
      <input aria-label="Quantity" value={qty} inputMode="numeric" onChange={e=>{const v=e.target.value.replace(/[^0-9]/g,'');commit(v===''?min:v);}} style={{width:32,textAlign:'center',fontSize:14,border:'none',background:'none',color:'var(--text-primary)',fontFamily:'inherit'}}/>
      <button aria-label="Increase quantity" onClick={()=>commit(qty+1)} disabled={atMax} style={{width:38,height:38,border:'none',background:'none',cursor:atMax?'default':'pointer',fontSize:16,color:atMax?'var(--text-muted)':'var(--text-primary)'}}>+</button>
    </div>
  );
}
function PrimaryButton({children,onClick,style,type='button',disabled}){
  return <button type={type} onClick={onClick} disabled={disabled} style={{background:'var(--charcoal)',color:'var(--ivory)',border:'none',borderRadius:'var(--radius-md)',padding:'16px 32px',fontSize:13,letterSpacing:'var(--tracking-wide)',textTransform:'uppercase',cursor:disabled?'default':'pointer',opacity:disabled?0.5:1,...style}}>{children}</button>;
}
function StaticPage({eyebrow,title,lede,heroImg,sections=[],breadcrumb}){
  return (
    <div>
      <Breadcrumbs trail={breadcrumb||[{label:'Home',href:'index.html'},{label:title}]}/>
      {heroImg!=null&&<div style={{maxWidth:'var(--container-max)',margin:'32px auto 0',padding:'0 var(--container-pad)'}}><div style={{aspectRatio:'21/9',borderRadius:'var(--radius-lg)',overflow:'hidden'}}><img src={photo(heroImg,1800)} alt={title} style={{width:'100%',height:'100%',objectFit:'cover'}}/></div></div>}
      <div style={{maxWidth:760,margin:'0 auto',padding:'var(--space-7) var(--container-pad)',textAlign:'center'}}>
        {eyebrow&&<Eyebrow style={{justifyContent:'center'}}>{eyebrow}</Eyebrow>}
        <h1 style={{fontFamily:'var(--font-serif)',fontWeight:400,fontSize:'clamp(30px,4vw,46px)',margin:'0 0 20px',color:'var(--text-primary)'}}>{title}</h1>
        {lede&&<p style={{fontSize:18,lineHeight:1.8,color:'var(--text-secondary)'}}>{lede}</p>}
      </div>
      <div style={{maxWidth:760,margin:'0 auto',padding:'0 var(--container-pad) var(--space-section)'}}>
        {sections.map((s,i)=>(
          <div key={i} style={{marginBottom:40}}>
            {s.heading&&<H2 style={{fontSize:22,marginBottom:14}}>{s.heading}</H2>}
            {(Array.isArray(s.body)?s.body:[s.body]).map((p,j)=>(<p key={j} style={{fontSize:16,lineHeight:1.85,color:'var(--text-secondary)',margin:'0 0 14px'}}>{p}</p>))}
          </div>
        ))}
      </div>
    </div>
  );
}
function FaqAccordion({q,a}){
  const [open,setOpen]=React.useState(false);
  return (
    <div style={{borderBottom:'1px solid var(--border-soft)'}}>
      <button onClick={()=>setOpen(!open)} style={{width:'100%',textAlign:'left',display:'flex',justifyContent:'space-between',alignItems:'center',padding:'20px 0',background:'none',border:'none',cursor:'pointer',fontFamily:'var(--font-serif)',fontSize:18,color:'var(--text-primary)'}}>
        {q}<i data-lucide={open?'minus':'plus'} style={{width:16,height:16,flexShrink:0,marginLeft:16}}></i>
      </button>
      {open&&<p style={{fontSize:15,lineHeight:1.8,color:'var(--text-secondary)',paddingBottom:20,margin:0}}>{a}</p>}
    </div>
  );
}
function LegalPage({title,desc,dateLabel,dateValue,sections,schemaType}){
  const [active,setActive]=React.useState(sections[0].id);
  React.useEffect(()=>{
    document.title=`${title} \u2014 Bold Bee`;
    const schema={"@context":"https://schema.org","@graph":[
      {"@type":"BreadcrumbList",itemListElement:[{"@type":"ListItem",position:1,name:"Home",item:"index.html"},{"@type":"ListItem",position:2,name:title}]},
      {"@type":schemaType,name:title,description:desc,dateModified:dateValue}
    ]};
    let el=document.getElementById('bb-schema');
    if(!el){el=document.createElement('script');el.type='application/ld+json';el.id='bb-schema';document.head.appendChild(el);}
    el.textContent=JSON.stringify(schema);
    const obs=new IntersectionObserver(entries=>{
      entries.forEach(en=>{if(en.isIntersecting)setActive(en.target.id);});
    },{rootMargin:'-20% 0px -70% 0px'});
    sections.forEach(s=>{const el2=document.getElementById(s.id);if(el2)obs.observe(el2);});
    return ()=>obs.disconnect();
  },[]);
  return (
    <div>
      <Breadcrumbs trail={[{label:'Home',href:'index.html'},{label:title}]}/>
      <div style={{maxWidth:760,margin:'0 auto',padding:'var(--space-7) var(--container-pad) 0',textAlign:'center'}}>
        <Eyebrow style={{justifyContent:'center'}}>{dateLabel} {dateValue}</Eyebrow>
        <h1 style={{fontFamily:'var(--font-serif)',fontWeight:400,fontSize:'clamp(30px,4vw,46px)',margin:0,color:'var(--text-primary)'}}>{title}</h1>
      </div>
      <div style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'var(--space-7) var(--container-pad) var(--space-section)',display:'grid',gridTemplateColumns:'260px 1fr',gap:64,alignItems:'start'}}>
        <nav aria-label={`${title} sections`} style={{position:'sticky',top:110,display:'flex',flexDirection:'column',gap:4}}>
          {sections.map(s=>(
            <a key={s.id} href={`#${s.id}`} style={{fontSize:13,padding:'8px 0',color:active===s.id?'var(--text-primary)':'var(--text-muted)',borderLeft:'2px solid '+(active===s.id?'var(--gold-deep)':'transparent'),paddingLeft:14,textDecoration:'none'}}>{s.heading}</a>
          ))}
        </nav>
        <div style={{maxWidth:680}}>
          {sections.map((s,i)=>(
            <div key={s.id} id={s.id} style={{marginBottom:44,scrollMarginTop:110}}>
              <H2 style={{fontSize:22,marginBottom:14}}>{s.heading}</H2>
              {(Array.isArray(s.body)?s.body:[s.body]).map((p,j)=>(<p key={j} style={{fontSize:16,lineHeight:1.85,color:'var(--text-secondary)',margin:'0 0 14px'}}>{p}</p>))}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
function PublicationBanner({destination}){
  const pub=window.BBExperience?(window.BBExperience.publishedPublications(destination)[0]||null):null;
  if(!pub)return null;
  return (
    <div style={{maxWidth:'var(--container-max)',margin:'0 auto',padding:'0 var(--container-pad) var(--space-section)'}}>
      <a href={`Publication.html?id=${pub.id}`} style={{textDecoration:'none',display:'grid',gridTemplateColumns:'1.1fr 1fr',gap:32,alignItems:'center',background:'var(--beige)',borderRadius:'var(--radius-lg)',overflow:'hidden'}}>
        <div style={{padding:'var(--space-7)'}}>
          <Eyebrow>{pub.contentType||'Featured'}</Eyebrow>
          <H2 style={{marginBottom:14}}>{pub.title}</H2>
          {pub.shortDescription&&<p style={{fontSize:14,lineHeight:1.8,color:'var(--text-secondary)',marginBottom:16,maxWidth:420}}>{pub.shortDescription}</p>}
          <span style={{fontSize:13,letterSpacing:'var(--tracking-wide)',textTransform:'uppercase',color:'var(--gold-deep)',borderBottom:'1px solid var(--gold-deep)',paddingBottom:2}}>Read More</span>
        </div>
        <div style={{aspectRatio:'4/3'}}><img src={photo(pub.heroImg||3,1200)} style={{width:'100%',height:'100%',objectFit:'cover'}} alt={pub.title}/></div>
      </a>
    </div>
  );
}
function FieldMsg({touched,valid,value,okMsg,errMsg}){
  if(!touched||!value)return null;
  return valid?(okMsg?<p style={{color:'#3D6B4A',fontSize:12,margin:'4px 0 0'}}>{okMsg}</p>:null):(<p style={{color:'#B3261E',fontSize:12,margin:'4px 0 0'}}>{errMsg}</p>);
}
function fieldBorder(touched,value,valid){return touched&&value?(valid?'1px solid #3D6B4A':'1px solid #B3261E'):'1px solid var(--border-default)';}
// Type-to-search City combobox over LocationMaster.citiesFor(state) — only a listed city can be
// committed (free text is rejected on blur), keeping City always valid for the selected State.
function CitySearchSelect({state,value,onChange,onBlur,disabled,style}){
  const [open,setOpen]=React.useState(false);
  const [query,setQuery]=React.useState(value||'');
  const boxRef=React.useRef(null);
  React.useEffect(()=>{setQuery(value||'');},[value]);
  React.useEffect(()=>{
    function onDocClick(e){ if(boxRef.current&&!boxRef.current.contains(e.target))setOpen(false); }
    document.addEventListener('mousedown',onDocClick);
    return ()=>document.removeEventListener('mousedown',onDocClick);
  },[]);
  const results=(typeof LocationMaster!=='undefined'?LocationMaster.searchCities(state,query):[]).slice(0,50);
  function commit(city){ onChange(city); setQuery(city); setOpen(false); }
  function handleBlur(){
    setTimeout(()=>{
      if(typeof LocationMaster!=='undefined'&&!LocationMaster.isValidCombo(state,query)){ setQuery(value||''); }
      setOpen(false);
      onBlur&&onBlur();
    },120);
  }
  return (
    <div ref={boxRef} style={{position:'relative',...style}}>
      <input disabled={disabled} placeholder={disabled?'Select a state first':'Type to search city\u2026'} value={query} onChange={e=>{setQuery(e.target.value);onChange('');setOpen(true);}} onFocus={()=>setOpen(true)} onBlur={handleBlur} style={{width:'100%',padding:'10px 12px',border:'1px solid var(--border-default)',borderRadius:'var(--radius-md)',fontSize:13,background:disabled?'var(--bg-muted)':'var(--white)'}}/>
      {open&&!disabled&&results.length>0&&(
        <div style={{position:'absolute',zIndex:20,top:'100%',left:0,right:0,marginTop:4,background:'var(--white)',border:'1px solid var(--border-default)',borderRadius:'var(--radius-md)',maxHeight:220,overflowY:'auto',boxShadow:'var(--shadow-card)'}}>
          {results.map(c=>(<div key={c} onMouseDown={()=>commit(c)} style={{padding:'9px 14px',fontSize:13,cursor:'pointer'}} onMouseEnter={e=>e.currentTarget.style.background='var(--beige)'} onMouseLeave={e=>e.currentTarget.style.background='none'}>{c}</div>))}
        </div>
      )}
      {open&&!disabled&&query&&results.length===0&&(
        <div style={{position:'absolute',zIndex:20,top:'100%',left:0,right:0,marginTop:4,background:'var(--white)',border:'1px solid var(--border-default)',borderRadius:'var(--radius-md)',padding:'9px 14px',fontSize:12.5,color:'var(--text-muted)'}}>No matching city in this state.</div>
      )}
    </div>
  );
}
Object.assign(window,{photo,money,COLLECTIONS,PRODUCTS,productBySlug,stockInfo,availabilityLabel,triggerCollectionToast,CollectionToast,productLinkProps,PublicationBanner,BB_STORE,BB_AUTH,BB_OAUTH_CONFIG,useCartCount,useAuth,Eyebrow,H2,Breadcrumbs,ProductTile,QtyStepper,PrimaryButton,StaticPage,FaqAccordion,LegalPage,FieldMsg,fieldBorder,CitySearchSelect});
