(function () {
  function slugify(text) {
    return text
      .toString()
      .toLowerCase()
      .trim()
      .replace(/\s+/g, '-')           // Replace spaces with -
      .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
      .replace(/\-\-+/g, '-');        // Replace multiple - with single -
  }

  function setFields(title) {
    const titleInput = document.querySelector('[name$="-title"]');
    const slugInput = document.querySelector('[name$="-slug"]');

    if (titleInput && !titleInput.value) {
      titleInput.value = title;
    }

    if (slugInput && !slugInput.value) {
      slugInput.value = slugify(title);
    }
  }

  function attachEventListeners() {
    const serviceSelect = document.querySelector('select[name$="-service"]');
    const documentSelect = document.querySelector('select[name$="-document"]');
    const pageSelect = document.querySelector('select[name$="-page"]');

    if (serviceSelect) {
      serviceSelect.addEventListener('change', () => {
        const selectedOption = serviceSelect.selectedOptions[0];
        if (selectedOption && selectedOption.text) {
          setFields(selectedOption.text);
        }
      });
    }

    if (documentSelect) {
      documentSelect.addEventListener('change', () => {
        const selectedOption = documentSelect.selectedOptions[0];
        if (selectedOption && selectedOption.text) {
          setFields(selectedOption.text);
        }
      });
    }

    if (pageSelect) {
      pageSelect.addEventListener('change', () => {
        const selectedOption = pageSelect.selectedOptions[0];
        if (selectedOption && selectedOption.text) {
          setFields(selectedOption.text);
        }
      });
    }
  }

  document.addEventListener('DOMContentLoaded', attachEventListeners);
})();
