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

  const form = document.querySelector('[data-pcec-settings-form]');
  const tabButtons = Array.from(document.querySelectorAll('[data-pcec-tab]'));
  const panels = Array.from(document.querySelectorAll('[data-pcec-panel]'));
  let submitting = false;
  let initialState = '';

  const formState = () => form ? $(form).serialize() : '';

  const hasUnsavedChanges = () => form && formState() !== initialState;

  const activateTab = (name, remember = true) => {
    if (!tabButtons.some(button => button.dataset.pcecTab === name)) name = 'welcome';
    tabButtons.forEach((button) => {
      const active = button.dataset.pcecTab === name;
      button.classList.toggle('nav-tab-active', active);
      button.setAttribute('aria-selected', active ? 'true' : 'false');
    });
    panels.forEach((panel) => { panel.hidden = panel.dataset.pcecPanel !== name; });
    if (remember) window.sessionStorage.setItem('pcecSettingsTab', name);
  };

  tabButtons.forEach(button => button.addEventListener('click', () => activateTab(button.dataset.pcecTab)));
  document.querySelectorAll('[data-pcec-open-tab]').forEach(button => button.addEventListener('click', () => {
    if (hasUnsavedChanges() && !window.confirm('You have unsaved settings. The test estimate form uses the last saved settings. Continue anyway?')) return;
    activateTab(button.dataset.pcecOpenTab);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }));
  activateTab(window.sessionStorage.getItem('pcecSettingsTab') || 'welcome', false);

  if (form) {
    initialState = formState();
    form.addEventListener('submit', () => { submitting = true; });
    window.addEventListener('beforeunload', (event) => {
      if (!submitting && hasUnsavedChanges()) {
        event.preventDefault();
        event.returnValue = '';
      }
    });
  }

  const colourPicker = document.querySelector('[data-pcec-colour-picker]');
  const colourHex = document.querySelector('[data-pcec-colour-hex]');
  const colourStatus = document.querySelector('[data-pcec-colour-status]');
  const setColourStatus = custom => {
    if (colourStatus) colourStatus.textContent = custom ? 'Custom colour override' : 'Using theme default';
  };

  if (colourPicker && colourHex) {
    colourPicker.addEventListener('input', () => {
      colourHex.value = colourPicker.value.toUpperCase();
      setColourStatus(true);
    });
    colourHex.addEventListener('input', () => {
      const value = colourHex.value.trim();
      const match = value.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
      if (!value) {
        setColourStatus(false);
      } else if (match) {
        const digits = match[1].length === 3 ? match[1].split('').map(character => character + character).join('') : match[1];
        colourPicker.value = `#${digits}`;
        setColourStatus(true);
      }
    });
  }

  $(document).on('click', '[data-pcec-clear-colour]', function(event) {
    event.preventDefault();
    if (colourHex) colourHex.value = '';
    setColourStatus(false);
  });

  $(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).trigger('change');
      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').trigger('change');
    row.find('.pcec-admin-image img').attr('src', row.find('[data-pcec-fallback]').val());
    $(this).prop('hidden', true);
  });

  $(document).on('click', '[data-pcec-select-email-logo]', function(event) {
    event.preventDefault();
    const control = $(this).closest('[data-pcec-email-logo]');
    const frame = wp.media({ title: 'Choose email logo', button: { text: 'Use this logo' }, library: { type: 'image' }, multiple: false });
    frame.on('select', () => {
      const selected = frame.state().get('selection').first().toJSON();
      const preview = selected.sizes?.medium?.url || selected.sizes?.thumbnail?.url || selected.url;
      control.find('[data-pcec-email-logo-id]').val(selected.id).trigger('change');
      control.find('.pcec-email-logo-preview').html($('<img>', { src: preview, alt: '' }));
      control.find('[data-pcec-remove-email-logo]').prop('hidden', false);
    });
    frame.open();
  });

  $(document).on('click', '[data-pcec-remove-email-logo]', function(event) {
    event.preventDefault();
    const control = $(this).closest('[data-pcec-email-logo]');
    control.find('[data-pcec-email-logo-id]').val('0').trigger('change');
    control.find('.pcec-email-logo-preview').html($('<span>').text('No logo selected'));
    $(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);
