// Main JS: product data, cart logic, and WhatsApp checkout
(function(){
  // Business WhatsApp number (Kenya) - change as needed
  const businessNumber = '254769928876';

  // Sample product list — update image filenames to match Product_Images folder
  const products = [
    {id:1, name: '2.4m Quarter round PVC', price:750, unit:'per piece', stock:'In stock', imagePath:'Product_Images/2.4m Quarter round PVC Ksh. 750.jpeg', category:'Skirting & Accessories'},
    {id:2, name: '2m PVC skirtings', price:850, unit:'per 2m length', stock:'In stock', imagePath:'Product_Images/2m PVC skirtings Ksh. 850.jpeg', category:'Skirting & Accessories'},
    {id:3, name: 'Angle line (2mtrs)', price:1500, unit:'per 2m', stock:'In stock', imagePath:'Product_Images/Angle line 1500 2mtrs long.jpg', category:'Accessories'},
    {id:4, name: 'Bamboo natural', price:6800, unit:'per piece', stock:'Limited', imagePath:'Product_Images/Bamboo natural 6800.jpg', category:'Flooring'},
    {id:5, name: 'Bamboo Natural (alt)', price:6800, unit:'per piece', stock:'Limited', imagePath:'Product_Images/Bamboo Natural.jpg', category:'Flooring'},
    {id:6, name: 'Wall to Wall Carpet', price:0, unit:'- ', stock:'In Stock', imagePath:'Product_Images/Door Matt.jpg', category:'Accessories'},
    {id:7, name: 'Doorstrip (2.7m)', price:1500, unit:'per 2.7m', stock:'In stock', imagePath:'Product_Images/Doorstrip 1500 2.7mtrs long.jpg', category:'Accessories'},
    {id:8, name: 'Grass carpet (various)', price:1300, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Grass carpet from 1300-3500 per square meter.jpg', category:'Flooring'},
    {id:9, name: 'Grass carpet (roll)', price:1500, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Grass carpet.jpg', category:'Flooring'},
    {id:10, name: 'Herringbone SPC 5mm', price:2300, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Herringbone SPC 5mm 2300.jpg', category:'SPC Flooring'},
    {id:11, name: 'Laminate flooring 8mm', price:1900, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Laminate flooring 8mm 1900 per square meter.jpg', category:'Laminated Flooring'},
    {id:12, name: 'Laminate Oak', price:1990, unit:'per m²', stock:'In stock', imagePath:'Product_Images/laminate_oak.svg', category:'Laminated Flooring'},
    {id:13, name: 'Laminate Walnut', price:2490, unit:'per m²', stock:'In stock', imagePath:'Product_Images/laminate_walnut.svg', category:'Laminated Flooring'},
    {id:14, name: 'LVT Dryback', price:1200, unit:'per m²', stock:'In stock', imagePath:'Product_Images/LVT Dryback 1200= per square meter.jpeg', category:'Vinyl Flooring'},
    {id:15, name: 'MDF skirtings', price:850, unit:'per 2.4m', stock:'In stock', imagePath:'Product_Images/MDF skirtings 850= 2.4mtrs long.jpeg', category:'Skirting & Accessories'},
    {id:16, name: 'PVC carpet', price:1200, unit:'per m²', stock:'In stock', imagePath:'Product_Images/PVC carpet 1200 per square meter.jpg', category:'Flooring'},
    {id:17, name: 'PVC carpet', price:1500, unit:'per m²', stock:'In stock', imagePath:'Product_Images/PVC carpet 1500 per square meter.jpg', category:'Flooring'},
    {id:18, name: 'Quarter round', price:0, unit:'per piece', stock:'Contact', imagePath:'Product_Images/Quarter round.jpg', category:'Skirting & Accessories'},
    {id:19, name: 'Quarter round (alt)', price:0, unit:'per piece', stock:'Contact', imagePath:'Product_Images/Quarter round1.jpg', category:'Skirting & Accessories'},
    {id:20, name: 'Rubber nose (2m)', price:1500, unit:'per 2m', stock:'In stock', imagePath:'Product_Images/Rubber nose 1500 2mtrs long.jpg', category:'Accessories'},
    {id:21, name: 'Rubber nose ()', price:1500, unit:'per 2m', stock:'In stock', imagePath:'Product_Images/Rubber nose 1500= 2mtrs long.jpeg', category:'Accessories'},
    {id:22, name: 'SPC', price:2000, unit:'per m²', stock:'In stock', imagePath:'Product_Images/SPC 2000= per square meter.jpeg', category:'SPC Flooring'},
    {id:23, name: 'SPC 5mm', price:2100, unit:'per m²', stock:'In stock', imagePath:'Product_Images/sqm SPC 5mm Ksh. 2100.jpeg', category:'SPC Flooring'},
    {id:24, name: 'Underlay 1mm / 2mm', price:150, unit:'per meter', stock:'In stock', imagePath:'Product_Images/Underlay 1mm 150 per meter 2mm 250 per meter.jpeg', category:'Accessories'},
    {id:25, name: 'Vinyl Grey', price:1590, unit:'per m²', stock:'In stock', imagePath:'Product_Images/vinyl_grey.svg', category:'Vinyl Flooring'},
    {id:26, name: 'Vinyl White', price:1390, unit:'per m²', stock:'In stock', imagePath:'Product_Images/vinyl_white.svg', category:'Vinyl Flooring'},
    {id:27, name: 'Wall to wall Delta', price:0, unit:'-', stock:'Contact', imagePath:'Product_Images/Wall to wall Delta.jpeg', category:'Wall Panels'},
    {id:28, name: 'Decorative Wall Panel', price:2990, unit:'per panel', stock:'In stock', imagePath:'Product_Images/wall_decor.svg', category:'Wall Panels'},
    {id:29, name: 'Wood Wall Panel', price:3490, unit:'per panel', stock:'In stock', imagePath:'Product_Images/wall_wood.svg', category:'Wall Panels'},
    {id:30, name: 'Installation Kit', price:500, unit:'per kit', stock:'In stock', imagePath:'Product_Images/kit.svg', category:'Accessories'},
    {id:31, name: 'Outdoor Dacking panels', price:2700, unit:'per pcs', stock:'In stock', imagePath:'Product_Images/Outdoor Dacking panels at 2700 per pcs.jpeg', category:'Outdoor', featured:true},
    {id:32, name: 'Lvt flooring', price:1300, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Lvt flooring at 1300 per square meters.jpeg', category:'Vinyl Flooring'},
    {id:33, name: 'SPC 4mm', price:1900, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Available thickness 4mm 1900 per sqm  then between 5mm 1900 and 2300 per sqm.jpeg', category:'SPC Flooring'},
    {id:34, name: 'SPC 5mm', price:1900, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Available thickness 4mm 1900 per sqm  then between 5mm 1900 and 2300 per sqm.jpeg', category:'SPC Flooring'},
    {id:35, name: 'SPC floor 5mm', price:2300, unit:'per m²', stock:'In stock', imagePath:'Product_Images/Herringbone SPC 5mm 2300.jpg', category:'SPC Flooring', featured:true},
    {id:36, name: 'Pu stone', price:2500, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Pu stone.jpeg', category:'SPC Flooring'},
    {id:37, name: 'Pu cornice', price:550, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Pu cornice.jpeg', category:'SPC Flooring'},
    {id:38, name: 'PS-1601101', price:1000-1500, unit:'per piece', stock:'In stock', imagePath:'Product_Images/PS-1601101.jpeg', category:'SPC Flooring'},
    {id:39, name: 'PS 1501103 160mm by 2900mm', price:1000-1500, unit:'per piece', stock:'In stock', imagePath:'Product_Images/PS 1501103 160mm by 2900mm.jpeg', category:'SPC Flooring'},
    {id:40, name: 'PS91601201', price:1000-1500, unit:'per piece', stock:'In stock', imagePath:'Product_Images/PS91601201.jpeg', category:'SPC Flooring'},
    {id:41, name: 'PS1501102 160mm by 2900mm', price:1000-1500, unit:'per piece', stock:'In stock', imagePath:'Product_Images/PS1501102 160mm by 2900mm.jpeg', category:'SPC Flooring'},
    {id:42, name: 'PHM03 size 170mm by 2950mm', price:1000-1500, unit:'per piece', stock:'In stock', imagePath:'Product_Images/PHM03 size 170mm by 2950mm.jpeg', category:'SPC Flooring'},
    {id:43, name: 'Flutted panels', price:1000-1500, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Flutted panels.jpeg', category:'SPC Flooring'},
    {id:44, name: 'Wallpapers', price:1200, unit:'per piece', stock:'In stock', imagePath:'Wallpapers.jpeg', category:'SPC Flooring'},
    {id:45, name: 'Pu wainscoting 1 inch ', price:350, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Pu wainscoting.jpeg', category:'SPC Flooring'},
    {id:46, name: 'Pu wainscoting 1.5 inch ', price:450, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Pu wainscoting.jpeg', category:'SPC Flooring'},
    {id:47, name: 'Pu wainscoting 2 inch ', price:530, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Pu wainscoting.jpeg', category:'SPC Flooring'},
    {id:48, name: 'Pu wainscoting 2.5 inch ', price:600, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Pu wainscoting.jpeg', category:'SPC Flooring'},
    {id:49, name: 'Pu wainscoting 3 inch ', price:730, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Pu wainscoting.jpeg', category:'SPC Flooring'},
    {id:50, name: 'Malpha hinges', price:140, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Malpha hinges.jpeg', category:'SPC Flooring'},
    {id:51, name: 'Drawer Slides 18 inch', price:450, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Drawer Slides.jpeg', category:'SPC Flooring'},
    {id:52, name: 'Drawer Slides 16 inch', price:380, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Drawer Slides.jpeg', category:'SPC Flooring'},
    {id:53, name: 'Drawer Slides 14 inch', price:350, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Drawer Slides.jpeg', category:'SPC Flooring'},
    {id:54, name: 'Drawer Slides 12 inch', price:320, unit:'per piece', stock:'In stock', imagePath:'Product_Images/Drawer Slides.jpeg', category:'SPC Flooring'},






  ];

  // palette variants for card accents
  const variants = ['variant-a','variant-b','variant-c','variant-d','variant-e','variant-f'];

  /* Cart helpers */
  function getCart(){
    try{return JSON.parse(localStorage.getItem('fl_cart')||'[]')}catch(e){return []}
  }
  function saveCart(cart){localStorage.setItem('fl_cart',JSON.stringify(cart));renderCartCount();}
  function addToCart(id){
    const cart=getCart();
    const item=cart.find(i=>i.id===id);
    if(item){item.qty++}else{const p=products.find(x=>x.id===id);cart.push({id:p.id,name:p.name,price:p.price,imagePath:p.imagePath,unit:p.unit,stock:p.stock,qty:1})}
    saveCart(cart);
    showToast('Added to cart: ' + (products.find(p=>p.id===id)||{}).name);
    // if checkout panel is open and showing order cart, refresh it
    const panel = document.querySelector('.checkout-panel');
    if(panel && panel.dataset && panel.dataset.mode === 'order'){
      populatePanel('order');
    }
  }
  /* Quote cart helpers (separate from checkout cart) */
  function getQuoteCart(){
    try{return JSON.parse(localStorage.getItem('fl_quote')||'[]')}catch(e){return []}
  }
  function saveQuoteCart(cart){localStorage.setItem('fl_quote',JSON.stringify(cart));renderQuoteCount();}
  function addToQuote(id){
    const cart=getQuoteCart();
    const item=cart.find(i=>i.id===id);
    if(item){item.qty++}else{const p=products.find(x=>x.id===id);cart.push({id:p.id,name:p.name,price:p.price,imagePath:p.imagePath,unit:p.unit,stock:p.stock,qty:1})}
    saveQuoteCart(cart);
    showToast('Added to quote list: ' + (products.find(p=>p.id===id)||{}).name);
    // if quote panel open, refresh it live
    const panel = document.querySelector('.checkout-panel');
    if(panel && panel.dataset && panel.dataset.mode === 'quote'){
      populatePanel('quote');
    }
  }
  function removeFromQuote(id){const cart=getQuoteCart().filter(i=>i.id!==id);saveQuoteCart(cart);}
  function updateQuoteQty(id,qty){const cart=getQuoteCart();const it=cart.find(i=>i.id===id); if(it){it.qty=qty>0?qty:1; saveQuoteCart(cart);} }
  function quoteTotal(){return getQuoteCart().reduce((s,i)=>s + (i.price*i.qty),0)}
  function renderQuoteCount(){
    const count = getQuoteCart().reduce((s,i)=>s+i.qty,0);
    // update any quote count displays (id or class)
    document.querySelectorAll('#quote-count, .q-count').forEach(el=>el.textContent = count);
  }
  function removeFromCart(id){const cart=getCart().filter(i=>i.id!==id);saveCart(cart);renderCartPage();}
  function updateQty(id,qty){const cart=getCart();const it=cart.find(i=>i.id===id); if(it){it.qty=qty>0?qty:1; saveCart(cart);} renderCartPage();}

  function cartTotal(){return getCart().reduce((s,i)=>s + (i.price*i.qty),0)}

  function renderCartCount(){
    const count = getCart().reduce((s,i)=>s+i.qty,0);
    document.querySelectorAll('#cart-count').forEach(el=>el.textContent = count);
    // update floating cart badge if present
    const badge = document.querySelector('#cart-float .cart-badge');
    if(badge) badge.textContent = count;
  }

  /* Toast helper */
  function showToast(msg,timeout=2800){
    let t = document.getElementById('toast');
    if(!t){ t = document.createElement('div'); t.id='toast'; t.className='toast'; document.body.appendChild(t); }
    t.textContent = msg;
    t.classList.add('show');
    setTimeout(()=>{ t.classList.remove('show') }, timeout);
  }

  /* Render pages */
  function renderProductsGrid(){
    const grid = document.getElementById('products-grid');
    if(!grid) return;
    grid.innerHTML = '';
    products.forEach(p=>{
      const card = document.createElement('article');card.className='product-card ' + variants[p.id % variants.length];
      const imgSrc = encodeURI(p.imagePath);
      card.innerHTML = `
        <div class="product-media"><img src="${imgSrc}" alt="${p.name}"></div>
        <div class="product-info">
          <h4>${p.name}</h4>
          <div class="price-row"><div class="price">KES ${p.price? p.price.toLocaleString() : 'Contact'}</div><div class="unit">${p.unit||''}</div></div>
          <div class="product-features">✔ Water resistant &nbsp; ✔ Easy to install &nbsp; ✔ Durable finish</div>
          <div style="margin-top:8px;color:var(--muted);font-size:.95rem">${p.stock? `<span class=\"badge-stock\">${p.stock}</span>`: ''}</div>
        </div>
        <div class="product-actions">
          <button class="btn" data-id="${p.id}">Add to Cart</button>
          <button class="btn-outline quote" data-id="${p.id}">Get Quote</button>
        </div>`;
      grid.appendChild(card);
    });
    grid.querySelectorAll('.product-actions .btn').forEach(b=>b.addEventListener('click',e=>addToCart(Number(e.currentTarget.dataset.id))));
    // wire quote buttons to open a simplified quote panel (no payment fields)
    grid.querySelectorAll('.product-actions .quote').forEach(b=>b.addEventListener('click',e=>{
      const id = Number(e.currentTarget.dataset.id);
      // add item to the separate quote cart and open the quote panel for review
      addToQuote(id);
      openCheckoutPanel('quote');
    }));
  }

  /* Product page: live search, category filter, price-range and price sort */
  const productFilters = { search: '', category: '', sort: '', minPrice: null, maxPrice: null };

  function debounce(fn, wait=250){ let t; return function(...args){ clearTimeout(t); t = setTimeout(()=> fn.apply(this,args), wait); } }

  function renderProductsGridFiltered(){
    const grid = document.getElementById('products-grid');
    if(!grid) return;
    grid.innerHTML = '';
    let list = products.slice();
    // category filter
    if(productFilters.category){ list = list.filter(p=> (p.category||'').toLowerCase() === productFilters.category.toLowerCase()); }
    // search filter
    if(productFilters.search){ const q = productFilters.search.toLowerCase(); list = list.filter(p=> p.name.toLowerCase().includes(q) || (p.category||'').toLowerCase().includes(q)); }
    // sort
    if(productFilters.sort === 'price-asc'){ list.sort((a,b)=> (a.price||9999999) - (b.price||9999999)); }
    if(productFilters.sort === 'price-desc'){ list.sort((a,b)=> (b.price||0) - (a.price||0)); }
    // price range filter
    if(typeof productFilters.minPrice === 'number'){ list = list.filter(p=> (p.price||0) >= productFilters.minPrice); }
    if(typeof productFilters.maxPrice === 'number'){ list = list.filter(p=> (p.price||0) <= productFilters.maxPrice); }

    if(list.length===0){ grid.innerHTML = '<p>No products found.</p>'; return }

    list.forEach(p=>{
      const card = document.createElement('article');card.className='product-card ' + variants[p.id % variants.length];
      const imgSrc = encodeURI(p.imagePath);
      card.innerHTML = `
        <div class="product-media"><img src="${imgSrc}" alt="${p.name}"></div>
        <div class="product-info">
          <h4>${p.name}</h4>
          <div class="price-row"><div class="price">KES ${p.price? p.price.toLocaleString() : 'Contact'}</div><div class="unit">${p.unit||''}</div></div>
          <div class="product-features">✔ Water resistant &nbsp; ✔ Easy to install &nbsp; ✔ Durable finish</div>
          <div style="margin-top:8px;color:var(--muted);font-size:.95rem">${p.stock? `<span class=\"badge-stock\">${p.stock}</span>`: ''}</div>
        </div>
        <div class="product-actions">
          <button class="btn" data-id="${p.id}">Add to Cart</button>
          <button class="btn-outline quote" data-id="${p.id}">Get Quote</button>
        </div>`;
      grid.appendChild(card);
    });
    // wire buttons
    grid.querySelectorAll('.product-actions .btn').forEach(b=>b.addEventListener('click',e=>addToCart(Number(e.currentTarget.dataset.id))));
    grid.querySelectorAll('.product-actions .quote').forEach(b=>b.addEventListener('click',e=>{ const id = Number(e.currentTarget.dataset.id); addToQuote(id); openCheckoutPanel('quote'); }));
  }

  function wireProductsControls(){
    const search = document.getElementById('product-search');
    const spinner = document.getElementById('search-spinner');
    const sort = document.getElementById('product-sort');
    const cats = document.querySelectorAll('.category-btn');
    if(search){
      const doSearch = debounce(()=>{ productFilters.search = search.value.trim(); renderProductsGridFiltered(); if(spinner) spinner.classList.remove('active'); }, 280);
      search.addEventListener('input', (e)=>{ if(spinner) spinner.classList.add('active'); doSearch(); });
      search.addEventListener('blur', ()=>{ if(spinner) setTimeout(()=>spinner.classList.remove('active'), 300); });
    }
    if(sort){ sort.addEventListener('change', ()=>{ productFilters.sort = sort.value; renderProductsGridFiltered(); }); }
    if(cats && cats.length){ cats.forEach(b=> b.addEventListener('click', (e)=>{ cats.forEach(x=>x.classList.remove('active')); e.currentTarget.classList.add('active'); const cat = e.currentTarget.dataset.cat || ''; productFilters.category = cat; renderProductsGridFiltered(); }));
      // set All active by default
      const all = document.querySelector('.category-btn[data-cat=""]'); if(all) all.classList.add('active');
    }
    // initialize price range sliders
    initPriceRangeControls();
  }

  function initPriceRangeControls(){
    const minInput = document.getElementById('price-min');
    const maxInput = document.getElementById('price-max');
    const minDisplay = document.getElementById('price-min-display');
    const maxDisplay = document.getElementById('price-max-display');
    if(!minInput || !maxInput || !minDisplay || !maxDisplay) return;
    const priced = products.filter(p=> p.price && p.price>0).map(p=>p.price);
    const min = priced.length? Math.min(...priced) : 0;
    const max = priced.length? Math.max(...priced) : 10000;
    minInput.min = min; minInput.max = max; minInput.value = min;
    maxInput.min = min; maxInput.max = max; maxInput.value = max;
    productFilters.minPrice = min; productFilters.maxPrice = max;
    minDisplay.textContent = min.toLocaleString(); maxDisplay.textContent = max.toLocaleString();

    function syncAndRender(){
      let a = Number(minInput.value);
      let b = Number(maxInput.value);
      if(a > b){ const t = a; a = b; b = t; minInput.value = a; maxInput.value = b; }
      productFilters.minPrice = a; productFilters.maxPrice = b;
      minDisplay.textContent = a.toLocaleString(); maxDisplay.textContent = b.toLocaleString();
      renderProductsGridFiltered();
    }
    minInput.addEventListener('input', syncAndRender);
    maxInput.addEventListener('input', syncAndRender);
    const reset = document.getElementById('price-reset'); if(reset) reset.addEventListener('click', ()=>{ minInput.value = min; maxInput.value = max; syncAndRender(); });
  }

  function renderFeatured(){
    const el = document.getElementById('featured-grid'); if(!el) return;
    el.innerHTML='';
    // Show featured products first, then fill up to 6 with other products
    const featured = products.filter(p=>p.featured);
    const others = products.filter(p=>!p.featured);
    const list = featured.concat(others).slice(0,6);
    list.forEach(p=>{
      const d=document.createElement('div');d.className='product-card ' + variants[p.id % variants.length];
      const img = encodeURI(p.imagePath);
      d.innerHTML = `<div class="product-media"><img src="${img}" alt="${p.name}"></div><div class="product-info"><h4>${p.name}</h4><div class="price">KES ${p.price? p.price.toLocaleString() : 'Contact'}</div></div><div class="product-actions"><button class="btn" data-id="${p.id}">Add to Cart</button></div>`;
      el.appendChild(d);
    });
    el.querySelectorAll('.btn').forEach(b=>b.addEventListener('click',e=>addToCart(Number(e.currentTarget.dataset.id))));
  }

  /* Render horizontal category rows on homepage */
  function renderCategoryRows(){
    // Top deals: first 8 products
    const top = document.getElementById('row-top-deals');
    const newA = document.getElementById('row-new-arrivals');
    const budget = document.getElementById('row-budget-picks');
    if(top){
      top.innerHTML='';
      products.slice(0,8).forEach(p=>{ top.appendChild(makeCardForRow(p)); });
    }
    if(newA){
      newA.innerHTML='';
      products.slice(8,16).forEach(p=>{ newA.appendChild(makeCardForRow(p)); });
    }
    if(budget){
      budget.innerHTML='';
      // pick cheaper items for budget
      const sorted = products.slice().sort((a,b)=> (a.price||999999)-(b.price||999999));
      sorted.slice(0,8).forEach(p=>{ budget.appendChild(makeCardForRow(p)); });
    }
  }

  function makeCardForRow(p){
    const card = document.createElement('article');card.className='product-card ' + variants[p.id % variants.length];
    const img = encodeURI(p.imagePath);
    card.innerHTML = `
      <div class="product-media"><img src="${img}" alt="${p.name}"></div>
      <div class="product-info"><h4>${p.name}</h4><div class="price">KES ${p.price? p.price.toLocaleString() : 'Contact'}</div><div class="product-features">${p.unit? p.unit : ''}</div></div>
      <div class="product-actions"><button class="btn" data-id="${p.id}">Add</button></div>`;
    // wire add button
    card.querySelector('.btn').addEventListener('click',e=>addToCart(Number(e.currentTarget.dataset.id)));
    return card;
  }

  function renderCartPage(){
    const container = document.getElementById('cart-items');
    if(!container) return;
    const cart=getCart();
    container.innerHTML='';
    if(cart.length===0){container.innerHTML='<p>Your cart is empty.</p>'}
    cart.forEach(i=>{
      const div=document.createElement('div');div.className='cart-item';
      const thumb = encodeURI(i.imagePath);
      div.innerHTML=`
        <img src="${thumb}" alt="${i.name}">
        <div style="flex:1"><strong>${i.name}</strong><p>KES ${i.price.toLocaleString()} <small>${i.unit? ' · '+i.unit : ''}</small></p></div>
        <div>
          <input type="number" min="1" value="${i.qty}" data-id="${i.id}" style="width:64px">
          <p>Subtotal: KES ${ (i.price*i.qty).toLocaleString() }</p>
          <button data-id="${i.id}" class="btn btn-outline remove">Remove</button>
        </div>`;
      container.appendChild(div);
    });
    // wire events
    container.querySelectorAll('input[type=number]').forEach(inp=>inp.addEventListener('change',e=>updateQty(Number(e.currentTarget.dataset.id),Number(e.currentTarget.value))));
    container.querySelectorAll('.remove').forEach(b=>b.addEventListener('click',e=>{removeFromCart(Number(e.currentTarget.dataset.id))}));
    document.getElementById('cart-total').textContent = cartTotal().toLocaleString();
  }

  /* Floating checkout panel creation */
  function openCheckoutPanel(mode = 'order', productId = null){
    // mode: 'order' (full order with payment) or 'quote' (simple product+qty quote)
    let panel = document.querySelector('.checkout-panel');
    if(panel){ panel.remove(); }
    panel = document.createElement('div'); panel.className='checkout-panel';
    // build items HTML depending on mode
    const itemsHtml = (()=>{
      if(mode === 'quote'){
        const q = getQuoteCart();
        if(q.length===0){
          // if a single productId was provided, show that one
          if(productId){ const p = products.find(x=>x.id===productId); return `<div class="quote-item" data-id="${p.id}"><div style="display:flex;gap:8px;align-items:center"><img src="${encodeURI(p.imagePath)}" style="width:64px;height:48px;object-fit:cover;border-radius:6px"><div><strong>${p.name}</strong><div>KES ${p.price? p.price.toLocaleString() : 'Contact'}</div></div></div><div style="margin-top:8px"><label>Quantity <input type="number" min="1" value="1" data-id="${p.id}" class="quote-qty" style="width:72px"></label></div></div>`; }
          return '<p>Your quote list is empty.</p>'
        }
        return q.map(i=>`<div class="quote-item" data-id="${i.id}"><div style="display:flex;gap:8px;align-items:center"><img src="${encodeURI(i.imagePath)}" style="width:64px;height:48px;object-fit:cover;border-radius:6px"><div><strong>${i.name}</strong><div>KES ${i.price? i.price.toLocaleString() : 'Contact'}</div></div></div><div style="margin-top:8px"><label>Quantity <input type="number" min="1" value="${i.qty}" data-id="${i.id}" class="quote-qty" style="width:72px"></label></div></div>`).join('');
      }
      // default: use checkout cart
      const cart = getCart(); if(cart.length===0) return '<p>Your cart is empty.</p>';
      return cart.map(i=>`<div class="quote-item" data-id="${i.id}"><div style="display:flex;gap:8px;align-items:center"><img src="${encodeURI(i.imagePath)}" style="width:64px;height:48px;object-fit:cover;border-radius:6px"><div><strong>${i.name}</strong><div>KES ${i.price? i.price.toLocaleString() : 'Contact'}</div></div></div><div style="margin-top:8px"><label>Quantity <input type="number" min="1" value="${i.qty}" data-id="${i.id}" class="quote-qty" style="width:72px"></label></div></div>`).join('');
    })();

    if(mode === 'quote'){
      panel.innerHTML = `
        <button class="close-cke" aria-label="Close">✕</button>
        <h3>Request a Quote</h3>
        <div id="panel-cart-items">${itemsHtml}</div>
        <form id="checkout-form">
          <input type="hidden" name="panel-mode" value="quote">
          <label>Name<input id="cust-name" required></label>
          <label>Phone<input id="cust-phone" required></label>
          <label>Message<textarea id="order-notes" placeholder="Any details or measurements (optional)"></textarea></label>
          <div style="margin-top:12px;display:flex;gap:8px;justify-content:flex-end">
            <button type="button" class="btn btn-outline close-panel">Close</button>
            <button type="submit" class="btn">Send Quote Request</button>
          </div>
        </form>
      `;
    } else {
      panel.innerHTML = `
        <button class="close-cke" aria-label="Close">✕</button>
        <h3>Your Cart</h3>
        <div id="panel-cart-items">${itemsHtml}</div>
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px"><strong>Total:</strong><div id="panel-cart-total">${cartTotal().toLocaleString()}</div></div>
        <form id="checkout-form">
          <input type="hidden" name="panel-mode" value="order">
          <label>Name<input id="cust-name" required></label>
          <label>Phone<input id="cust-phone" required></label>
          <label>Address<textarea id="cust-address"></textarea></label>
          <label>Mpesa Sender Name<input id="mpesa-name" placeholder="Sender name (optional)"></label>
          <label>Mpesa Time<input id="mpesa-time" placeholder="Time payment was sent (optional)"></label>
          <label>Mpesa Reference<input id="mpesa-ref" placeholder="Transaction reference (optional)"></label>
          <div style="margin-top:12px;display:flex;gap:8px;justify-content:flex-end">
            <button type="button" class="btn btn-outline close-panel">Close</button>
            <button type="submit" class="btn">Place Order</button>
          </div>
        </form>
      `;
    }

    document.body.appendChild(panel);
    // mark panel with current mode for live updates and accessibility
    panel.dataset.mode = mode;
    panel.setAttribute('role','dialog');
    panel.setAttribute('aria-label', mode === 'quote' ? 'Quote panel' : 'Checkout panel');
    // focus first input for keyboard users
    const firstFocusable = panel.querySelector('input,button,textarea,select'); if(firstFocusable) firstFocusable.focus();
    // wire close to central closePanel to ensure focus is released
    panel.querySelectorAll('.close-cke').forEach(btn=>btn.addEventListener('click',()=>closePanel(panel)));
    const closeBtn = panel.querySelector('.close-panel'); if(closeBtn) closeBtn.addEventListener('click',()=>closePanel(panel));
    // trap focus and keyboard handling
    trapFocus(panel);
    // ensure panel cart items and bindings
    populatePanel(mode);
  }

  // Close panel helper: remove panel and release focus handlers
  function closePanel(panel){
    if(!panel) return;
    releaseFocus();
    try{ panel.remove(); }catch(e){}
  }

  // Focus trap for modal-like panel
  let _focusHandler = null;
  let _lastFocused = null;
  function trapFocus(panel){
    releaseFocus();
    _lastFocused = document.activeElement;
    const focusable = panel.querySelectorAll('a[href],button:not([disabled]),input,textarea,select,[tabindex]:not([tabindex="-1"])');
    const first = focusable[0];
    const last = focusable[focusable.length-1];
    function onKey(e){
      if(e.key === 'Escape'){
        e.preventDefault();
        closePanel(panel);
        return;
      }
      if(e.key === 'Tab'){
        if(focusable.length === 0) { e.preventDefault(); return }
        if(e.shiftKey){
          if(document.activeElement === first){ e.preventDefault(); last.focus(); }
        } else {
          if(document.activeElement === last){ e.preventDefault(); first.focus(); }
        }
      }
    }
    _focusHandler = onKey;
    document.addEventListener('keydown', _focusHandler);
    // ensure focus starts inside
    if(first) first.focus();
  }

  function releaseFocus(){ if(_focusHandler){ document.removeEventListener('keydown', _focusHandler); _focusHandler = null; if(_lastFocused && _lastFocused.focus) _lastFocused.focus(); _lastFocused = null; } }

  function populatePanel(mode='order'){
    const itemsContainer = document.getElementById('panel-cart-items'); if(!itemsContainer) return;
    itemsContainer.innerHTML='';
    if(mode === 'quote'){
      const cart = getQuoteCart();
      if(cart.length===0){ itemsContainer.innerHTML = '<p>Your quote list is empty.</p>'; const pct = document.getElementById('panel-cart-total'); if(pct) pct.textContent = '0'; return }
      cart.forEach(i=>{
        const div = document.createElement('div'); div.className='quote-item';
        div.innerHTML = `<img src="${encodeURI(i.imagePath)}" style="width:64px;height:48px;object-fit:cover;border-radius:6px;margin-right:8px"><div style="flex:1"><strong>${i.name}</strong><p>KES ${i.price.toLocaleString()} · ${i.unit||''}</p></div><div><input type="number" min="1" value="${i.qty}" data-id="${i.id}" class="quote-qty" style="width:64px"><button data-id="${i.id}" class="btn btn-outline remove-quote">Remove</button></div>`;
        itemsContainer.appendChild(div);
      });
      // wire inputs and remove for quote cart
      itemsContainer.querySelectorAll('input.quote-qty').forEach(inp=>inp.addEventListener('change',e=>{ updateQuoteQty(Number(e.currentTarget.dataset.id), Number(e.currentTarget.value)); populatePanel('quote'); }));
      itemsContainer.querySelectorAll('.remove-quote').forEach(b=>b.addEventListener('click',e=>{ removeFromQuote(Number(e.currentTarget.dataset.id)); populatePanel('quote'); }));
      const pct = document.getElementById('panel-cart-total'); if(pct) pct.textContent = quoteTotal().toLocaleString();
      renderQuoteCount();
      return;
    }
    // default: order cart
    const cart = getCart();
    if(cart.length===0){ itemsContainer.innerHTML = '<p>Your cart is empty.</p>'; const pct = document.getElementById('panel-cart-total'); if(pct) pct.textContent = '0'; return }
    cart.forEach(i=>{
      const div = document.createElement('div'); div.className='cart-item';
      div.innerHTML = `<img src="${encodeURI(i.imagePath)}" style="width:64px;height:48px;object-fit:cover;border-radius:6px;margin-right:8px"><div style="flex:1"><strong>${i.name}</strong><p>KES ${i.price.toLocaleString()} · ${i.unit||''}</p></div><div><input type="number" min="1" value="${i.qty}" data-id="${i.id}" style="width:64px"><button data-id="${i.id}" class="btn btn-outline remove">Remove</button></div>`;
      itemsContainer.appendChild(div);
    });
    // wire inputs and remove
    itemsContainer.querySelectorAll('input[type=number]').forEach(inp=>inp.addEventListener('change',e=>{ updateQty(Number(e.currentTarget.dataset.id), Number(e.currentTarget.value)); populatePanel(); }));
    itemsContainer.querySelectorAll('.remove').forEach(b=>b.addEventListener('click',e=>{ removeFromCart(Number(e.currentTarget.dataset.id)); populatePanel(); }));
    const pct = document.getElementById('panel-cart-total'); if(pct) pct.textContent = cartTotal().toLocaleString();
    renderCartCount();
  }

  /* Checkout */
  function handleCheckoutForm(){
    // Use event delegation so dynamically-created panels/forms are handled once
    document.addEventListener('submit', function(e){
      const form = e.target;
      if(!form || form.id !== 'checkout-form') return;
      e.preventDefault();
      const panelModeInput = form.querySelector('input[name="panel-mode"]');
      const panelMode = panelModeInput ? panelModeInput.value : 'order';
      const name = document.getElementById('cust-name') ? document.getElementById('cust-name').value.trim() : '';
      const phone = document.getElementById('cust-phone') ? document.getElementById('cust-phone').value.trim() : '';
      const address = document.getElementById('cust-address') ? document.getElementById('cust-address').value.trim() : '';
      const payment = document.getElementById('payment-method') ? document.getElementById('payment-method').value : '';
      const mpesaName = document.getElementById('mpesa-name') ? document.getElementById('mpesa-name').value.trim() : '';
      const mpesaTime = document.getElementById('mpesa-time') ? document.getElementById('mpesa-time').value.trim() : '';
      const mpesaRef = document.getElementById('mpesa-ref') ? document.getElementById('mpesa-ref').value.trim() : '';
      const notes = document.getElementById('order-notes') ? document.getElementById('order-notes').value.trim() : '';

      if(panelMode === 'quote'){
        // build quote message from panel items (doesn't touch cart)
        const items = [];
        document.querySelectorAll('#panel-cart-items .quote-item').forEach(el=>{
          const id = Number(el.dataset.id);
          const qtyInput = el.querySelector('.quote-qty');
          const qty = qtyInput ? Number(qtyInput.value) : 1;
          const p = products.find(x=>x.id===id);
          if(p) items.push({name: p.name, qty: qty, price: p.price});
        });
        if(items.length===0){ alert('No items selected for quote'); return }
        let msg = `Quote Request - Floor Luxe Laminates KE\n\nCustomer Name: ${name}\nPhone Number: ${phone}\n\nRequested Items:\n`;
        items.forEach(i=>{ msg += `- ${i.name} × ${i.qty}${i.price? ' = KES '+(i.price*i.qty).toLocaleString() : ''}\n`; });
        msg += `\nNotes: ${notes}\n\nPlease provide a quotation.`;
        const url = `https://wa.me/${businessNumber}?text=${encodeURIComponent(msg)}`;
        window.open(url,'_blank');
        const panel = document.querySelector('.checkout-panel'); if(panel) panel.remove();
        return;
      }

      // default: order flow using cart
      const cart = getCart(); if(cart.length===0){ alert('Cart is empty'); return }
      let msg = `New Order - Floor Luxe Laminates KE\n\nCustomer Name: ${name}\nPhone Number: ${phone}\nDelivery Address: ${address}\n\nOrder Items:\n`;
      cart.forEach(i=>{ msg += `- ${i.name} × ${i.qty} = KES ${ (i.price*i.qty).toLocaleString() }\n`; });
      msg += `\nTotal Amount: KES ${cartTotal().toLocaleString()}\n\nMpesa Sender Name: ${mpesaName}\nTime Payment Was Sent: ${mpesaTime}\nMpesa Reference: ${mpesaRef}\n\nNotes: ${notes}\n\nPlease confirm order.`;
      const url = `https://wa.me/${businessNumber}?text=${encodeURIComponent(msg)}`;
      window.open(url,'_blank');
      // clear cart after initiating checkout and update UI
      clearCart();
      // close floating panel if open
      const panel = document.querySelector('.checkout-panel'); if(panel) panel.remove();
    });
  }

  /* Simple banner carousel initializer */
  function initBannerCarousel(){
    const car = document.querySelector('.banner-carousel');
    if(!car) return;
    const slidesWrap = car.querySelector('.carousel-slides');
    const slides = car.querySelectorAll('.banner-slide');
    const prev = car.querySelector('.carousel-prev');
    const next = car.querySelector('.carousel-next');
    const indicators = car.querySelector('.carousel-indicators');
    const autoplay = slidesWrap && slidesWrap.dataset.autoplay === 'true';
    const interval = Number(slidesWrap && slidesWrap.dataset.interval) || 6000;
    let idx = 0; let timer = null;

    function update(){
      slidesWrap.style.transform = `translateX(-${idx * 100}%)`;
      if(indicators){
        Array.from(indicators.children).forEach((b,i)=> b.classList.toggle('active', i===idx));
      }
    }

    // build indicators
    if(indicators){
      indicators.innerHTML = '';
      slides.forEach((s,i)=>{
        const b = document.createElement('button'); b.type='button'; b.setAttribute('aria-label', 'Slide '+(i+1));
        if(i===0) b.classList.add('active');
        b.addEventListener('click', ()=>{ idx = i; update(); resetTimer(); });
        indicators.appendChild(b);
      });
    }

    function prevSlide(){ idx = (idx - 1 + slides.length) % slides.length; update(); resetTimer(); }
    function nextSlide(){ idx = (idx + 1) % slides.length; update(); resetTimer(); }

    if(prev) prev.addEventListener('click', prevSlide);
    if(next) next.addEventListener('click', nextSlide);

    function resetTimer(){ if(timer){ clearInterval(timer); timer = null; } if(autoplay){ timer = setInterval(()=>{ nextSlide(); }, interval); } }

    // pause on hover/focus
    car.addEventListener('mouseenter', ()=>{ if(timer) clearInterval(timer); });
    car.addEventListener('mouseleave', ()=>{ resetTimer(); });
    car.addEventListener('focusin', ()=>{ if(timer) clearInterval(timer); });
    car.addEventListener('focusout', ()=>{ resetTimer(); });

    // keyboard navigation
    car.addEventListener('keydown', (e)=>{ if(e.key==='ArrowLeft') prevSlide(); if(e.key==='ArrowRight') nextSlide(); });

    // kick off
    update(); resetTimer();
  }

  function clearCart(){
    localStorage.removeItem('fl_cart');
    renderCartCount();
    renderCartPage();
    const panelItems = document.getElementById('panel-cart-items'); if(panelItems) panelItems.innerHTML = '<p>Your cart is empty.</p>';
  }

  /* WhatsApp float */
  function wireWhatsAppFloat(){
    const el = document.getElementById('whatsapp-float'); if(!el) return;
    el.href = `https://wa.me/${businessNumber}`;
    // if the element has label spans, keep them; otherwise set text
    if(!el.querySelector('.w-label')){
      el.textContent = '💬 Chat on WhatsApp';
    }
  }

  // ensure cart-float shows and links
  function wireCartFloat(){
    const cf = document.getElementById('cart-float');
    if(!cf) return;
    // open floating checkout panel instead of navigating to a cart page
    cf.addEventListener('click', function(e){ e.preventDefault(); openCheckoutPanel(); });
    renderCartCount();
  }

  /* Small interactions: hamburger */
  function wireMenu(){
    document.querySelectorAll('.hamburger').forEach(btn=>btn.addEventListener('click',()=>{
      const list = btn.parentElement.querySelector('.nav-list');
      if(!list) return;
      const isOpen = list.classList.contains('open') || list.getAttribute('data-open') === 'true';
      if(isOpen){
        list.classList.remove('open');
        list.setAttribute('data-open','false');
        btn.setAttribute('aria-expanded','false');
        document.body.classList.remove('mobile-nav-open');
      } else {
        list.classList.add('open');
        list.setAttribute('data-open','true');
        btn.setAttribute('aria-expanded','true');
        document.body.classList.add('mobile-nav-open');
      }
      // update runtime measurements so floats reposition correctly
      updateMobileCtaHeight();
    }));
  }

  /* Measure mobile CTA and mobile nav heights and set CSS variables so floats avoid overlap */
  function updateMobileCtaHeight(){
    try{
      const cta = document.querySelector('.mobile-cta-bar');
      const nav = document.querySelector('.nav-list');
      let ctaH = 0;
      if(cta && window.getComputedStyle(cta).display !== 'none') ctaH = cta.offsetHeight || 0;
      document.documentElement.style.setProperty('--mobile-cta-height', (ctaH || 0) + 'px');
      if(document.body.classList.contains('mobile-nav-open') && nav){
        const navH = nav.offsetHeight || 0;
        document.documentElement.style.setProperty('--mobile-nav-height', navH + 'px');
      } else {
        document.documentElement.style.setProperty('--mobile-nav-height', '0px');
      }
    }catch(e){console.warn('updateMobileCtaHeight error', e)}
  }

  /* Init page-specific renders */
  function init(){
    renderCartCount();
    renderQuoteCount();
    wireMenu();
    wireWhatsAppFloat();
    renderFeatured();
    // on products page use filtered renderer + controls
    if(document.body && document.body.id === 'products-page'){
      renderProductsGridFiltered();
      wireProductsControls();
    } else {
      renderProductsGrid();
    }
    renderCategoryRows();
    wireCartFloat();
    initBannerCarousel();
    // wire header quote button to open quote panel
    const qb = document.getElementById('quote-btn'); if(qb) qb.addEventListener('click', e=>{ e.preventDefault(); openCheckoutPanel('quote'); });
    const mq = document.getElementById('mobile-quote-btn'); if(mq) mq.addEventListener('click', e=>{ e.preventDefault(); openCheckoutPanel('quote'); });
    renderCartPage();
    handleCheckoutForm();
    // bind cart page checkout button to floating panel
    const cb = document.getElementById('checkout-btn'); if(cb) cb.addEventListener('click', e=>{ e.preventDefault(); openCheckoutPanel('order'); });

    // set year in footer
    document.getElementById('year') && (document.getElementById('year').textContent = new Date().getFullYear());
    // set initial CTA/nav measurements and update on resize
    updateMobileCtaHeight();
    window.addEventListener('resize', debounce(function(){ updateMobileCtaHeight(); }, 150));
  }

  // expose addToCart for inline usage if needed
  window.addToCart = addToCart;
  window.onload = init;
})();
