jQuery(($) => {
  let dcatlMediaFrame;

  $('.dcatl-upload-image-button').on('click', (event) => {
    event.preventDefault();

    if (dcatlMediaFrame) {
      dcatlMediaFrame.open();
      return;
    }

    dcatlMediaFrame = wp.media({
      title: dcatl_meta_image?.title,
      button: { text: dcatl_meta_image?.button },
      library: { type: 'image' },
      multiple: false,
    });

    dcatlMediaFrame.on('select', () => {
      const attachment = dcatlMediaFrame
        .state()
        .get('selection')
        .first()
        .toJSON();

      $('#dcatl_upload_image').val(attachment?.id || '');
      $('#dcatl_upload_image_btn').attr('src', attachment?.url || '');
    });

    dcatlMediaFrame.open();
  });

  $('.dcatl_image_remove').on('click', (event) => {
    event.preventDefault();
    $('#dcatl_upload_image_btn').attr('src', dcatl_meta_image?.placeholder);
    $('#dcatl_upload_image').val('');
  });
});
