$(document).on('click', '.image_upload', async function (e) {

  const image= e.target.closest('.image_upload').dataset.image;

  setTimeout(() => {

    //console.log(image)

    if (image) {

      $$('input[name="item_image"]').closest('.custom-file-upload').find('label').css('background-image', `url('${image}')`)

      $$('input[name="item_image"]').closest('.custom-file-upload').find('label').css('background-size', 'contain')

      $$('input[name="item_image"]').closest('.custom-file-upload').find('label').css('background-position', 'center')

      $$('input[name="item_image"]').closest('.custom-file-upload').find('label').css('background-repeat', 'no-repeat')

    }

  }, 300)    

})



$(document).on('page:beforein', '.page[data-name="image_upload"]', async function(e) {

  console.log('app image_upload ready')

  var tbl = e.detail.route.params.cat;

  var id = e.detail.route.params.id;

  console.log(id + ', ' + tbl);  

  var strHtml = `

<div class="custom-file-upload item" id="fileUpload">

  <input type="hidden" id="a8_id" value="` + id + `">

  <input type="hidden" id="a8_tbl" value="` + tbl + `">

  <input type="file" id="fileuploadInput" name="item_image" />

  <label for="fileuploadInput">

  </label>

</div>

<div data-lang="tap_to_upload" class="centered-text mb-15">${text.tap_to_upload}</div>

<div class="centered-text">

  <a href="#" id="image_upload_button" data-lang="save" class="btn btn-primary fw-700">${text.save}</a>

</div>`;

  $$("#image_upload_content").html(strHtml);  

});



$(document).on('change', 'input#fileuploadInput', function(e) {

  const file = e.target.files[0]

  const reader = new FileReader()

  reader.onload = function(e) {

    document.querySelector('.custom-file-upload label').style.backgroundImage = `url('${e.target.result}')`

    document.querySelector('.custom-file-upload label').style.backgroundSize = 'cover'

  }

  reader.readAsDataURL(file)

})



$(document).on('change', 'input[name="item_image"]', function(e) {

  const file = e.target.files[0];

  const reader = new FileReader();

  reader.onload = function(event) {

    //console.log($('.custom-file-upload.item'));

    $('.custom-file-upload.item')

      .find('label')

      .css('background-image', `url('${event.target.result}')`)

      .css('background-size', 'cover');

  };

  if (file) {

    reader.readAsDataURL(file);

  }

});



$$(document).on('click', '#image_upload_button', async function() {

  var view = app.views.current

  const id = $('#a8_id').val();

  const tbl = $('#a8_tbl').val();

  const item_image = $('input[name="item_image"]').prop('files')[0]

  let itemImgBase64 = null

  if (item_image) {

    // Wrap the FileReader in a Promise to wait for it to complete

    itemImgBase64 = await new Promise((resolve, reject) => {

      const reader = new FileReader()

      reader.readAsDataURL(item_image)

      reader.onload = () => resolve(reader.result)

      reader.onerror = () => reject(new Error('Failed to read image as base64'))

    })

    //console.log(itemImgBase64)

  }

  if (itemImgBase64) {

    let img_data= itemImgBase64;

    let req = {

      id,tbl,img_data

    }

    try {

      app.preloader.show()

      let promises = [];

      if (req) {

        console.log(req)  

        promises.push(image_upload(req))

      }

      const responses = await Promise.all(promises)

      app.preloader.hide()

    } catch (error) {

      app.preloader.hide()

      app.dialog.alert(res.message, 'Upload Image Error');

    }

  }

});