// ---------- Inventory ----------
const CARS = [
  {
    slug: 'ford-ranger-supercab-2020', make: 'Ford', body: 'Bakkie',
    name: '2020 Ford Ranger SuperCab', variant: '2.2 TDCi', year: 2020,
    km: 154000, price: 204999, fuel: 'Diesel', transmission: 'Manual',
    images: 16,
    features: ['Bluetooth', 'Air conditioning', 'Power steering', 'Electric windows', 'Original paint', 'Full service history', 'Bull bar', 'Tow bar'],
    description: 'Workhorse bakkie with solid 2.2 TDCi diesel, manual gearbox, and the proven Ranger reliability. Ideal for business, farm, or family use.'
  },
  {
    slug: 'ford-everest-xls-2017', make: 'Ford', body: 'SUV',
    name: '2017 Ford Everest', variant: '2.2 TDCi XLS', year: 2017,
    km: 124000, price: 259999, fuel: 'Diesel', transmission: 'Automatic',
    images: 15,
    features: ['Leather seats', '7 seater', 'Reverse camera', 'Cruise control', 'Multifunction steering', 'Bluetooth', 'Climate control', 'Alloy wheels'],
    description: 'Spacious 7-seater SUV with the efficient 2.2 TDCi engine and smooth automatic. Perfect family vehicle with generous cabin space.'
  },
  {
    slug: 'ford-everest-sport-2022', make: 'Ford', body: 'SUV',
    name: '2022 Ford Everest Sport', variant: '2.0 Sit XLT Sport', year: 2022,
    km: 28000, price: 449999, fuel: 'Diesel', transmission: 'Automatic',
    images: 9,
    features: ['Leather seats', '7 seater', 'Reverse camera', 'Park distance control', 'Apple CarPlay', 'Android Auto', 'Climate control', 'Sport wheels', 'LED headlights'],
    description: 'Low-mileage Everest Sport with premium black trim, sport wheels, and the latest infotainment. Nearly new condition.'
  },
  {
    slug: 'ford-ranger-singlecab-2024', make: 'Ford', body: 'Bakkie',
    name: '2024 Ford Ranger Single Cab', variant: '2.0 D Sit XL', year: 2024,
    km: 19000, price: 319999, fuel: 'Diesel', transmission: 'Manual',
    images: 16,
    features: ['Canopy', 'Tablet-style infotainment', 'Bluetooth', 'Apple CarPlay', 'Air conditioning', 'Electric windows', 'Original paint', 'Near-new condition'],
    description: 'Brand-new generation Ranger Single Cab with modern infotainment and low 19 000 km. Practical workhorse with modern tech.'
  },
  {
    slug: 'haval-h2-2019', make: 'Haval', body: 'SUV',
    name: '2019 Haval H2', variant: '1.5T Luxury', year: 2019,
    km: 121000, price: 134999, fuel: 'Petrol', transmission: 'Manual',
    images: 7,
    features: ['Leather seats', 'Reverse camera', 'Cruise control', 'Bluetooth', 'Alloy wheels', 'Air conditioning', 'Electric windows'],
    description: 'Compact SUV with comfortable leather interior and punchy 1.5 turbo engine. Great value entry into the SUV segment.'
  },
  {
    slug: 'haval-h2-2020', make: 'Haval', body: 'SUV',
    name: '2020 Haval H2', variant: '1.5T Luxury', year: 2020,
    km: 86000, price: 164999, fuel: 'Diesel', transmission: 'Automatic',
    images: 21,
    features: ['Leather seats', 'Panoramic roof', 'Reverse camera', 'Park distance control', 'Climate control', 'Cruise control', 'Bluetooth', 'Alloy wheels', 'Keyless entry'],
    description: 'Well-specced second-gen Haval H2 with rounded fascia, full leather trim, and automatic gearbox. Loaded with comfort features.'
  },
  {
    slug: 'toyota-urban-cruiser', make: 'Toyota', body: 'SUV',
    name: 'Toyota Urban Cruiser', variant: '1.5 XR Auto', year: 2022,
    km: 13000, price: 199999, fuel: 'Petrol', transmission: 'Automatic',
    images: 11,
    features: ['Low mileage', 'Reverse camera', 'Bluetooth', 'Cruise control', 'Multifunction steering', 'Alloy wheels', 'Air conditioning', 'Toyota reliability'],
    description: 'Ultra-low-mileage urban SUV with Toyota bulletproof reliability. Economical 1.5 petrol with smooth automatic gearbox.'
  },
  {
    slug: 'volvo-v40', make: 'Volvo', body: 'Hatchback',
    name: '2015 Volvo V40 T3', variant: '1.5T Momentum', year: 2015,
    km: 98000, price: 179999, fuel: 'Petrol', transmission: 'Automatic',
    images: 13,
    features: ['Leather seats', 'Heated seats', 'Climate control', 'Park distance control', 'Bluetooth', 'Alloy wheels', 'Safety pack', 'Panoramic roof'],
    description: 'Premium Swedish hatchback with leather interior and class-leading safety. Turbocharged 1.5 delivers smooth performance.'
  },
  {
    slug: 'suzuki-swift-2022', make: 'Suzuki', body: 'Hatchback',
    name: '2022 Suzuki Swift', variant: '1.2 GLX', year: 2022,
    km: 60000, price: 179999, fuel: 'Petrol', transmission: 'Automatic',
    images: 12,
    features: ['Reverse camera', 'Bluetooth', 'Apple CarPlay', 'Android Auto', 'Alloy wheels', 'Cruise control', 'Multifunction steering', 'Keyless start'],
    description: 'Fuel-efficient modern hatchback with peppy 1.2 petrol and automatic gearbox. Ideal city car with modern connectivity.'
  },
  {
    slug: 'range-rover-sport', make: 'Land Rover', body: 'SUV',
    name: 'Range Rover Sport', variant: 'Supercharged', year: 2018,
    km: 76000, price: 699999, fuel: 'Petrol', transmission: 'Automatic',
    images: 1,
    features: ['Supercharged V8', 'Full leather', 'Air suspension', 'Panoramic roof', 'Navigation', 'Heated &amp; cooled seats', 'Premium sound', 'All-wheel drive'],
    description: 'Iconic British luxury SUV with supercharged power and unmatched presence. Impeccably maintained and ready to drive.'
  }
];

