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

  console.log('app account_image_edit ready')

  let user = JSON.parse(localStorage.getItem('t01_user'));

  console.log(user)

  if (user.data.url_img) {	

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

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

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

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

  }

})



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

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

  const reader = new FileReader();

  reader.onload = function(event) {

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

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

      .find('label')

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

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

  };

  if (file) {

    reader.readAsDataURL(file);

  }

});



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

  var view = app.views.current

  let user = JSON.parse(localStorage.getItem('t01_user'));

  let tbl='users';



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

  let profileBase64 = null

  if (profile_image) {

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

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

      const reader = new FileReader()

      reader.readAsDataURL(profile_image)

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

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

    })

  }

  if (!profileBase64) {

    return

  }

  try {

    app.preloader.show()

    let img_data=profileBase64;

    let id=user.uuid;

    let req = {

      id,tbl,img_data

    }

    let promises = []

    if (profileBase64) {

    //console.log(req)

      promises.push(upload_image(req))

    }

    const responses = await Promise.all(promises)

    app.preloader.hide()

    if (responses.every(response => response && response.success)) {

      showToast('Images updated successfully', 'Success')

      return

    }

    if (responses.some(response => response && !response.success)) {

      throw new Error('Failed to update images')

    }

  } catch (error) {

    app.preloader.hide()

    app.notification.create({

      titleRightText: 'now',

      subtitle: 'Oops, something went wrong',

      text: error.message || 'Failed to update images',

    }).open()

  }

})