document.addEventListener('DOMContentLoaded', function () {
  let pendingDeleteForm = null;
  const sidebarToggle = document.getElementById('sidebarToggle');
  const savedSidebarState = localStorage.getItem('sidebarCollapsed');

  if (savedSidebarState === '1') {
    document.body.classList.add('sidebar-collapsed');
  }

  if (sidebarToggle) {
    sidebarToggle.addEventListener('click', function () {
      const collapsed = document.body.classList.toggle('sidebar-collapsed');
      localStorage.setItem('sidebarCollapsed', collapsed ? '1' : '0');
    });
  }

  const searchInputs = document.querySelectorAll('[data-table-search]');
  searchInputs.forEach(function (input) {
    const tableId = input.getAttribute('data-table-search');
    const table = document.getElementById(tableId);
    if (!table) return;

    input.addEventListener('input', function () {
      const q = this.value.toLowerCase().trim();
      const rows = table.tBodies[0] ? table.tBodies[0].rows : table.querySelectorAll('tbody tr');
      Array.from(rows).forEach(function (row) {
        if (row.id === 'rowEmptyUser') return;
        const text = row.textContent.toLowerCase();
        row.style.display = text.includes(q) ? 'table-row' : 'none';
      });
      if (typeof updateBulkSiswaState === 'function') {
        updateBulkSiswaState();
      }
    });
  });

  document.querySelectorAll('[data-modal-open]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const id = this.getAttribute('data-modal-open');
      const modal = document.getElementById(id);
      if (modal) modal.classList.add('show');
    });
  });

  document.querySelectorAll('[data-modal-close]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      const modal = this.closest('.modal-overlay');
      if (modal) modal.classList.remove('show');
    });
  });

  document.querySelectorAll('.modal-overlay').forEach(function (overlay) {
    overlay.addEventListener('click', function (e) {
      if (e.target === overlay) overlay.classList.remove('show');
    });
  });

  const deleteModal = document.getElementById('modalDeleteConfirm');
  const deleteModalTitle = document.getElementById('deleteConfirmTitle');
  const deleteModalText = document.getElementById('deleteConfirmText');
  const deleteCancelBtn = document.getElementById('deleteConfirmCancel');
  const deleteSubmitBtn = document.getElementById('deleteConfirmSubmit');

  document.querySelectorAll('form[data-confirm-delete]').forEach(function (form) {
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      pendingDeleteForm = form;

      if (form.id === 'formBulkDelete') {
        const count = document.querySelectorAll('.row-check-siswa:checked').length;
        if (count === 0) {
          pendingDeleteForm = null;
          return;
        }
        if (deleteModalTitle) {
          deleteModalTitle.textContent = 'Hapus Data Siswa Terpilih?';
        }
        if (deleteModalText) {
          deleteModalText.textContent =
            count + ' data siswa akan dihapus. Data yang dihapus tidak dapat dikembalikan.';
        }
      } else {
        if (deleteModalTitle) {
          deleteModalTitle.textContent =
            form.getAttribute('data-confirm-title') || 'Hapus Data Siswa?';
        }
        if (deleteModalText) {
          deleteModalText.textContent =
            form.getAttribute('data-confirm-text') || 'Data yang dihapus tidak dapat dikembalikan.';
        }
      }

      if (deleteModal) {
        deleteModal.classList.add('show');
      }
    });
  });

  if (deleteCancelBtn) {
    deleteCancelBtn.addEventListener('click', function () {
      pendingDeleteForm = null;
      if (deleteModal) {
        deleteModal.classList.remove('show');
      }
    });
  }

  if (deleteSubmitBtn) {
    deleteSubmitBtn.addEventListener('click', function () {
      if (!pendingDeleteForm) return;
      const form = pendingDeleteForm;
      pendingDeleteForm = null;
      if (deleteModal) {
        deleteModal.classList.remove('show');
      }
      form.submit();
    });
  }

  if (deleteModal) {
    deleteModal.addEventListener('click', function (e) {
      if (e.target === deleteModal) {
        pendingDeleteForm = null;
      }
    });
  }

  const checkAllSiswa = document.getElementById('checkAllSiswa');
  const bulkDeleteBtn = document.getElementById('btnBulkDelete');
  const tableSiswa = document.getElementById('tableSiswa');

  function allRowChecks() {
    return tableSiswa
      ? Array.from(tableSiswa.querySelectorAll('.row-check-siswa'))
      : Array.from(document.querySelectorAll('.row-check-siswa'));
  }

  function visibleRowChecks() {
    return allRowChecks().filter(function (cb) {
      const row = cb.closest('tr');
      return row && row.style.display !== 'none';
    });
  }

  window.updateBulkSiswaState = function () {
    const all = allRowChecks();
    const visible = visibleRowChecks();
    const checkedAll = all.filter(function (cb) {
      return cb.checked;
    });
    const checkedVisible = visible.filter(function (cb) {
      return cb.checked;
    });

    if (bulkDeleteBtn) {
      bulkDeleteBtn.disabled = checkedAll.length === 0;
    }

    if (checkAllSiswa) {
      checkAllSiswa.checked = all.length > 0 && checkedAll.length === all.length;
      checkAllSiswa.indeterminate =
        checkedAll.length > 0 && checkedAll.length < all.length;
    }
  };

  if (tableSiswa) {
    tableSiswa.addEventListener('change', function (e) {
      const target = e.target;
      if (!(target instanceof HTMLInputElement) || target.type !== 'checkbox') return;

      if (target.id === 'checkAllSiswa') {
        allRowChecks().forEach(function (cb) {
          cb.checked = target.checked;
        });
        updateBulkSiswaState();
        return;
      }

      if (target.classList.contains('row-check-siswa')) {
        updateBulkSiswaState();
      }
    });
  }

  updateBulkSiswaState();

  function getFieldLabel(field) {
    if (field.id) {
      const label = document.querySelector('label[for="' + field.id + '"]');
      if (label) {
        return label.textContent.replace(/\s*\([^)]*\)\s*/g, '').trim();
      }
    }
    const group = field.closest('.form-group');
    if (group) {
      const label = group.querySelector('label');
      if (label) {
        return label.textContent.replace(/\s*\([^)]*\)\s*/g, '').trim();
      }
    }
    return 'Field';
  }

  function isFieldInvalid(field) {
    if (field.disabled || field.type === 'hidden') return false;

    if (field.hasAttribute('required')) {
      if (field.type === 'checkbox' || field.type === 'radio') {
        if (!field.checked) return true;
      } else if (field.tagName === 'SELECT') {
        if (field.value === '') return true;
      } else if (String(field.value).trim() === '') {
        return true;
      }
    }

    if (field.type === 'number' && String(field.value).trim() !== '') {
      const min = field.getAttribute('min');
      if (min !== null && Number(field.value) < Number(min)) return true;
    }

    return false;
  }

  function findFirstInvalidField(form) {
    const fields = form.querySelectorAll('input, select, textarea');
    for (let i = 0; i < fields.length; i++) {
      if (isFieldInvalid(fields[i])) {
        return fields[i];
      }
    }
    return null;
  }

  function clearFormValidation(form) {
    form.querySelectorAll('.is-invalid').forEach(function (el) {
      el.classList.remove('is-invalid');
    });
    form.querySelectorAll('.form-validation-alert').forEach(function (alert) {
      alert.remove();
    });
  }

  function showFormValidationError(form, field) {
    field.classList.add('is-invalid');
    field.focus({ preventScroll: false });

    let message = getFieldLabel(field) + ' wajib diisi.';
    if (field.hasAttribute('required') && String(field.value).trim() !== '' && field.type === 'number') {
      message = getFieldLabel(field) + ' tidak valid.';
    }

    const container = form.querySelector('.modal-body') || form;
    let box = container.querySelector('.form-validation-alert');
    if (!box) {
      box = document.createElement('div');
      box.className = 'alert alert-danger form-validation-alert';
      container.insertBefore(box, container.firstChild);
    }
    box.textContent = message;
    box.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  }

  document.querySelectorAll('input, select, textarea').forEach(function (field) {
    field.addEventListener('invalid', function (e) {
      e.preventDefault();
    });
  });

  document.querySelectorAll('form').forEach(function (form) {
    if (form.hasAttribute('data-skip-validation')) return;

    form.setAttribute('novalidate', 'novalidate');

    form.addEventListener(
      'submit',
      function (e) {
        if (form.hasAttribute('data-confirm-delete')) return;

        clearFormValidation(form);

        const invalidField = findFirstInvalidField(form);
        if (invalidField) {
          e.preventDefault();
          e.stopPropagation();
          showFormValidationError(form, invalidField);
        }
      },
      true
    );

    form.querySelectorAll('input, select, textarea').forEach(function (field) {
      field.addEventListener('input', function () {
        field.classList.remove('is-invalid');
        const container = form.querySelector('.modal-body') || form;
        const alert = container.querySelector('.form-validation-alert');
        if (alert) alert.remove();
      });
      field.addEventListener('change', function () {
        field.classList.remove('is-invalid');
        const container = form.querySelector('.modal-body') || form;
        const alert = container.querySelector('.form-validation-alert');
        if (alert) alert.remove();
      });
    });
  });
});

function openModal(id) {
  const modal = document.getElementById(id);
  if (modal) modal.classList.add('show');
}

function closeModal(id) {
  const modal = document.getElementById(id);
  if (modal) modal.classList.remove('show');
}
