$(() => {
  const language = document.documentElement.lang || 'es-ES';
  // CSRF global para AJAX
  const csrfToken = document.querySelector('meta[name="_csrf"]')?.getAttribute('content');
  const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.getAttribute('content');
  if (csrfToken && csrfHeader) {
    $.ajaxSetup({
      beforeSend: function (xhr) {
        xhr.setRequestHeader(csrfHeader, csrfToken);
      }
    });
  }


  const table = new DataTable('#users-datatable', {
    processing: true,
    serverSide: true,
    orderCellsTop: true,
    pageLength: 50,
    language: { url: '/assets/libs/datatables/i18n/' + language + '.json' },
    responsive: true,
    ajax: {
      url: '/users/datatable',
      method: 'GET',
      data: function (d) {
        d.f_role = $('#search-role').val() || '';   // 'USER' | 'ADMIN' | 'SUPERADMIN' | ''
        d.f_enabled = $('#search-status').val() || '';   // 'true' | 'false' | ''
      }
    },
    order: [[0, 'asc']],
    columns: [
      { data: 'id', name: 'id', orderable: true },
      { data: 'fullName', name: 'fullName', orderable: true },
      { data: 'userName', name: 'userName', orderable: true },
      { data: 'roles', name: 'roleRank' },
      { data: 'enabled', name: 'enabled', searchable: false },
      { data: 'actions', name: 'actions' }
    ],
    columnDefs: [{ targets: -1, orderable: false, searchable: false }]
  });

  table.on("keyup", ".user-filter", function () {
    const colName = $(this).data("col");
    const colIndex = table.settings()[0].aoColumns.findIndex(c => c.name === colName);

    if (colIndex >= 0) {
      table.column(colIndex).search(this.value).draw();
    }
  });

  table.on("change", ".user-filter-select", function () {
    table.draw();
  });

  const modalEl = document.getElementById('userFormModal');
  const modal = bootstrap.Modal.getOrCreateInstance(modalEl);

  // Abrir "Crear"
  $('#addUserButton').on('click', (e) => {
    e.preventDefault();
    $.get('/users/form', function (html) {
      $('#userModalBody').html(html);
      const title = $('#userModalBody #userForm').data('add');
      $('#userFormModal .modal-title').text(title);
      modal.show();
    });
  });

  // Abrir "Editar"
  $(document).on('click', '.btn-edit-user', function (e) {
    e.preventDefault();
    const id = $(this).data('id');
    $.get('/users/form', { id }, function (html) {
      $('#userModalBody').html(html);
      const title = $('#userModalBody #userForm').data('edit');
      $('#userFormModal .modal-title').text(title);
      modal.show();
    });
  });

  // Botón "Eliminar"
  $(document).on('click', '.btn-delete-user', function (e) {
    e.preventDefault();
    const id = $(this).data('id');

    Swal.fire({
      title: window.languageBundle.get(['usuarios.delete.title']) || 'Eliminar usuario',
      html: window.languageBundle.get(['usuarios.delete.text']) || 'Esta acción no se puede deshacer.',
      icon: 'warning',
      showCancelButton: true,
      buttonsStyling: false,
      customClass: {
        confirmButton: 'btn btn-danger w-xs mt-2',
        cancelButton: 'btn btn-light w-xs mt-2'
      },
      confirmButtonText: window.languageBundle.get(['usuarios.delete.button']) || 'Eliminar',
      cancelButtonText: window.languageBundle.get(['app.cancelar']) || 'Cancelar',
    }).then((result) => {
      if (!result.isConfirmed) return;

      $.ajax({
        url: '/users/' + id,
        type: 'DELETE',
        success: function () {
          Swal.fire({
            icon: 'success', title: window.languageBundle.get(['usuarios.delete.ok.title']) || 'Eliminado',
            text: window.languageBundle.get(['usuarios.delete.ok.text']) || 'El usuario ha sido eliminado con éxito.',
            showConfirmButton: true,
            customClass: {
              confirmButton: 'btn btn-secondary w-xs mt-2',
            },
          });
          $('#users-datatable').DataTable().ajax.reload(null, false);
        },
        error: function (xhr) {
          //  usa el mensaje del backend; fallback genérico por si no llega JSON
          const msg = (xhr.responseJSON && xhr.responseJSON.message)
            || 'Error al eliminar el usuario.';
          Swal.fire({ icon: 'error', title: 'No se pudo eliminar', text: msg });
        }
      });
    });
  });


  // Submit del form en el modal
  $(document).on('submit', '#userForm', function (e) {
    e.preventDefault();
    const $form = $(this);

    $.ajax({
      url: $form.attr('action'),
      type: 'POST',               // PUT simulado via _method
      data: $form.serialize(),
      dataType: 'html',
      success: function (html) {
        // Si por cualquier motivo llega 200 con fragmento, lo insertamos igual
        if (typeof html === 'string' && html.indexOf('id="userForm"') !== -1 && html.indexOf('<html') === -1) {
          $('#userModalBody').html(html);
          const isEdit = $('#userModalBody #userForm input[name="_method"][value="PUT"]').length > 0;
          const title = $('#userModalBody #userForm').data(isEdit ? 'edit' : 'add');
          $('#userFormModal .modal-title').text(title);
          return;
        }
        // Éxito real: cerrar y recargar tabla
        modal.hide();
        table.ajax.reload(null, false);
      },
      error: function (xhr) {
        // Con 422 devolvemos el fragmento con errores aquí
        if (xhr.status === 422 && xhr.responseText) {
          $('#userModalBody').html(xhr.responseText);
          const isEdit = $('#userModalBody #userForm input[name="_method"][value="PUT"]').length > 0;
          const title = $('#userModalBody #userForm').data(isEdit ? 'edit' : 'add');
          $('#userFormModal .modal-title').text(title);
          return;
        }
        // Fallback
        $('#userModalBody').html('<div class="p-3 text-danger">Error inesperado.</div>');
      }
    });
  });
});
