/* ==========================================================
   Rasmussen Jewelers - Holiday Sale 2026 landing page
   Paste into Punchmark > Global JavaScript.
   Only runs on a page that contains the .rj-hs block, so it's safe site-wide.

   What it does:
   1. Countdown badge: "Ends Dec 24" -> "3 days left" -> "Last day today!"
   2. After Dec 24 (Mountain Time) it shows a "sale has ended" bar
   3. Smooth scrolling for "Find Your Store" / "Plan Your Visit"
   4. FAQ: opening one question closes the others
   ========================================================== */
(function () {
  'use strict';

  function init() {
    var root = document.querySelector('.rj-hs');
    if (!root) return;

    /* ---------- 0. Stylesheet cache safety net ----------
       Punchmark can keep serving an old cached copy of the Global
       Stylesheet after you save. If the Holiday Sale styles aren't
       there, load a fresh copy (refreshes at most once an hour). */
    var hasStyles = getComputedStyle(root).getPropertyValue('--rj-wine').trim() !== '';
    if (!hasStyles && !document.getElementById('rj-hs-fresh-css')) {
      var link = document.createElement('link');
      link.id = 'rj-hs-fresh-css';
      link.rel = 'stylesheet';
      link.href = '/css/local.css?rj=' + Math.floor(Date.now() / 3600000);
      document.head.appendChild(link);
    }

    /* ---------- 1 & 2. Countdown + end-of-sale ---------- */
    var hero = root.querySelector('[data-rj-sale-end]');
    var badge = root.querySelector('[data-rj-countdown]');

    // Today's date in Mountain Time (both stores), as YYYY-MM-DD
    function todayMT() {
      try {
        return new Intl.DateTimeFormat('en-CA', {
          timeZone: 'America/Denver', year: 'numeric', month: '2-digit', day: '2-digit'
        }).format(new Date());
      } catch (e) {
        var d = new Date();
        return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
      }
    }

    function daysBetween(a, b) {
      // a, b are YYYY-MM-DD strings; returns whole days from a to b
      var pa = a.split('-'), pb = b.split('-');
      var da = Date.UTC(+pa[0], +pa[1] - 1, +pa[2]);
      var db = Date.UTC(+pb[0], +pb[1] - 1, +pb[2]);
      return Math.round((db - da) / 86400000);
    }

    if (hero && badge) {
      var start = hero.getAttribute('data-rj-sale-start');
      var end = hero.getAttribute('data-rj-sale-end');
      var today = todayMT();
      var left = daysBetween(today, end);

      if (left < 0) {
        root.classList.add('is-ended');
        var endedBar = root.querySelector('.rj-hs-ended');
        if (endedBar) endedBar.hidden = false;
        badge.textContent = 'Sale Ended';
      } else if (start && daysBetween(start, today) < 0) {
        // Before the sale starts: keep "Ends Dec 24" but show the start
        badge.textContent = 'Starts Dec 3';
      } else if (left === 0) {
        badge.textContent = 'Last Day Today!';
        badge.classList.add('rj-hs-badge--urgent');
      } else if (left <= 7) {
        badge.textContent = left === 1 ? '1 Day Left' : left + ' Days Left';
        badge.classList.add('rj-hs-badge--urgent');
      }
      // 8+ days out: leave "Ends Dec 24" as written in the HTML
    }

    /* ---------- 3. Smooth scroll for in-page links ---------- */
    var reduceMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    root.querySelectorAll('a[href^="#"]').forEach(function (link) {
      link.addEventListener('click', function (e) {
        var id = link.getAttribute('href').slice(1);
        var target = id && document.getElementById(id);
        if (!target) return;
        e.preventDefault();
        // Offset for Punchmark's sticky header, if there is one
        var header = document.querySelector('header');
        var offset = header && getComputedStyle(header).position.match(/fixed|sticky/) ? header.offsetHeight : 0;
        var y = target.getBoundingClientRect().top + window.pageYOffset - offset - 12;
        window.scrollTo({ top: y, behavior: reduceMotion ? 'auto' : 'smooth' });
      });
    });

    /* ---------- 4. FAQ: one open at a time ---------- */
    var faqs = root.querySelectorAll('.rj-hs-faq details');
    faqs.forEach(function (item) {
      item.addEventListener('toggle', function () {
        if (!item.open) return;
        faqs.forEach(function (other) { if (other !== item) other.open = false; });
      });
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
