// ---------- Car inventory (demo) ----------
const CARS = [
  { img: 'images/imgi_3_670588227_17863521012654004_5373845267430646685_n.jpg', name: 'VW T-Cross Highline', year: 2021, km: '48 000 km', price: 359900, type: 'suv' },
  { img: 'images/imgi_4_670869130_17862932478654004_3092507986317060902_n.jpg', name: 'Audi A3 Sportback', year: 2020, km: '62 500 km', price: 429900, type: 'luxury' },
  { img: 'images/imgi_5_659226024_17862144024654004_8904706581844058295_n.jpg', name: 'BMW 320i M-Sport', year: 2019, km: '74 800 km', price: 479900, type: 'luxury' },
  { img: 'images/imgi_6_669611786_17862042456654004_1630267728015162165_n.jpg', name: 'Toyota Corolla Quest', year: 2022, km: '36 200 km', price: 289900, type: 'sedan' },
  { img: 'images/imgi_7_660759290_17861847474654004_8149771367372078594_n.jpg', name: 'Ford Ranger XLT 2.0', year: 2021, km: '81 000 km', price: 549900, type: 'bakkie' },
  { img: 'images/imgi_8_661484574_17861846487654004_4350837944866014000_n.jpg', name: 'Hyundai Creta Executive', year: 2022, km: '42 700 km', price: 339900, type: 'suv' },
  { img: 'images/imgi_9_657379448_17860718040654004_586002670575209143_n.jpg', name: 'Mercedes-Benz A200', year: 2020, km: '58 400 km', price: 459900, type: 'luxury' },
  { img: 'images/imgi_10_657717999_17860691604654004_8066637107295484091_n.jpg', name: 'VW Polo TSI Life', year: 2022, km: '31 000 km', price: 279900, type: 'hatch' },
  { img: 'images/imgi_11_659481773_17860578063654004_4630476254547652287_n.jpg', name: 'Kia Sonet EX', year: 2022, km: '39 500 km', price: 299900, type: 'suv' },
  { img: 'images/imgi_12_657315799_17860577694654004_1718344494503963054_n.jpg', name: 'Suzuki Swift GL', year: 2021, km: '52 300 km', price: 189900, type: 'hatch' },
  { img: 'images/imgi_13_658403557_17860080264654004_4772769186024031729_n.jpg', name: 'Renault Kiger Zen', year: 2022, km: '28 900 km', price: 259900, type: 'suv' },
  { img: 'images/imgi_14_656798684_17859883197654004_4272105728319725344_n.jpg', name: 'Nissan Magnite Acenta', year: 2022, km: '33 800 km', price: 249900, type: 'suv' },
  { img: 'images/imgi_15_656060334_17859671412654004_2659462999053186742_n.jpg', name: 'Honda Civic 1.8', year: 2019, km: '78 200 km', price: 289900, type: 'sedan' },
  { img: 'images/imgi_16_657963860_17859669633654004_7456250449936791241_n.jpg', name: 'Mazda CX-3 Active', year: 2021, km: '44 100 km', price: 319900, type: 'suv' },
  { img: 'images/imgi_17_657372224_17859542445654004_5239559086165867436_n.jpg', name: 'Toyota Hilux 2.4 GD-6', year: 2020, km: '94 300 km', price: 479900, type: 'bakkie' },
  { img: 'images/imgi_18_655225619_17858910846654004_9063889064585670681_n.jpg', name: 'VW Golf 7 GTI', year: 2018, km: '88 000 km', price: 439900, type: 'hatch' },
  { img: 'images/imgi_19_655863004_17858880264654004_1520155986640873458_n.jpg', name: 'Audi Q2 35 TFSI', year: 2021, km: '51 600 km', price: 459900, type: 'luxury' },
  { img: 'images/imgi_20_652865978_17858367660654004_2273442367923605780_n.jpg', name: 'BMW 1 Series 118i', year: 2020, km: '67 400 km', price: 389900, type: 'luxury' },
  { img: 'images/imgi_21_654653346_17858155185654004_1597101967762149426_n.jpg', name: 'Haval Jolion Premium', year: 2022, km: '29 700 km', price: 319900, type: 'suv' },
  { img: 'images/imgi_22_650731070_17857636581654004_6293355469704505206_n.jpg', name: 'Toyota Fortuner 2.8 GD-6', year: 2019, km: '112 500 km', price: 569900, type: 'suv' },
  { img: 'images/imgi_23_650556314_17857518549654004_4913457941449587463_n.jpg', name: 'Mercedes-Benz C200', year: 2018, km: '97 200 km', price: 419900, type: 'luxury' },
  { img: 'images/imgi_24_650054289_17857518237654004_3463838386626795237_n.jpg', name: 'Hyundai i20 Fluid', year: 2022, km: '34 500 km', price: 249900, type: 'hatch' },
  { img: 'images/imgi_25_648683838_2147696959310551_7793957479228482908_n.jpg', name: 'Ford Fiesta Trend', year: 2019, km: '72 800 km', price: 199900, type: 'hatch' },
  { img: 'images/imgi_26_650850437_1691948372167100_536890494602395741_n.jpg', name: 'Mazda 3 Astina', year: 2020, km: '56 300 km', price: 349900, type: 'sedan' },
  { img: 'images/imgi_27_649229105_17856525345654004_3181951527970212651_n.jpg', name: 'Isuzu D-Max 250 HO', year: 2021, km: '68 400 km', price: 469900, type: 'bakkie' },
  { img: 'images/imgi_29_641067114_17855272041654004_1435839267936811191_n.jpg', name: 'VW Tiguan Comfortline', year: 2020, km: '79 100 km', price: 429900, type: 'suv' },
  { img: 'images/imgi_31_641769607_2054731848717291_7391899162761375212_n.jpg', name: 'Audi A4 35 TFSI', year: 2019, km: '84 600 km', price: 489900, type: 'luxury' },
  { img: 'images/imgi_32_639745154_17854064964654004_6207730296376894908_n.jpg', name: 'Toyota Starlet XS', year: 2022, km: '27 500 km', price: 229900, type: 'hatch' },
];

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

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

