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

  const form = document.querySelector('[data-rfec-settings-form]');
  const tabButtons = Array.from(document.querySelectorAll('[data-rfec-tab]'));
  const panels = Array.from(document.querySelectorAll('[data-rfec-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.rfecTab === name)) name = 'welcome';
    tabButtons.forEach((button) => {
      const active = button.dataset.rfecTab === name;
      button.classList.toggle('nav-tab-active', active);
      button.setAttribute('aria-selected', active ? 'true' : 'false');
    });
    panels.forEach((panel) => { panel.hidden = panel.dataset.rfecPanel !== name; });
    if (remember) window.sessionStorage.setItem('rfecSettingsTab', name);
  };

  tabButtons.forEach(button => button.addEventListener('click', () => activateTab(button.dataset.rfecTab)));
  document.querySelectorAll('[data-rfec-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.rfecOpenTab);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }));
  activateTab(window.sessionStorage.getItem('rfecSettingsTab') || '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-rfec-colour-picker]');
  const colourHex = document.querySelector('[data-rfec-colour-hex]');
  const colourStatus = document.querySelector('[data-rfec-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-rfec-clear-colour]', function(event) {
    event.preventDefault();
    if (colourHex) colourHex.value = '';
    setColourStatus(false);
  });

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

  $(document).on('click', '[data-rfec-select-email-logo]', function(event) {
    event.preventDefault();
    const control = $(this).closest('[data-rfec-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-rfec-email-logo-id]').val(selected.id).trigger('change');
      control.find('.rfec-email-logo-preview').html($('<img>', { src: preview, alt: '' }));
      control.find('[data-rfec-remove-email-logo]').prop('hidden', false);
    });
    frame.open();
  });

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