(function () {
  // Mobile nav toggle
  var toggle = document.querySelector('.nav-toggle');
  var nav = document.querySelector('.main-nav');
  if (toggle && nav) {
    toggle.addEventListener('click', function () {
      nav.classList.toggle('is-open');
    });
  }

  // ---- Light/dark mode toggle ----
  // The *initial* theme is applied synchronously by a small inline script in
  // <head> (before first paint, to avoid a flash of the wrong theme). This
  // just wires up the button: flips it, persists the choice, updates the label.
  var themeToggle = document.getElementById('themeToggle');
  if (themeToggle) {
    var applyLabel = function () {
      var isDark = document.documentElement.getAttribute('data-theme') === 'dark';
      themeToggle.setAttribute('aria-label', isDark ? 'Switch to light mode' : 'Switch to dark mode');
    };
    applyLabel();
    themeToggle.addEventListener('click', function () {
      var isDark = document.documentElement.getAttribute('data-theme') === 'dark';
      if (isDark) {
        document.documentElement.removeAttribute('data-theme');
      } else {
        document.documentElement.setAttribute('data-theme', 'dark');
      }
      try { localStorage.setItem('yst-theme', isDark ? 'light' : 'dark'); } catch (e) { /* ignore */ }
      applyLabel();
    });
  }

  // Reveal-on-scroll
  var revealEls = document.querySelectorAll('.reveal');
  if ('IntersectionObserver' in window && revealEls.length) {
    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('in');
          io.unobserve(entry.target);
        }
      });
    }, { threshold: 0.15 });
    revealEls.forEach(function (el) { io.observe(el); });
  } else {
    revealEls.forEach(function (el) { el.classList.add('in'); });
  }

  // Active header state on scroll
  var header = document.querySelector('.site-header');
  if (header) {
    window.addEventListener('scroll', function () {
      if (window.scrollY > 40) header.classList.add('is-scrolled');
      else header.classList.remove('is-scrolled');
    }, { passive: true });
  }

  // Current year in footer
  var yearEl = document.getElementById('year');
  if (yearEl) yearEl.textContent = new Date().getFullYear();

  // ---- Contact / quote request form -> real backend (/api/contact) ----
  var form = document.getElementById('quoteForm');
  if (form) {
    var statusEl = document.getElementById('quoteFormStatus');
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      var data = new FormData(form);
      var submitBtn = form.querySelector('button[type="submit"]');
      var payload = {
        name: data.get('name') || '',
        email: data.get('email') || '',
        phone: data.get('phone') || '',
        reason: data.get('service') || '',
        message: data.get('message') || ''
      };
      if (submitBtn) { submitBtn.disabled = true; submitBtn.dataset.label = submitBtn.textContent; submitBtn.textContent = 'Sending…'; }
      if (statusEl) { statusEl.textContent = ''; statusEl.className = 'form-note'; }

      fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
        .then(function (resp) { return resp.json().then(function (body) { return { ok: resp.ok, body: body }; }); })
        .then(function (result) {
          if (!result.ok) throw new Error(result.body.error || 'Something went wrong.');
          form.reset();
          if (statusEl) {
            statusEl.textContent = result.body.message || 'Thank you — your message has been received.';
            statusEl.className = 'form-note form-note-success';
          }
        })
        .catch(function (err) {
          if (statusEl) {
            statusEl.textContent = "Couldn't reach the server — please email info@yst.co.tz directly. (" + err.message + ')';
            statusEl.className = 'form-note form-note-error';
          }
        })
        .finally(function () {
          if (submitBtn) { submitBtn.disabled = false; submitBtn.textContent = submitBtn.dataset.label; }
        });
    });
  }

  // ---- Newsletter signup -> real backend (/api/newsletter) ----
  var nlForm = document.getElementById('newsletterForm');
  if (nlForm) {
    var nlStatus = document.getElementById('newsletterStatus');
    nlForm.addEventListener('submit', function (e) {
      e.preventDefault();
      var email = new FormData(nlForm).get('email');
      fetch('/api/newsletter', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email })
      })
        .then(function (resp) { return resp.json().then(function (body) { return { ok: resp.ok, body: body }; }); })
        .then(function (result) {
          if (!result.ok) throw new Error(result.body.error || 'Something went wrong.');
          nlForm.reset();
          if (nlStatus) { nlStatus.textContent = result.body.message || 'Subscribed!'; nlStatus.className = 'form-note form-note-success'; }
        })
        .catch(function (err) {
          if (nlStatus) { nlStatus.textContent = err.message; nlStatus.className = 'form-note form-note-error'; }
        });
    });
  }

  // ---- Founder / Assistant Director profile toggle ----
  document.querySelectorAll('.about-mark').forEach(function (card) {
    var tabs = card.querySelectorAll('.profile-tab');
    if (!tabs.length) return;
    tabs.forEach(function (tab) {
      tab.addEventListener('click', function () {
        var target = tab.getAttribute('data-profile');
        tabs.forEach(function (t) { t.classList.toggle('active', t === tab); });
        card.querySelectorAll('.profile-panel').forEach(function (panel) {
          panel.classList.toggle('active', panel.getAttribute('data-panel') === target);
        });
      });
    });
  });
})();
