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

  $(document).on('click', '[data-rfec-select-image]', function(event) {
    event.preventDefault();
    const row = $(this).closest('[data-rfec-image-row]');
    const frame = wp.media({
      title: 'Choose roof 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-rfec-image-id]').val(image.id);
      row.find('.rfec-admin-image img').attr('src', preview);
      row.find('[data-rfec-remove-image]').prop('hidden', false);
    });

    frame.open();
  });

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

  $(document).on('input', '[data-rfec-multiplier]', function() {
    const value = Number.parseFloat(this.value);
    const effect = $(this).closest('tr').find('[data-rfec-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);
