/**
 * Page: SystemCore Product Form (Create/Edit)
 */

$(function () {
  'use strict';

  $.ajaxSetup({
    headers: {
      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
  });

  // Initialize Select2
  $('.select2').select2({
    allowClear: true
  });

  // Initialize Dropzone for product image upload
  if (document.querySelector('#productImageDropzone')) {
    Dropzone.autoDiscover = false;
    const dropzone = new Dropzone('#productImageDropzone', {
      url: pageData.urls.uploadImage,
      maxFilesize: 2,
      acceptedFiles: 'image/*',
      maxFiles: 1,
      addRemoveLinks: true,
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      },
      init: function () {
        // If editing and product already has an image, show it
        if (typeof pageData.product !== 'undefined' && pageData.product.image) {
          const mockFile = { name: 'current-image', size: 12345 };
          this.displayExistingFile(mockFile, pageData.product.image);
        }
      },
      success: function (file, response) {
        $('#product_image_path').val(response.path);
      },
      removedfile: function (file) {
        $('#product_image_path').val('');
        file.previewElement.remove();
      }
    });
  }
});
