/**
 * dynamic-content.js
 * Fetches data/promos.json and data/testimonials.json and renders them
 * into any matching container on the page. Falls back silently (leaves
 * static HTML in place) if the fetch fails — e.g. when opened as a local
 * file:// page instead of served over http(s).
 */
(function () {
  function starString(n) {
    n = Math.max(1, Math.min(5, parseInt(n, 10) || 5));
    return "&#9733;".repeat(n) + "&#9734;".repeat(5 - n);
  }

  function renderPromos(promos) {
    const track = document.querySelector('.promo-track');
    if (!track || !Array.isArray(promos) || promos.length === 0) return;
    const spans = promos.map(p => `<span>${escapeHtml(p)}</span>`).join('');
    // duplicate once for seamless marquee loop
    track.innerHTML = spans + spans;
  }

  function renderTestimonials(items) {
    const containers = document.querySelectorAll('[data-dynamic="testimonials"]');
    if (!containers.length || !Array.isArray(items) || items.length === 0) return;
    const html = items.map(t => `
      <div class="testi-card">
        <div class="stars">${starString(t.stars)}</div>
        <div class="quote-mark">&ldquo;</div>
        <p>${escapeHtml(t.quote)}</p>
        <div class="who">${escapeHtml(t.name)}</div>
      </div>`).join('');
    containers.forEach(c => c.innerHTML = html);
  }

  function escapeHtml(s) {
    const d = document.createElement('div');
    d.textContent = s || '';
    return d.innerHTML;
  }

  fetch('data/promos.json').then(r => r.ok ? r.json() : null).then(data => {
    if (data) renderPromos(data);
  }).catch(() => {});

  fetch('data/testimonials.json').then(r => r.ok ? r.json() : null).then(data => {
    if (data) renderTestimonials(data);
  }).catch(() => {});
})();