// ---------- Floating social rail ----------
const railHTML = `
  <aside class="social-rail" aria-label="Social links">
    <a href="https://www.facebook.com/p/011-Motors-61584747089208/" target="_blank" rel="noopener" aria-label="Facebook" title="Facebook">f</a>
    <a href="https://www.instagram.com/011.motors/" target="_blank" rel="noopener" aria-label="Instagram" title="Instagram">&#9678;</a>
    <a href="https://www.011motors.co.za/" target="_blank" rel="noopener" aria-label="Website" title="Website">&#8962;</a>
    <a href="tel:+27722211138" aria-label="Call us" title="Call us">&#9742;</a>
  </aside>`;
document.body.insertAdjacentHTML('beforeend', railHTML);

// ---------- WhatsApp widget ----------
const WA_NUMBER = '27722211138';
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/logo.jpg" alt="011 Motors" /></div>
        <div>
          <div class="name">011 Motors</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! 👋 Welcome to 011 Motors. 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');
  });

  // auto-open first visit after 5s
  if (!sessionStorage.getItem('waShown')) {
    setTimeout(() => {
      panel.classList.add('open');
      sessionStorage.setItem('waShown', '1');
    }, 5000);
  }
})();

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

// ---------- Car card renderer ----------
function renderCar(c) {
  return `
    <article class="car-card">
      <div class="car-img"><img src="${c.img}" alt="${c.name}" loading="lazy" /></div>
      <div class="car-body">
        <h3>${c.name}</h3>
        <div class="car-meta">${c.year} · ${c.km}</div>
        <div class="car-price">${fmtR(c.price)}</div>
        <a href="contact.html" class="btn btn-primary">Enquire</a>
      </div>
    </article>`;
}

// ---------- Home featured (first 6) ----------
const featured = document.getElementById('featured-grid');
if (featured) {
  featured.innerHTML = CARS.slice(0, 6).map(renderCar).join('');
}

// ---------- Showroom + filters ----------
const grid = document.getElementById('car-grid');
if (grid) {
  const render = (filter = 'all') => {
    const list = filter === 'all' ? CARS : CARS.filter(c => c.type === filter);
    grid.innerHTML = list.map(renderCar).join('') || '<p style="grid-column:1/-1;text-align:center;color:var(--muted)">No vehicles in this category - check back soon.</p>';
  };
  render();

  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      render(btn.dataset.filter);
    });
  });
}

// ---------- 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;

    // Standard SA vehicle finance with balloon - amortize (principal - balloon PV)
    // Common approach: monthly = (principal - balloon/(1+r)^n) * r / (1 - (1+r)^-n)
    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();
}

// ---------- Contact form (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();
  });
}