const fmtR = n => 'R ' + Math.round(n).toLocaleString('en-ZA').replace(/,/g, ' ');
const fmtKm = n => n.toLocaleString('en-ZA').replace(/,/g, ' ') + ' km';

const imgPath = (car, idx) => {
  const n = String(idx).padStart(2, '0');
  return `images/${car.slug}-${n}.jpg`;
};
const heroImg = car => imgPath(car, 1);
const allImgs = car => Array.from({length: car.images}, (_, i) => imgPath(car, i + 1));

// ---------- Year ----------
document.querySelectorAll('#year').forEach(el => el.textContent = new Date().getFullYear());

// ---------- Mobile menu ----------
const toggle = document.querySelector('.menu-toggle');
if (toggle) {
  toggle.addEventListener('click', () => {
    document.querySelector('.nav-links').classList.toggle('open');
  });
}

// ---------- Car card ----------
function carCard(c) {
  return `
    <article class="car-card" data-slug="${c.slug}">
      <div class="car-img">
        <span class="car-ribbon">${c.year >= 2023 ? 'New In' : 'Featured'}</span>
        <img src="${heroImg(c)}" alt="${c.name}" loading="lazy" />
      </div>
      <div class="car-body">
        <div class="make">${c.make}</div>
        <h3>${c.name}</h3>
        <div class="car-price">${fmtR(c.price)}</div>
        <div class="car-specs">
          <div class="spec">${c.year}</div>
          <div class="spec">${fmtKm(c.km)}</div>
          <div class="spec">${c.fuel}</div>
          <div class="spec">${c.transmission}</div>
        </div>
        <div class="actions">
          <button class="btn btn-ghost" data-action="view">View Details</button>
          <a class="btn btn-primary" href="contact.html" data-action="enquire" onclick="event.stopPropagation()">Enquire</a>
        </div>
      </div>
    </article>`;
}

// ---------- Featured on home ----------
const featured = document.getElementById('featured-grid');
if (featured) {
  const picks = [...CARS].sort((a, b) => b.year - a.year).slice(0, 6);
  featured.innerHTML = picks.map(carCard).join('');
  wireCards(featured);
}

