'use strict';

/*
 * Morgengry Psykologpraksis, script.js
 *
 * Class and id contract with style.css (names come from the markup):
 *   html.js                      set immediately, so CSS can hide .reveal pending reveal
 *   .reveal / .timeline / .timeline__step
 *                                receive `.visible` once when they enter the viewport
 *   .ck-accordion__item          receives `.is-open` (also on trigger and panel)
 *   .ck-accordion__panel         `inert` while closed, `.is-open` while open
 *   .ck-field                    receives `.ck-field--error` while its input is invalid
 *   .ck-field__error             uses `hidden` as its closed state; JS removes the attribute
 *   #form-status                 receives `.is-visible` when it carries a message
 *   .scroll-to-top               receives `.visible` after the page has scrolled 400px
 *
 * The navigation (scroll state, hamburger, active link) is scaffold-owned and
 * is deliberately not handled here.
 */

document.documentElement.classList.add('js');

(function () {
  var prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  /* ---------------------------------------------------------------
     Scroll reveal
  --------------------------------------------------------------- */
  function initReveal() {
    var revealTargets = Array.prototype.slice.call(
      document.querySelectorAll('.reveal, .timeline, .timeline__step')
    );

    if (prefersReducedMotion || !('IntersectionObserver' in window)) {
      revealTargets.forEach(function (el) {
        el.classList.add('visible');
      });
      return;
    }

    var revealObserver = new IntersectionObserver(
      function (entries, observer) {
        entries.forEach(function (entry) {
          if (!entry.isIntersecting) {
            return;
          }
          entry.target.classList.add('visible');
          observer.unobserve(entry.target);
        });
      },
      { threshold: 0.15, rootMargin: '0px 0px -5% 0px' }
    );

    revealTargets.forEach(function (el) {
      revealObserver.observe(el);
    });
  }

  /* ---------------------------------------------------------------
     Accordion (FAQ): single open, aria-expanded tracks what is on screen
  --------------------------------------------------------------- */
  function initAccordion() {
    var accordion = document.querySelector('.ck-accordion');
    if (!accordion) {
      return;
    }

    var triggers = Array.prototype.slice.call(accordion.querySelectorAll('.ck-accordion__trigger'));
    if (!triggers.length) {
      console.error('[accordion] .ck-accordion__trigger not found inside .ck-accordion');
      return;
    }

    var entries = [];
    triggers.forEach(function (trigger) {
      var item = trigger.closest('.ck-accordion__item');
      var panel = document.getElementById(trigger.getAttribute('aria-controls') || '');
      if (!item || !panel) {
        console.error('[accordion] missing item or panel for trigger #' + trigger.id);
        return;
      }
      entries.push({ trigger: trigger, item: item, panel: panel });
    });

    function setOpen(entry, open) {
      entry.trigger.setAttribute('aria-expanded', open ? 'true' : 'false');
      entry.item.classList.toggle('is-open', open);
      entry.trigger.classList.toggle('is-open', open);
      entry.panel.classList.toggle('is-open', open);
      if (open) {
        entry.panel.removeAttribute('hidden');
      }
      if (open) {
        entry.panel.removeAttribute('inert');
      } else {
        entry.panel.setAttribute('inert', '');
      }
    }

    entries.forEach(function (entry) {
      setOpen(entry, false);
      entry.trigger.addEventListener('click', function () {
        var willOpen = entry.trigger.getAttribute('aria-expanded') !== 'true';
        entries.forEach(function (other) {
          if (other !== entry) {
            setOpen(other, false);
          }
        });
        setOpen(entry, willOpen);
      });
    });
  }

  /* ---------------------------------------------------------------
     Scroll-to-top button (site-wide, no page gating)
  --------------------------------------------------------------- */
  function findScrollTopButtons() {
    var found = Array.prototype.slice.call(
      document.querySelectorAll(
        '.scroll-to-top, .scroll-top, .scrolltop, .back-to-top, .to-top, .scroll-up, ' +
          '#scroll-to-top, #scroll-top, #back-to-top, #to-top, #scrollTop, #scrollToTop, ' +
          '[data-scroll-to-top], [data-scroll-top], [data-back-to-top]'
      )
    );
    if (found.length) {
      return found;
    }

    /* Fallback: match a button or link whose accessible name says "to the top". */
    var labelPattern = /(til\s*toppen|til\s*topp|tilbake\s*til\s*topp|to\s*top|back\s*to\s*top|scroll\s*(to\s*)?top|scroll\s*up)/i;
    return Array.prototype.slice
      .call(document.querySelectorAll('button, a[href="#"], a[href="#top"]'))
      .filter(function (el) {
        var label = (el.getAttribute('aria-label') || '') + ' ' + (el.getAttribute('title') || '');
        return labelPattern.test(label);
      });
  }

  function initScrollToTop() {
    var buttons = findScrollTopButtons();
    if (!buttons.length) {
      return;
    }

    var threshold = 400;

    function currentScroll() {
      return window.pageYOffset || window.scrollY || document.documentElement.scrollTop || 0;
    }

    function update() {
      var show = currentScroll() > threshold;
      buttons.forEach(function (button) {
        button.classList.toggle('visible', show);
      });
    }

    window.addEventListener('scroll', update, { passive: true });
    update();

    buttons.forEach(function (button) {
      button.addEventListener('click', function (event) {
        event.preventDefault();
        window.scrollTo({ top: 0, behavior: 'smooth' });
      });
    });
  }

  /* ---------------------------------------------------------------
     Contact form: validation, psychologist preselect, mailto submit
  --------------------------------------------------------------- */
  function initContactForm() {
    var form = document.getElementById('contact-form');
    if (!form) {
      return;
    }

    var submitButton = document.getElementById('contact-submit');
    var statusBox = document.getElementById('form-status');
    var nameInput = document.getElementById('navn');
    var emailInput = document.getElementById('epost');
    var phoneInput = document.getElementById('telefon');
    var psychologistSelect = document.getElementById('psykolog');
    var messageInput = document.getElementById('henvendelse');

    if (!nameInput || !emailInput || !phoneInput || !submitButton) {
      console.error(
        '[contact-form] required fields (#navn, #epost, #telefon, #contact-submit) not found'
      );
      return;
    }

    var submitLabel = submitButton.textContent;
    var resetTimer = null;

    /* Preselect psychologist from ?psykolog=... */
    if (psychologistSelect) {
      var wanted = new URLSearchParams(window.location.search).get('psykolog');
      if (wanted) {
        var wantedLower = wanted.trim().toLowerCase();
        Array.prototype.slice.call(psychologistSelect.options).forEach(function (option) {
          if (
            option.value.trim().toLowerCase() === wantedLower ||
            option.textContent.trim().toLowerCase() === wantedLower
          ) {
            psychologistSelect.value = option.value;
          }
        });
      }
    }

    function errorFor(input) {
      return document.getElementById(input.id + '-error');
    }

    function setError(input, message) {
      var error = errorFor(input);
      var wrapper = input.closest('.ck-field');
      input.setAttribute('aria-invalid', 'true');
      if (wrapper) {
        wrapper.classList.add('ck-field--error');
      }
      if (error) {
        error.textContent = message;
        error.removeAttribute('hidden');
        input.setAttribute('aria-describedby', error.id);
      }
    }

    function clearError(input) {
      var error = errorFor(input);
      var wrapper = input.closest('.ck-field');
      input.removeAttribute('aria-invalid');
      if (wrapper) {
        wrapper.classList.remove('ck-field--error');
      }
      if (error) {
        error.textContent = '';
        error.setAttribute('hidden', '');
      }
    }

    function validate() {
      var firstInvalid = null;

      var nameValue = nameInput.value.trim();
      if (!nameValue) {
        setError(nameInput, 'Skriv inn navnet ditt.');
        firstInvalid = firstInvalid || nameInput;
      } else {
        clearError(nameInput);
      }

      var emailValue = emailInput.value.trim();
      if (!emailValue) {
        setError(emailInput, 'Skriv inn e-postadressen din.');
        firstInvalid = firstInvalid || emailInput;
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailValue)) {
        setError(emailInput, 'Skriv inn en gyldig e-postadresse.');
        firstInvalid = firstInvalid || emailInput;
      } else {
        clearError(emailInput);
      }

      var phoneValue = phoneInput.value.trim();
      var phoneDigits = phoneValue.replace(/\D/g, '');
      if (!phoneValue) {
        setError(phoneInput, 'Skriv inn telefonnummeret ditt.');
        firstInvalid = firstInvalid || phoneInput;
      } else if (phoneDigits.length < 8) {
        setError(phoneInput, 'Skriv inn et gyldig telefonnummer.');
        firstInvalid = firstInvalid || phoneInput;
      } else {
        clearError(phoneInput);
      }

      return firstInvalid;
    }

    [nameInput, emailInput, phoneInput].forEach(function (input) {
      input.addEventListener('input', function () {
        if (input.getAttribute('aria-invalid') === 'true') {
          clearError(input);
        }
      });
    });

    function selectedMeetingType() {
      var checked = form.querySelector('input[type="radio"]:checked');
      if (!checked) {
        return 'Ikke oppgitt';
      }
      var label = checked.id ? form.querySelector('label[for="' + checked.id + '"]') : null;
      var text = label ? label.textContent.trim() : '';
      return text || checked.value;
    }

    function selectedPsychologist() {
      if (!psychologistSelect) {
        return 'Ingen preferanse';
      }
      var option = psychologistSelect.options[psychologistSelect.selectedIndex];
      return option ? option.textContent.trim() : 'Ingen preferanse';
    }

    function buildMailto() {
      var name = nameInput.value.trim();
      var lines = [
        'Navn: ' + name,
        'E-post: ' + emailInput.value.trim(),
        'Telefon: ' + phoneInput.value.trim(),
        'Foretrukket psykolog: ' + selectedPsychologist(),
        'Video eller oppmøte: ' + selectedMeetingType(),
        '',
        'Kort om hva jeg ønsker hjelp med:',
        messageInput && messageInput.value.trim() ? messageInput.value.trim() : '(ikke oppgitt)',
      ];
      var subject = 'Henvendelse fra nettsiden – ' + name;
      return (
        'mailto:post@morgengry.no' +
        '?subject=' +
        encodeURIComponent(subject) +
        '&body=' +
        encodeURIComponent(lines.join('\r\n'))
      );
    }

    function showStatus(message) {
      if (!statusBox) {
        return;
      }
      statusBox.textContent = message;
      statusBox.removeAttribute('hidden');
      statusBox.classList.add('is-visible');
    }

    function restoreButton() {
      submitButton.disabled = false;
      submitButton.textContent = submitLabel;
      resetTimer = null;
    }

    form.addEventListener('submit', function (event) {
      if (form.getAttribute('action')) {
        return;
      }
      event.preventDefault();

      if (resetTimer !== null) {
        return;
      }

      var firstInvalid = validate();
      if (firstInvalid) {
        firstInvalid.focus();
        return;
      }

      submitButton.disabled = true;
      submitButton.textContent = 'Åpner e-postprogrammet ditt…';
      showStatus(
        'Skjemaet åpner e-postprogrammet ditt. Hvis ingenting skjer, kan du skrive til post@morgengry.no eller ringe 69 30 22 80.'
      );

      resetTimer = window.setTimeout(restoreButton, 2000);
      window.location.href = buildMailto();
    });
  }

  /* ---------------------------------------------------------------
     Init
  --------------------------------------------------------------- */
  function init() {
    initScrollToTop();
    initReveal();
    initAccordion();
    initContactForm();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
/* ============================================================
   NAVIGATION SCAFFOLD — DO NOT EDIT (managed by Orchestra)
   ============================================================ */
(function () {
  var nav = document.getElementById('ns-nav');
  var linksContainer = document.getElementById('ns-links');
  var burger = document.getElementById('ns-hamburger');
  var overlay = document.getElementById('ns-overlay');
  if (!nav || !linksContainer || !burger) return;

  var isOpen = false;

  function openMenu() {
    isOpen = true;
    linksContainer.classList.add('open');
    if (overlay) {
      overlay.classList.add('open');
      overlay.setAttribute('aria-hidden', 'false');
    }
    burger.setAttribute('aria-expanded', 'true');
    document.body.style.overflow = 'hidden';
  }

  function closeMenu() {
    isOpen = false;
    linksContainer.classList.remove('open');
    if (overlay) {
      overlay.classList.remove('open');
      overlay.setAttribute('aria-hidden', 'true');
    }
    burger.setAttribute('aria-expanded', 'false');
    document.body.style.overflow = '';
  }

  function toggleMenu() {
    if (isOpen) closeMenu();
    else openMenu();
  }

  // Event listeners
  burger.addEventListener('click', toggleMenu);
  if (overlay) overlay.addEventListener('click', closeMenu);

  linksContainer.querySelectorAll('a').forEach(function (link) {
    link.addEventListener('click', function () {
      if (window.innerWidth <= 768) closeMenu();
    });
  });

  // Keyboard — Escape closes menu
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && isOpen) {
      closeMenu();
      burger.focus();
    }
  });

  // Resize safety — prevents double nav when resizing from mobile to desktop
  window.addEventListener(
    'resize',
    function () {
      if (window.innerWidth > 768 && isOpen) {
        closeMenu();
      }
    },
    { passive: true }
  );

  // Scroll effect — transparent to solid background
  window.addEventListener(
    'scroll',
    function () {
      nav.classList.toggle('scrolled', window.scrollY > 80);
    },
    { passive: true }
  );

  // Active link highlighting via IntersectionObserver
  var sections = [];
  linksContainer.querySelectorAll('a[href^="#"]').forEach(function (a) {
    var id = a.getAttribute('href').slice(1);
    var el = document.getElementById(id);
    if (el) sections.push({ el: el, link: a });
  });
  if (sections.length && 'IntersectionObserver' in window) {
    var obs = new IntersectionObserver(
      function (entries) {
        entries.forEach(function (entry) {
          if (entry.isIntersecting) {
            linksContainer.querySelectorAll('a').forEach(function (a) {
              a.classList.remove('active');
            });
            sections.forEach(function (s) {
              if (s.el === entry.target) s.link.classList.add('active');
            });
          }
        });
      },
      { rootMargin: '-20% 0px -70% 0px', threshold: 0 }
    );
    sections.forEach(function (s) {
      obs.observe(s.el);
    });
  }
})();

