(function () {
  'use strict';

  function init(root) {
    var source = root.querySelector('[name="calliope_sp_tracking_settings[utm_source]"]');
    var medium = root.querySelector('[name="calliope_sp_tracking_settings[utm_medium]"]');
    var campaign = root.querySelector('[name="calliope_sp_tracking_settings[utm_campaign]"]');
    var network = root.querySelector('[data-tracking-preview-network]');
    var shortLinks = root.querySelector('[name="calliope_sp_short_links_enabled"]');
    var output = root.querySelector('[data-tracking-example-url]');
    var ga4SourceMedium = root.querySelector('[data-ga4-source-medium]');
    var ga4Campaign = root.querySelector('[data-ga4-campaign]');
    var tokenButtons = Array.prototype.slice.call(root.querySelectorAll('[data-tracking-token]'));

    if (!source || !medium || !campaign || !network || !output) return;

    function resolved(value) {
      return String(value || '').replace(/\{network\}/g, String(network.value || 'linkedin'));
    }

    function update() {
      var base = 'https://example.com/post';
      try {
        var url = new URL(base);
        [
          ['utm_source', source],
          ['utm_medium', medium],
          ['utm_campaign', campaign]
        ].forEach(function (pair) {
          var value = resolved(pair[1].value).trim();
          if (value) url.searchParams.set(pair[0], value);
        });
        output.textContent = shortLinks && shortLinks.checked
          ? 'https://example.com/sp/A7k3Lm'
          : url.toString();
        if (ga4SourceMedium) ga4SourceMedium.textContent = (resolved(source.value).trim() || '(not set)') + ' / ' + (resolved(medium.value).trim() || '(not set)');
        if (ga4Campaign) ga4Campaign.textContent = resolved(campaign.value).trim() || '(not set)';
      } catch (e) {
        output.textContent = base;
      }
    }

    [source, medium, campaign, network].concat(shortLinks ? [shortLinks] : []).forEach(function (field) {
      field.addEventListener('input', update);
      field.addEventListener('change', update);
    });

    tokenButtons.forEach(function (button) {
      button.addEventListener('click', function () {
        var targetId = button.getAttribute('data-tracking-target') || '';
        var target = targetId ? document.getElementById(targetId) : null;
        var token = button.getAttribute('data-tracking-token') || '{network}';
        if (!target) return;
        var start = typeof target.selectionStart === 'number' ? target.selectionStart : target.value.length;
        var end = typeof target.selectionEnd === 'number' ? target.selectionEnd : start;
        target.value = target.value.slice(0, start) + token + target.value.slice(end);
        var caret = start + token.length;
        if (typeof target.setSelectionRange === 'function') target.setSelectionRange(caret, caret);
        target.focus();
        target.dispatchEvent(new Event('input', { bubbles: true }));
      });
    });

    update();
  }

  document.addEventListener('DOMContentLoaded', function () {
    Array.prototype.forEach.call(document.querySelectorAll('[data-calliope-tracking-settings]'), init);
  });
})();