// ---------- Showroom page ----------
const grid = document.getElementById('car-grid');
if (grid && !featured) {
  const fMake = document.getElementById('fMake');
  const fBody = document.getElementById('fBody');
  const fFuel = document.getElementById('fFuel');
  const fTrans = document.getElementById('fTrans');
  const fPrice = document.getElementById('fPrice');
  const sort = document.getElementById('sort');
  const resultCount = document.getElementById('resultCount');
  const resetBtn = document.getElementById('resetBtn');

  // Populate select options
  const uniq = key => [...new Set(CARS.map(c => c[key]))].sort();
  uniq('make').forEach(m => fMake.insertAdjacentHTML('beforeend', `<option value="${m}">${m}</option>`));
  uniq('body').forEach(m => fBody.insertAdjacentHTML('beforeend', `<option value="${m}">${m}</option>`));
  uniq('fuel').forEach(m => fFuel.insertAdjacentHTML('beforeend', `<option value="${m}">${m}</option>`));
  uniq('transmission').forEach(m => fTrans.insertAdjacentHTML('beforeend', `<option value="${m}">${m}</option>`));

  function render() {
    let list = CARS.filter(c =>
      (!fMake.value || c.make === fMake.value) &&
      (!fBody.value || c.body === fBody.value) &&
      (!fFuel.value || c.fuel === fFuel.value) &&
      (!fTrans.value || c.transmission === fTrans.value) &&
      (!fPrice.value || c.price <= +fPrice.value)
    );

    const s = sort.value;
    if (s === 'price-asc') list.sort((a, b) => a.price - b.price);
    else if (s === 'price-desc') list.sort((a, b) => b.price - a.price);
    else if (s === 'km-asc') list.sort((a, b) => a.km - b.km);
    else list.sort((a, b) => b.year - a.year);

    resultCount.textContent = list.length;
    grid.innerHTML = list.length
      ? list.map(carCard).join('')
      : '<p style="grid-column:1/-1;text-align:center;color:var(--muted);padding:60px 20px;">No vehicles match those filters. Try adjusting your criteria.</p>';
    wireCards(grid);
  }

  [fMake, fBody, fFuel, fTrans, fPrice, sort].forEach(el => el.addEventListener('change', render));
  resetBtn.addEventListener('click', () => {
    [fMake, fBody, fFuel, fTrans, fPrice].forEach(el => el.value = '');
    sort.value = 'newest';
    render();
  });

  render();
}

// ---------- Wire card clicks to modal ----------
function wireCards(container) {
  container.querySelectorAll('.car-card').forEach(card => {
    card.addEventListener('click', e => {
      if (e.target.closest('[data-action="enquire"]')) return;
      openCarModal(card.dataset.slug);
    });
  });
}

// ---------- Car modal ----------
const modal = document.getElementById('carModal');
const modalContent = document.getElementById('carModalContent');

function openCarModal(slug) {
  const c = CARS.find(x => x.slug === slug);
  if (!c) return;
  const imgs = allImgs(c);
  modalContent.innerHTML = `
    <button class="modal-close" aria-label="Close">&times;</button>
    <div class="modal-gallery">
      <div class="main-img"><img id="modalMain" src="${imgs[0]}" alt="${c.name}" /></div>
      <div class="thumbs">
        ${imgs.map((src, i) => `<img src="${src}" alt="${c.name} ${i+1}" data-idx="${i}" class="${i===0?'active':''}" />`).join('')}
      </div>
    </div>
    <div class="modal-body">
      <div class="make">${c.make}</div>
      <h2>${c.name}</h2>
      <div class="price">${fmtR(c.price)}</div>
      <p style="color:var(--muted);margin-bottom:20px;">${c.description}</p>
      <div class="modal-specs">
        <div class="s"><small>Year</small><strong>${c.year}</strong></div>
        <div class="s"><small>Mileage</small><strong>${fmtKm(c.km)}</strong></div>
        <div class="s"><small>Fuel</small><strong>${c.fuel}</strong></div>
        <div class="s"><small>Transmission</small><strong>${c.transmission}</strong></div>
        <div class="s"><small>Body Type</small><strong>${c.body}</strong></div>
        <div class="s"><small>Variant</small><strong>${c.variant}</strong></div>
      </div>
      <h3 style="margin-bottom:14px;font-size:1.05rem;text-transform:uppercase;letter-spacing:1px;">Features &amp; Extras</h3>
      <ul class="modal-features">
        ${c.features.map(f => `<li>${f}</li>`).join('')}
      </ul>
      <div class="modal-actions">
        <a class="btn btn-primary" href="https://wa.me/27871536734?text=${encodeURIComponent('Hi, I\'m interested in the ' + c.name + ' (' + fmtR(c.price) + ').')}" target="_blank" rel="noopener">Chat on WhatsApp</a>
        <a class="btn btn-outline" href="tel:+27871536734">Call +27 87 153 6734</a>
        <a class="btn btn-ghost" href="finance.html">Finance This Car</a>
      </div>
    </div>`;
  modal.classList.add('open');
  document.body.style.overflow = 'hidden';

  modalContent.querySelector('.modal-close').addEventListener('click', closeCarModal);
  const mainImg = modalContent.querySelector('#modalMain');
  modalContent.querySelectorAll('.thumbs img').forEach(thumb => {
    thumb.addEventListener('click', () => {
      mainImg.src = thumb.src;
      modalContent.querySelectorAll('.thumbs img').forEach(t => t.classList.remove('active'));
      thumb.classList.add('active');
    });
  });
}

