'use strict';

// searchToggler keyboard shortcut
const searchToggler = document.querySelectorAll('[data-search-toggler]');
searchToggler.forEach((item) => {
	let userAgentData = navigator?.userAgentData?.platform || navigator?.platform || 'unknown';

	if (userAgentData == 'macOS') {
		item.innerText = `⌘ + K`
	} else {
		item.innerText = `Ctrl + K`
	}
});

// Navbar fixed
window.onscroll = function () {
	if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
		document.querySelector(".navigation").classList.add("nav-bg");
	} else {
		document.querySelector(".navigation").classList.remove("nav-bg");
	}
};

// masonry
window.onload = function () {
	let masonryWrapper = document.querySelector('.masonry-wrapper');
	// if masonryWrapper is not null, then initialize masonry
	if (masonryWrapper) {
		let masonry = new Masonry(masonryWrapper, {
			columnWidth: 1
		});
	}
};

// copy to clipboard
let blocks = document.querySelectorAll("pre");
blocks.forEach((block) => {
  if (navigator.clipboard) {
    let button = document.createElement("span");
    button.innerText = "copy";
    button.className = "copy-to-clipboard";
    block.appendChild(button);
    button.addEventListener("click", async () => {
      await copyCode(block, button);
    });
  }
});
async function copyCode(block, button) {
  let code = block.querySelector("code");
  let text = code.innerText;
  await navigator.clipboard.writeText(text);
  button.innerText = "copied";
  setTimeout(() => {
    button.innerText = "copy";
  }, 700);
}

document.addEventListener('DOMContentLoaded', function () {
  const form = document.getElementById('cta-lead-form');
  const emailInput = document.getElementById('cta-email');
  const messageEl = document.getElementById('cta-message');
  const submitBtn = document.getElementById('cta-submit');

  if (!form) {
    console.warn("Form not found");
    return;
  }

  form.addEventListener('submit', function (e) {
    e.preventDefault();

    const email = emailInput.value.trim();
    messageEl.textContent = '';

    if (!email) {
      messageEl.textContent = 'Vul alstublieft uw e-mailadres in.';
      return;
    }

    submitBtn.disabled = true;
    submitBtn.textContent = 'Versturen…';

    fetch('https://crm.start-it.nl/api/v1/LeadCapture/f802fa2121e89066c15f1d31cf74fad0', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ emailAddress: email })
    })
    .then(function (res) {
      if (!res.ok) throw new Error("Niet-ok: " + res.status);

      // Succes!
      emailInput.value = '';
      messageEl.textContent = 'U ontvangt een bericht zodra de website live is.';
    })
    .catch(function (err) {
      console.error(err);
      messageEl.textContent = 'Er ging iets mis bij het versturen. Probeer het later opnieuw.';
    })
    .finally(function () {
      submitBtn.disabled = false;
      submitBtn.textContent = 'Verzonden';
    });
  });
});