(function () {
  'use strict';

  const root = document.querySelector('.subscriber-contracts.is-desktop');
  if (!root) return;

  const tabs = Array.from(root.querySelectorAll('[data-sct-tab]'));
  const panels = Array.from(root.querySelectorAll('[data-sct-panel]'));
  const available = new Set(panels.map(function (panel) {
    return panel.dataset.sctPanel;
  }));

  function panelFromLocation() {
    const queryPanel = new URL(window.location.href).searchParams.get('panel');
    if (queryPanel && available.has(queryPanel)) return queryPanel;
    const hashPanel = window.location.hash.replace(/^#/, '');
    if (available.has(hashPanel)) return hashPanel;
    return '';
  }

  function writeReturnPanel(form, panel) {
    let field = form.querySelector('input[name="return_panel"]');
    if (!field) {
      field = document.createElement('input');
      field.type = 'hidden';
      field.name = 'return_panel';
      form.appendChild(field);
    }
    field.value = panel;
  }

  function activate(panel, updateUrl, replaceUrl) {
    if (!available.has(panel)) panel = available.has('subscribers') ? 'subscribers' : panels[0]?.dataset.sctPanel;
    if (!panel) return;

    root.dataset.activePanel = panel;
    tabs.forEach(function (tab) {
      const active = tab.dataset.sctTab === panel;
      tab.classList.toggle('is-active', active);
      tab.setAttribute('aria-selected', active ? 'true' : 'false');
      tab.tabIndex = active ? 0 : -1;
    });
    panels.forEach(function (item) {
      const active = item.dataset.sctPanel === panel;
      item.hidden = !active;
      item.setAttribute('aria-hidden', active ? 'false' : 'true');
    });
    root.querySelectorAll('form[method="post"]').forEach(function (form) {
      const owner = form.closest('[data-sct-panel]');
      writeReturnPanel(form, owner?.dataset.sctPanel || panel);
    });

    if (updateUrl) {
      const url = new URL(window.location.href);
      url.searchParams.set('panel', panel);
      url.hash = panel;
      window.history[replaceUrl ? 'replaceState' : 'pushState']({sctPanel: panel}, '', url);
    }
  }

  tabs.forEach(function (tab) {
    tab.addEventListener('click', function (event) {
      event.preventDefault();
      activate(tab.dataset.sctTab, true, false);
    });
  });

  root.addEventListener('submit', function (event) {
    const form = event.target;
    if (!(form instanceof HTMLFormElement) || form.method.toLowerCase() !== 'post') return;
    const owner = form.closest('[data-sct-panel]');
    writeReturnPanel(form, owner?.dataset.sctPanel || root.dataset.activePanel || 'subscribers');
  }, true);

  window.addEventListener('popstate', function () {
    activate(panelFromLocation() || root.dataset.activePanel || 'subscribers', false, false);
  });

  activate(panelFromLocation() || root.dataset.activePanel || 'subscribers', true, true);
  root.classList.add('is-panel-ready');
})();