function closeCarModal() {
  modal.classList.remove('open');
  document.body.style.overflow = '';
}
if (modal) {
  modal.addEventListener('click', e => { if (e.target === modal) closeCarModal(); });
  document.addEventListener('keydown', e => { if (e.key === 'Escape') closeCarModal(); });
}

// ---------- Hero slider ----------
const slider = document.getElementById('heroSlider');
if (slider) {
  const slides = slider.querySelectorAll('.hero-slide');
  const dotsEl = document.getElementById('heroDots');
  let i = 0;

  slides.forEach((_, idx) => {
    const b = document.createElement('button');
    if (idx === 0) b.classList.add('active');
    b.addEventListener('click', () => go(idx));
    dotsEl.appendChild(b);
  });
  const dots = dotsEl.querySelectorAll('button');

  function go(n) {
    slides[i].classList.remove('active');
    dots[i].classList.remove('active');
    i = (n + slides.length) % slides.length;
    slides[i].classList.add('active');
    dots[i].classList.add('active');
  }
  document.getElementById('heroPrev').addEventListener('click', () => { go(i - 1); reset(); });
  document.getElementById('heroNext').addEventListener('click', () => { go(i + 1); reset(); });
  let auto = setInterval(() => go(i + 1), 5500);
  function reset() { clearInterval(auto); auto = setInterval(() => go(i + 1), 5500); }
}

// ---------- Finance calculator ----------
const priceEl = document.getElementById('price');
if (priceEl) {
  const deposit = document.getElementById('deposit');
  const term = document.getElementById('term');
  const rate = document.getElementById('rate');
  const balloon = document.getElementById('balloon');

  const depositVal = document.getElementById('depositVal');
  const termVal = document.getElementById('termVal');
  const rateVal = document.getElementById('rateVal');
  const balloonVal = document.getElementById('balloonVal');
  const termLabel = document.getElementById('termLabel');

  const monthly = document.getElementById('monthly');
  const outPrice = document.getElementById('outPrice');
  const outDeposit = document.getElementById('outDeposit');
  const outLoan = document.getElementById('outLoan');
  const outInterest = document.getElementById('outInterest');
  const outBalloon = document.getElementById('outBalloon');
  const outTotal = document.getElementById('outTotal');

  function calc() {
    const P = Math.max(0, +priceEl.value || 0);
    const depPct = +deposit.value;
    const n = +term.value;
    const r = (+rate.value) / 100 / 12;
    const balPct = +balloon.value;

    const depAmt = P * (depPct / 100);
    const balAmt = P * (balPct / 100);
    const principal = P - depAmt;

    let m = 0;
    if (principal > 0 && n > 0) {
      if (r === 0) {
        m = (principal - balAmt) / n;
      } else {
        const balloonPV = balAmt / Math.pow(1 + r, n);
        m = (principal - balloonPV) * r / (1 - Math.pow(1 + r, -n));
      }
    }
    const totalPaid = m * n + depAmt + balAmt;
    const interest = totalPaid - P;

    depositVal.textContent = depPct + '%';
    termVal.textContent = n + ' months';
    rateVal.textContent = (+rate.value).toFixed(2) + '%';
    balloonVal.textContent = balPct + '%';
    termLabel.textContent = n;

    monthly.textContent = fmtR(m);
    outPrice.textContent = fmtR(P);
    outDeposit.textContent = fmtR(depAmt);
    outLoan.textContent = fmtR(principal);
    outInterest.textContent = fmtR(Math.max(0, interest));
    outBalloon.textContent = fmtR(balAmt);
    outTotal.textContent = fmtR(Math.max(P, totalPaid));
  }
  [priceEl, deposit, term, rate, balloon].forEach(el => el.addEventListener('input', calc));
  calc();
}

// ---------- Forms (demo) ----------
const cForm = document.getElementById('contact-form');
if (cForm) {
  cForm.addEventListener('submit', () => {
    document.getElementById('form-status').textContent = "Thanks - we'll be in touch shortly. (Demo form, not yet connected.)";
    cForm.reset();
  });
}
const aForm = document.getElementById('applyForm');
if (aForm) {
  aForm.addEventListener('submit', () => {
    document.getElementById('applyStatus').textContent = "Application received - our finance team will contact you within 24 hours. (Demo form, not yet connected.)";
    aForm.reset();
  });
}

