(() => {
  const slug = (value) => value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
  document.querySelectorAll('[data-dialog]').forEach((button) => button.addEventListener('click', () => {
    const dialog = document.getElementById(button.dataset.dialog);
    if (dialog && !button.disabled) dialog.showModal();
  }));
  document.querySelectorAll('[data-close]').forEach((button) => button.addEventListener('click', () => button.closest('dialog')?.close()));
  document.querySelectorAll('.studio-dialog').forEach((dialog) => dialog.addEventListener('click', (event) => {
    if (event.target === dialog) dialog.close();
  }));
  const source = document.querySelector('[data-slug-source]');
  const target = document.querySelector('[data-slug-target]');
  const table = document.querySelector('[data-table-target]');
  source?.addEventListener('input', () => {
    const value = slug(source.value);
    if (target && (!target.dataset.touched || !target.value)) target.value = value;
    if (table && (!table.dataset.touched || !table.value)) table.value = value.endsWith('s') ? value : value + 's';
  });
  target?.addEventListener('input', () => target.dataset.touched = '1');
  table?.addEventListener('input', () => table.dataset.touched = '1');
  const fieldSource = document.querySelector('[data-field-source]');
  const fieldTarget = document.querySelector('[data-field-target]');
  fieldSource?.addEventListener('input', () => { if (fieldTarget && (!fieldTarget.dataset.touched || !fieldTarget.value)) fieldTarget.value = slug(fieldSource.value); });
  fieldTarget?.addEventListener('input', () => fieldTarget.dataset.touched = '1');
  document.querySelectorAll('[data-tab]').forEach((button) => button.addEventListener('click', () => {
    document.querySelectorAll('[data-tab]').forEach((item) => item.classList.toggle('active', item === button));
    document.querySelectorAll('[data-tab-panel]').forEach((panel) => panel.classList.toggle('active', panel.dataset.tabPanel === button.dataset.tab));
  }));
})();
