(($) => {
  'use strict';
  const p = 'rfec';
  const attr = name => `data-${p}-${name}`;
  const select = name => `[${attr(name)}]`;
  const form = document.querySelector(select('settings-form'));
  const tabs = Array.from(document.querySelectorAll(select('tab')));
  const panels = Array.from(document.querySelectorAll(select('panel')));
  let submitting = false;
  let initialState = '';
  const state = () => form ? $(form).serialize() : '';
  const dirty = () => form && state() !== initialState;
  const data = (element, name) => element.getAttribute(attr(name));

  const activate = (name, remember = true) => {
    if (!tabs.some(tab => data(tab, 'tab') === name)) name = tabs.length ? data(tabs[0], 'tab') : '';
    tabs.forEach(tab => {
      const active = data(tab, 'tab') === name;
      tab.classList.toggle('nav-tab-active', active);
      tab.setAttribute('aria-selected', active ? 'true' : 'false');
    });
    panels.forEach(panel => { panel.hidden = data(panel, 'panel') !== name; });
    if (remember) sessionStorage.setItem(`${p}SettingsTab`, name);
  };

  tabs.forEach(tab => tab.addEventListener('click', () => activate(data(tab, 'tab'))));
  document.querySelectorAll(select('open-tab')).forEach(button => button.addEventListener('click', () => {
    if (dirty() && !confirm('You have unsaved settings. The test estimate form uses the last saved settings. Continue anyway?')) return;
    activate(data(button, 'open-tab'));
    scrollTo({ top: 0, behavior: 'smooth' });
  }));
  activate(sessionStorage.getItem(`${p}SettingsTab`) || 'welcome', false);

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

  const picker = document.querySelector(select('colour-picker'));
  const hex = document.querySelector(select('colour-hex'));
  const status = document.querySelector(select('colour-status'));
  const colourStatus = custom => { if (status) status.textContent = custom ? 'Custom colour override' : 'Using theme default'; };
  if (picker && hex) {
    picker.addEventListener('input', () => { hex.value = picker.value.toUpperCase(); colourStatus(true); });
    hex.addEventListener('input', () => {
      const value = hex.value.trim();
      const match = value.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
      if (!value) colourStatus(false);
      else if (match) {
        const digits = match[1].length === 3 ? match[1].split('').map(c => c + c).join('') : match[1];
        picker.value = `#${digits}`; colourStatus(true);
      }
    });
  }
  $(document).on('click', select('clear-colour'), event => { event.preventDefault(); if (hex) hex.value = ''; colourStatus(false); });

  const mediaFrame = (title, button, callback) => {
    const frame = wp.media({ title, button: { text: button }, library: { type: 'image' }, multiple: false });
    frame.on('select', () => callback(frame.state().get('selection').first().toJSON()));
    frame.open();
  };
  $(document).on('click', select('select-image'), function(event) {
    event.preventDefault(); const row = $(this).closest(select('image-row'));
    mediaFrame('Choose roof option image', 'Use this image', image => {
      const preview = image.sizes?.medium?.url || image.sizes?.thumbnail?.url || image.url;
      row.find(select('image-id')).val(image.id).trigger('change');
      row.find(`.${p}-admin-image img`).attr('src', preview);
      row.find(select('remove-image')).prop('hidden', false);
    });
  });
  $(document).on('click', select('remove-image'), function(event) {
    event.preventDefault(); const row = $(this).closest(select('image-row'));
    row.find(select('image-id')).val('0').trigger('change');
    row.find(`.${p}-admin-image img`).attr('src', row.find(select('fallback')).val());
    $(this).prop('hidden', true);
  });
  $(document).on('click', select('select-email-logo'), function(event) {
    event.preventDefault(); const control = $(this).closest(select('email-logo'));
    mediaFrame('Choose email logo', 'Use this logo', image => {
      const preview = image.sizes?.medium?.url || image.sizes?.thumbnail?.url || image.url;
      control.find(select('email-logo-id')).val(image.id).trigger('change');
      control.find(`.${p}-email-logo-preview`).html($('<img>', { src: preview, alt: '' }));
      control.find(select('remove-email-logo')).prop('hidden', false);
    });
  });
  $(document).on('click', select('remove-email-logo'), function(event) {
    event.preventDefault(); const control = $(this).closest(select('email-logo'));
    control.find(select('email-logo-id')).val('0').trigger('change');
    control.find(`.${p}-email-logo-preview`).html($('<span>').text('No logo selected'));
    $(this).prop('hidden', true);
  });
  $(document).on('input', select('multiplier'), function() {
    const value = Number.parseFloat(this.value); const effect = $(this).closest('tr').find(select('effect'));
    if (!Number.isFinite(value)) return effect.text('Enter a number');
    const change = Math.round((value - 1) * 1000) / 10;
    effect.text(change === 0 ? 'No change' : `${change > 0 ? '+' : ''}${change.toFixed(1)}%`);
  });
})(jQuery);
