(($) => {
  'use strict';

  $(document).on('click', '[data-pcec-select-image]', function(event) {
    event.preventDefault();
    const row = $(this).closest('[data-pcec-image-row]');
    const frame = wp.media({
      title: 'Choose painting option image',
      button: { text: 'Use this image' },
      library: { type: 'image' },
      multiple: false
    });

    frame.on('select', () => {
      const image = frame.state().get('selection').first().toJSON();
      const preview = image.sizes?.medium?.url || image.sizes?.thumbnail?.url || image.url;
      row.find('[data-pcec-image-id]').val(image.id);
      row.find('.pcec-admin-image img').attr('src', preview);
      row.find('[data-pcec-remove-image]').prop('hidden', false);
    });

    frame.open();
  });

  $(document).on('click', '[data-pcec-remove-image]', function(event) {
    event.preventDefault();
    const row = $(this).closest('[data-pcec-image-row]');
    row.find('[data-pcec-image-id]').val('0');
    row.find('.pcec-admin-image img').attr('src', row.find('[data-pcec-fallback]').val());
    $(this).prop('hidden', true);
  });

  $(document).on('input', '[data-pcec-multiplier]', function() {
    const value = Number.parseFloat(this.value);
    const effect = $(this).closest('tr').find('[data-pcec-effect]');
    if (!Number.isFinite(value)) {
      effect.text('Enter a number');
      return;
    }
    const change = Math.round((value - 1) * 1000) / 10;
    if (change === 0) effect.text('No change');
    else effect.text(`${change > 0 ? '+' : ''}${change.toFixed(1)}%`);
  });
})(jQuery);
