jQuery(function ($) {
  let frame;

  function markSettingsChanged() {
    // Woo's settings page enables "Save changes" when the form is "dirty"
    $("#ofpd-logo-id").trigger("change");
    $("#mainform").trigger("change");
  }

  $(document).on('click', '#ofpd-logo-select', function (e) {
    e.preventDefault();

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

    frame = wp.media({
      title: ofpdSettings.i18n.selectLogoTitle,
      button: { text: ofpdSettings.i18n.selectLogoButton },
      library: { type: 'image' },
      multiple: false
    });

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

      if (!attachment.mime || (attachment.mime !== 'image/jpeg' && attachment.mime !== 'image/png')) {
        alert(ofpdSettings.i18n.logoMimeError);
        return;
      }

      $('#ofpd-logo-id').val(attachment.id);

      let url = attachment.url;
      if (attachment.sizes && attachment.sizes.medium) url = attachment.sizes.medium.url;

      $('#ofpd-logo-preview').html(
        '<img src="' + url + '" style="max-width:200px;height:auto;border:1px solid #ccc;padding:4px;" alt="" />'
      );

      $('#ofpd-logo-remove').prop('disabled', false);
      $('#ofpd-logo-select').text(ofpdSettings.i18n.changeLogo);
	  markSettingsChanged();
    });

    frame.open();
  });

  $(document).on('click', '#ofpd-logo-remove', function (e) {
    e.preventDefault();
    $('#ofpd-logo-id').val('');
    $('#ofpd-logo-preview').empty();
    $(this).prop('disabled', true);
    $('#ofpd-logo-select').text(ofpdSettings.i18n.selectLogo);
	markSettingsChanged();
  });
});
