/* =========================================================
   Alpha Drive — main.js (vanilla, offline)
   ========================================================= */
(function () {
  'use strict';

  var CONSENT_KEY = 'alphadrive.consent.v1';
  var calmMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  function ready(fn) {
    if (document.readyState !== 'loading') {
      fn();
    } else {
      document.addEventListener('DOMContentLoaded', fn);
    }
  }

  /* ---------- Sticky header state ---------- */
  function initHeader() {
    var bar = document.querySelector('.helm-bar');
    if (!bar) return;
    var tick = false;

    function paint() {
      bar.classList.toggle('is-sunken', window.scrollY > 12);
      tick = false;
    }
    window.addEventListener('scroll', function () {
      if (!tick) {
        tick = true;
        window.requestAnimationFrame(paint);
      }
    }, { passive: true });
    paint();
  }

  /* ---------- Mobile navigation ---------- */
  function initNav() {
    var toggle = document.querySelector('.helm-toggle');
    var routes = document.querySelector('.helm-routes');
    if (!toggle || !routes) return;

    function close() {
      toggle.setAttribute('aria-expanded', 'false');
      routes.classList.remove('is-open');
      document.body.classList.remove('is-locked');
    }

    toggle.addEventListener('click', function () {
      var open = toggle.getAttribute('aria-expanded') === 'true';
      toggle.setAttribute('aria-expanded', open ? 'false' : 'true');
      routes.classList.toggle('is-open', !open);
      document.body.classList.toggle('is-locked', !open);
    });

    routes.addEventListener('click', function (event) {
      if (event.target.closest('a')) close();
    });

    document.addEventListener('keydown', function (event) {
      if (event.key === 'Escape') close();
    });

    window.addEventListener('resize', function () {
      if (window.innerWidth > 860) close();
    });
  }

  /* ---------- Scroll reveal ---------- */
  function initReveal() {
    var targets = document.querySelectorAll('.rise');
    if (!targets.length) return;

    if (calmMotion || !('IntersectionObserver' in window)) {
      Array.prototype.forEach.call(targets, function (node) {
        node.classList.add('is-lit');
      });
      return;
    }

    var watcher = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-lit');
          watcher.unobserve(entry.target);
        }
      });
    }, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 });

    Array.prototype.forEach.call(targets, function (node, index) {
      node.style.transitionDelay = Math.min(index % 4, 3) * 70 + 'ms';
      watcher.observe(node);
    });
  }

  /* ---------- FAQ: keep one answer open at a time ---------- */
  function initQueries() {
    var items = document.querySelectorAll('.query-item');
    Array.prototype.forEach.call(items, function (item) {
      item.addEventListener('toggle', function () {
        if (!item.open) return;
        Array.prototype.forEach.call(items, function (other) {
          if (other !== item) other.open = false;
        });
      });
    });
  }

  /* ---------- Cookie consent ---------- */
  function readConsent() {
    try {
      return JSON.parse(window.localStorage.getItem(CONSENT_KEY));
    } catch (error) {
      return null;
    }
  }

  function writeConsent(state) {
    try {
      window.localStorage.setItem(CONSENT_KEY, JSON.stringify(state));
    } catch (error) {
      /* Lagring blockerad i webbläsaren — inställningen gäller för denna session. */
    }
  }

  function initConsent() {
    var dock = document.getElementById('consentDock');
    var veil = document.getElementById('consentVeil');
    if (!dock) return;

    var panelForm = document.getElementById('consentPanelForm');
    var openers = document.querySelectorAll('[data-consent-open]');
    var lastFocus = null;

    function show() {
      dock.hidden = false;
      window.setTimeout(function () { dock.classList.add('is-shown'); }, 60);
    }

    function hide() {
      dock.classList.remove('is-shown');
      window.setTimeout(function () { dock.hidden = true; }, 400);
    }

    function openPanel() {
      if (!veil) return;
      lastFocus = document.activeElement;
      var saved = readConsent();
      if (saved && panelForm) {
        var analytics = panelForm.querySelector('#consentAnalytics');
        var marketing = panelForm.querySelector('#consentMarketing');
        if (analytics) analytics.checked = !!saved.analytics;
        if (marketing) marketing.checked = !!saved.marketing;
      }
      veil.classList.add('is-open');
      document.body.classList.add('is-locked');
      var first = veil.querySelector('input, button');
      if (first) first.focus();
    }

    function closePanel() {
      if (!veil) return;
      veil.classList.remove('is-open');
      document.body.classList.remove('is-locked');
      if (lastFocus && lastFocus.focus) lastFocus.focus();
    }

    function save(state) {
      state.necessary = true;
      state.decidedAt = new Date().toISOString();
      writeConsent(state);
      closePanel();
      hide();
    }

    document.addEventListener('click', function (event) {
      var action = event.target.closest('[data-consent]');
      if (action) {
        var kind = action.getAttribute('data-consent');
        if (kind === 'accept') save({ analytics: true, marketing: true });
        if (kind === 'reject') save({ analytics: false, marketing: false });
        if (kind === 'manage') openPanel();
        if (kind === 'close') closePanel();
        if (kind === 'save' && panelForm) {
          var a = panelForm.querySelector('#consentAnalytics');
          var m = panelForm.querySelector('#consentMarketing');
          save({ analytics: !!(a && a.checked), marketing: !!(m && m.checked) });
        }
        return;
      }
      if (veil && event.target === veil) closePanel();
    });

    Array.prototype.forEach.call(openers, function (node) {
      node.addEventListener('click', function (event) {
        event.preventDefault();
        openPanel();
      });
    });

    document.addEventListener('keydown', function (event) {
      if (event.key === 'Escape' && veil && veil.classList.contains('is-open')) closePanel();
    });

    if (!readConsent()) show();
  }

  /* ---------- Order form ---------- */
  function cleanPhone(value) {
    return value.replace(/[^\d+]/g, '');
  }

  function initOrderForm() {
    var form = document.getElementById('orderForm');
    if (!form) return;

    var name = form.querySelector('#orderName');
    var phone = form.querySelector('#orderPhone');
    var alertName = form.querySelector('#orderNameAlert');
    var alertPhone = form.querySelector('#orderPhoneAlert');

    function setError(field, box, message) {
      field.setAttribute('aria-invalid', message ? 'true' : 'false');
      box.textContent = message || '';
      return !message;
    }

    function checkName() {
      var value = name.value.trim();
      if (value.length < 2) return setError(name, alertName, 'Skriv ditt för- och efternamn.');
      if (!/\s/.test(value)) return setError(name, alertName, 'Ange både förnamn och efternamn.');
      return setError(name, alertName, '');
    }

    function checkPhone() {
      var digits = cleanPhone(phone.value).replace(/\+/g, '');
      if (!digits) return setError(phone, alertPhone, 'Ange ett telefonnummer vi kan nå dig på.');
      if (digits.length < 7 || digits.length > 15) {
        return setError(phone, alertPhone, 'Numret ser ut att vara ofullständigt. Kontrollera siffrorna.');
      }
      return setError(phone, alertPhone, '');
    }

    name.addEventListener('blur', checkName);
    phone.addEventListener('blur', checkPhone);
    name.addEventListener('input', function () {
      if (name.getAttribute('aria-invalid') === 'true') checkName();
    });
    phone.addEventListener('input', function () {
      if (phone.getAttribute('aria-invalid') === 'true') checkPhone();
    });

    form.addEventListener('submit', function (event) {
      event.preventDefault();
      var okName = checkName();
      var okPhone = checkPhone();

      if (!okName) { name.focus(); return; }
      if (!okPhone) { phone.focus(); return; }

      var button = form.querySelector('button[type="submit"]');
      if (button) {
        button.disabled = true;
        button.textContent = 'Skickar beställningen …';
      }
      window.setTimeout(function () {
        window.location.href = 'success.html';
      }, calmMotion ? 0 : 420);
    });
  }

  /* ---------- Newsletter ---------- */
  function initSignal() {
    var form = document.getElementById('signalForm');
    if (!form) return;
    var field = form.querySelector('#signalMail');
    var status = document.getElementById('signalStatus');

    form.addEventListener('submit', function (event) {
      event.preventDefault();
      var value = field.value.trim();
      if (!/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/.test(value)) {
        field.setAttribute('aria-invalid', 'true');
        status.textContent = 'Kontrollera e-postadressen och försök igen.';
        field.focus();
        return;
      }
      field.setAttribute('aria-invalid', 'false');
      status.textContent = 'Tack. Vi har noterat din adress för kommande utskick.';
      form.reset();
    });
  }

  /* ---------- Footer year ---------- */
  function initYear() {
    var slots = document.querySelectorAll('[data-year]');
    var year = String(new Date().getFullYear());
    Array.prototype.forEach.call(slots, function (slot) {
      slot.textContent = year;
    });
  }

  ready(function () {
    initHeader();
    initNav();
    initReveal();
    initQueries();
    initConsent();
    initOrderForm();
    initSignal();
    initYear();
  });
})();