/* ============================================================
   NAV CONTROLS SCAFFOLD — DO NOT EDIT (managed by Orchestra)
   ------------------------------------------------------------
   Wires the optional right-slot controls (search trigger, theme
   toggle) to their behaviour. Both branches are guarded by an
   element-existence check, so this block is inert on builds that
   don't opt in to controls.

   TRIGGERED-COMPONENT INVARIANT (see core/nav_scaffold.py docstring):
   • #ns-search-modal defaults to `hidden` + CSS `display:none`.
   • Open state is set ONLY here, in response to a user click.
   • Close paths: backdrop click, close button, Escape key.
   • Re-opening focus returns to the trigger for keyboard users.

   Do not duplicate this logic in script.js. Do not pre-open the
   modal in markup. Open state belongs to the user, not the template.
   ============================================================ */
(function () {
  // ── Search modal ───────────────────────────────────────────────────────
  var trigger = document.getElementById('ns-search-trigger');
  var modal = document.getElementById('ns-search-modal');
  if (trigger && modal) {
    var input = modal.querySelector('#ns-search-input');
    var closers = modal.querySelectorAll('[data-ns-search-close]');

    // Function EXPRESSIONS, not declarations. A `function foo() {}` inside an
    // `if` block is `no-inner-declarations`, and this template shipped three of
    // them into every static_site and nye_eventyr build — where the Developer
    // is forbidden to fix them, because this is the reserved `ns-` namespace.
    // Measured on marstrand-bokbinderi: all 6 of its eslint errors were in this
    // file's output, the build was filed `partial` for them, and a --bugfix run
    // then burned all three of its capped attempts on code it may not touch.
    // Both are declared before the listeners below that call them, so the
    // behaviour is identical.
    var openSearch = function () {
      modal.removeAttribute('hidden');
      modal.classList.add('open');
      modal.setAttribute('aria-hidden', 'false');
      trigger.setAttribute('aria-expanded', 'true');
      document.body.style.overflow = 'hidden';
      if (input)
        setTimeout(function () {
          input.focus();
        }, 30);
    };
    var closeSearch = function () {
      modal.classList.remove('open');
      modal.setAttribute('hidden', '');
      modal.setAttribute('aria-hidden', 'true');
      trigger.setAttribute('aria-expanded', 'false');
      document.body.style.overflow = '';
      trigger.focus();
    };

    trigger.addEventListener('click', openSearch);
    closers.forEach(function (el) {
      el.addEventListener('click', closeSearch);
    });
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' && modal.classList.contains('open')) closeSearch();
    });
  }

  // ── Theme toggle ───────────────────────────────────────────────────────
  // Sets `data-theme` on <html>; consumer CSS variables read from that
  // attribute (`:root[data-theme="light"] { ... }`) to recolour the site.
  // Persisted in localStorage so the choice survives reloads.
  var themeBtn = document.getElementById('ns-theme-toggle');
  if (themeBtn) {
    var STORAGE_KEY = 'orch-theme';

    // Expression, not a declaration — see the openSearch note below.
    var applyTheme = function (t) {
      document.documentElement.setAttribute('data-theme', t);
      themeBtn.setAttribute('aria-pressed', t === 'light' ? 'true' : 'false');
    };

    var stored = null;
    try {
      stored = localStorage.getItem(STORAGE_KEY);
    } catch (_) {
      /* storage blocked (private mode / 3rd-party cookies off) */
    }
    applyTheme(stored === 'light' ? 'light' : 'dark');

    themeBtn.addEventListener('click', function () {
      var current = document.documentElement.getAttribute('data-theme');
      var next = current === 'light' ? 'dark' : 'light';
      try {
        localStorage.setItem(STORAGE_KEY, next);
      } catch (_) {
        /* storage blocked: the theme still applies for this page */
      }
      applyTheme(next);
    });
  }
})();
/* END NAVIGATION SCAFFOLD */