// ---------- Floating social rail ----------
const railHTML = `
  <aside class="social-rail" aria-label="Social links">
    <a href="https://www.facebook.com/share/1HU5YjWTAD/" target="_blank" rel="noopener" aria-label="Facebook" title="Facebook">f</a>
    <a href="https://www.instagram.com/dbcarsdealership" target="_blank" rel="noopener" aria-label="Instagram" title="Instagram">&#9678;</a>
    <a href="https://vm.tiktok.com/ZMBr3KHrV/" target="_blank" rel="noopener" aria-label="TikTok" title="TikTok">T</a>
    <a href="tel:+27871536734" aria-label="Call us" title="Call us">&#9742;</a>
  </aside>`;
document.body.insertAdjacentHTML('beforeend', railHTML);

// ---------- WhatsApp widget ----------
const WA_NUMBER = '27871536734';
const waHTML = `
  <div class="wa-widget">
    <div class="wa-panel" id="waPanel" role="dialog" aria-label="WhatsApp chat">
      <div class="wa-header">
        <div class="avatar"><img src="images/brand-logo.jpg" alt="DB Cars" /></div>
        <div>
          <div class="name">DB Cars</div>
          <div class="status">Online</div>
        </div>
        <button class="close" id="waClose" aria-label="Close">&times;</button>
      </div>
      <div class="wa-body">
        <div class="wa-bubble">
          Hi there! &#128075; Welcome to DB Cars. How can we help you today?
          <span class="time">Now</span>
        </div>
      </div>
      <form class="wa-input" id="waForm" onsubmit="return false;">
        <input id="waMsg" type="text" placeholder="Type your message..." autocomplete="off" />
        <button type="submit" aria-label="Send">&#10148;</button>
      </form>
    </div>
    <button class="wa-btn" id="waToggle" aria-label="Open WhatsApp chat" title="Chat on WhatsApp">
      <svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
        <path d="M16 3C9.373 3 4 8.373 4 15c0 2.379.698 4.593 1.9 6.454L4 29l7.77-1.873A11.94 11.94 0 0 0 16 27c6.627 0 12-5.373 12-12S22.627 3 16 3zm0 21.818c-1.854 0-3.58-.52-5.054-1.417l-.362-.216-4.611 1.112 1.13-4.494-.235-.374A9.795 9.795 0 0 1 6.182 15c0-5.42 4.398-9.818 9.818-9.818S25.818 9.58 25.818 15 21.42 24.818 16 24.818zm5.43-7.35c-.298-.15-1.765-.872-2.04-.97-.273-.1-.472-.15-.671.15-.198.297-.77.97-.944 1.168-.174.198-.347.223-.645.074-.298-.15-1.26-.464-2.4-1.479-.887-.79-1.486-1.767-1.66-2.065-.174-.298-.019-.459.13-.608.134-.133.298-.347.447-.52.15-.174.198-.298.298-.496.1-.198.05-.372-.025-.521-.074-.15-.671-1.615-.919-2.213-.242-.582-.489-.503-.671-.513-.174-.008-.372-.01-.57-.01s-.521.074-.794.372c-.273.298-1.043 1.02-1.043 2.486 0 1.466 1.068 2.882 1.218 3.08.15.198 2.105 3.214 5.099 4.506.713.308 1.268.492 1.702.63.715.227 1.365.195 1.88.118.573-.086 1.765-.722 2.014-1.42.248-.698.248-1.296.174-1.42-.074-.125-.273-.198-.57-.347z"/>
      </svg>
    </button>
  </div>`;
document.body.insertAdjacentHTML('beforeend', waHTML);

(function initWa() {
  const toggle = document.getElementById('waToggle');
  const panel = document.getElementById('waPanel');
  const close = document.getElementById('waClose');
  const form = document.getElementById('waForm');
  const msg = document.getElementById('waMsg');

  toggle.addEventListener('click', () => panel.classList.toggle('open'));
  close.addEventListener('click', () => panel.classList.remove('open'));
  form.addEventListener('submit', () => {
    const text = msg.value.trim() || "Hi, I'd like to enquire about a vehicle.";
    const url = `https://wa.me/${WA_NUMBER}?text=${encodeURIComponent(text)}`;
    window.open(url, '_blank', 'noopener');
    msg.value = '';
    panel.classList.remove('open');
  });

  if (!sessionStorage.getItem('waShown')) {
    setTimeout(() => {
      panel.classList.add('open');
      sessionStorage.setItem('waShown', '1');
    }, 5000);
  }
})();
