const products = [
  {id:'silence', title:'SILENCE', collection:'Chapter I', price:89, image:'assets/silence-core.png', colors:['Earth Ash','Obsidian Black','Shadow Charcoal','Stone Grey'], line:'Greatness begins where applause ends.', story:'SILENCE is a reminder that real confidence does not ask to be noticed. The work happens privately. The result speaks when it is ready.'},
  {id:'memento', title:'MEMENTO MORI', collection:'Chapter II', price:89, image:'assets/memento-colors.png', colors:['Ash Brown','Stone Grey','Vintage Black','Charcoal'], line:'Time never waits. Neither should you.', story:'MEMENTO MORI turns mortality into urgency. Every hour is borrowed. Spend it building something that will remain.'},
  {id:'ascent', title:'ASCENT', collection:'Chapter III', price:89, image:'assets/ascent.png', colors:['Vintage Black','Stone Grey','Earth Brown'], line:'Every summit asks for sacrifice.', story:'ASCENT is for the ones who keep climbing without applause. Growth is earned one quiet step at a time.'},
  {id:'legacy', title:'LEGACY', collection:'Chapter IV', price:89, image:'assets/legacy.png', colors:['Earth Ash','Vintage Black','Stone Grey'], line:'When words disappear, actions continue speaking.', story:'LEGACY is not what you say. It is what remains after you are gone.'}
];

let cart = JSON.parse(localStorage.getItem('en_cart') || '[]');
let activeProduct = products[0];
const $ = (s)=>document.querySelector(s);
const $$ = (s)=>document.querySelectorAll(s);

window.addEventListener('load',()=> setTimeout(()=>$('#loader').classList.add('hide'), 650));

const cursor = $('#cursor');
if(cursor){
  window.addEventListener('mousemove', e=>{ cursor.style.left=e.clientX+'px'; cursor.style.top=e.clientY+'px'; });
  document.addEventListener('mouseover', e=>{ if(e.target.closest('a,button,.product-card,.chapter-line,input,select')) cursor.classList.add('active'); });
  document.addEventListener('mouseout', e=>{ if(e.target.closest('a,button,.product-card,.chapter-line,input,select')) cursor.classList.remove('active'); });
}

const grid = $('#productGrid');
products.forEach(p=>{
  const el=document.createElement('article');
  el.className='product-card reveal';
  el.innerHTML=`<img src="${p.image}" alt="${p.title} product mockup" loading="lazy"><div class="product-info"><h3>${p.title}</h3><p>${p.line}</p><div class="product-meta"><span>${p.colors.length} colors</span><strong>CA$${p.price}</strong></div></div>`;
  el.addEventListener('click',()=>openProduct(p.id));
  grid.appendChild(el);
});

document.querySelectorAll('[data-open]').forEach(el=>{
  el.addEventListener('click', e=>{ e.preventDefault(); openProduct(el.dataset.open); });
});

function openProduct(id){
  activeProduct = products.find(p=>p.id===id) || products[0];
  $('#modalImg').src=activeProduct.image;
  $('#modalCollection').textContent=activeProduct.collection;
  $('#modalTitle').textContent=activeProduct.title;
  $('#modalStory').textContent=activeProduct.story;
  $('#modalPrice').textContent=`CA$${activeProduct.price}`;
  $('#colorSelect').innerHTML=activeProduct.colors.map(c=>`<option>${c}</option>`).join('');
  $('#productModal').classList.add('open');
  $('#productModal').setAttribute('aria-hidden','false');
}
function closeProduct(){ $('#productModal').classList.remove('open'); $('#productModal').setAttribute('aria-hidden','true'); }
$('#closeModal').addEventListener('click',closeProduct);
$('#productModal').addEventListener('click',e=>{ if(e.target.id==='productModal') closeProduct(); });

function addToCart(){
  const color=$('#colorSelect').value;
  const size=$('#sizeSelect').value;
  const item={...activeProduct, color, size, qty:1, key:activeProduct.id+color+size+Date.now()};
  cart.push(item); saveCart(); renderCart(); closeProduct(); openCart();
}
$('#addToCartBtn').addEventListener('click',addToCart);

function saveCart(){ localStorage.setItem('en_cart', JSON.stringify(cart)); }
function renderCart(){
  $('#cartCount').textContent=cart.length;
  const wrap=$('#cartItems');
  if(!cart.length){ wrap.innerHTML='<p class="empty">Your cart is empty.</p>'; }
  else{
    wrap.innerHTML=cart.map((i,idx)=>`<div class="cart-item"><img src="${i.image}" alt="${i.title}"><div><strong>${i.title}</strong><br><small>${i.color} / ${i.size}</small><br><small>CA$${i.price}</small></div><button class="icon-btn" onclick="removeCart(${idx})">×</button></div>`).join('');
  }
  const total=cart.reduce((s,i)=>s+i.price*i.qty,0);
  $('#cartSubtotal').textContent=`CA$${total}`;
}
window.removeCart=(idx)=>{cart.splice(idx,1);saveCart();renderCart();}
function openCart(){ $('#cartDrawer').classList.add('open'); $('#cartDrawer').setAttribute('aria-hidden','false'); }
function closeCart(){ $('#cartDrawer').classList.remove('open'); $('#cartDrawer').setAttribute('aria-hidden','true'); }
$('#cartBtn').addEventListener('click',openCart); $('#closeCart').addEventListener('click',closeCart);
$('#checkoutBtn').addEventListener('click',()=>alert('Demo checkout. For launch, connect Shopify/Stripe, Apple Pay, Google Pay, taxes, shipping and inventory.'));
renderCart();

$('#waitlistForm').addEventListener('submit', async e=>{
  e.preventDefault();
  const email=e.target.querySelector('input').value;
  localStorage.setItem('en_waitlist', email);
  $('#waitlistMsg').textContent='You are on the private launch list.';
  e.target.reset();
  // If hosted on PHP server, api/waitlist.php will also save the email. Static preview still works through localStorage.
});

$('#menuBtn').addEventListener('click',()=>$('#nav').classList.toggle('open'));
$$('#nav a').forEach(a=>a.addEventListener('click',()=>$('#nav').classList.remove('open')));

$('#searchBtn').addEventListener('click',()=>{$('#searchOverlay').classList.add('open'); setTimeout(()=>$('#searchInput').focus(),100); renderSearch('');});
$('#closeSearch').addEventListener('click',()=>$('#searchOverlay').classList.remove('open'));
$('#searchInput').addEventListener('input',e=>renderSearch(e.target.value));
function renderSearch(q){
  q=q.toLowerCase();
  const result=products.filter(p=>(p.title+p.story+p.line+p.colors.join(' ')).toLowerCase().includes(q));
  $('#searchResults').innerHTML=result.map(p=>`<div class="search-result" data-id="${p.id}"><strong>${p.title}</strong><br><small>${p.line}</small></div>`).join('');
  $$('#searchResults .search-result').forEach(r=>r.addEventListener('click',()=>{$('#searchOverlay').classList.remove('open'); openProduct(r.dataset.id);}));
}

const io=new IntersectionObserver(entries=>entries.forEach(en=>{if(en.isIntersecting) en.target.classList.add('show')}),{threshold:.12});
$$('.reveal').forEach(el=>io.observe(el));

let last=0; window.addEventListener('scroll',()=>{const y=scrollY; $('#header').style.transform=y>last&&y>140?'translateY(-100%)':'translateY(0)'; last=y;});