/* ============================================================
   NAV PAGE-ACTIVE SCAFFOLD — DO NOT EDIT (managed by Orchestra)
   Multi-page builds: mark the current page's nav link .active by
   matching normalised pathnames. Works under file://, http(s)://,
   index/root, trailing slash, and extension-less routes.
   ============================================================ */
(function () {
  var links = document.getElementById('ns-links');
  if (!links) return;
  function pageKey(p) {
    try {
      p = decodeURIComponent(p || '');
    } catch (_) {
      /* malformed %-escape: fall through with the raw path */
    }
    p = p.split('#')[0].split('?')[0].replace(/\\/g, '/');
    var seg = p.substring(p.lastIndexOf('/') + 1).toLowerCase();
    if (seg === '' || seg === 'index.html' || seg === 'home.html') return 'index.html';
    if (seg.indexOf('.') === -1) seg += '.html';
    return seg;
  }
  var current = pageKey(window.location.pathname || window.location.href);
  links.querySelectorAll('a').forEach(function (a) {
    var href = a.getAttribute('href') || '';
    if (href.charAt(0) === '#') return; // in-page anchor, not a page link
    if (pageKey(href) === current) {
      a.classList.add('active');
      a.setAttribute('aria-current', 'page');
    } else {
      a.classList.remove('active');
      a.removeAttribute('aria-current');
    }
  });
})();
/* END NAV PAGE-ACTIVE SCAFFOLD */