// source --> /wp-content/ukalbert-attribution/attribution.js?v=20261012 
/* UK Albert lead attribution. No network calls or personal form values. */
(function () {
  'use strict';
  if (window.UKAlbertAttribution) return;
  var KEY = 'ukalbert_attribution_v1';
  var TTL = 30 * 24 * 60 * 60 * 1000;
  var UTM = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'];
  var now = Date.now();
  function text(value) {
    return String(value || '').replace(/[\u0000-\u001f\u007f]/g, '').slice(0, 200);
  }
  function safeUrl(value, local) {
    try {
      var url = new URL(value);
      if (!/^https?:$/.test(url.protocol)) return '';
      if (local && !/^(www\.)?ukalbert\.ru$/i.test(url.hostname)) return '';
      return (url.origin + url.pathname).slice(0, 1000);
    } catch (_) { return ''; }
  }
  function cleanTouch(value) {
    if (!value || typeof value !== 'object') return null;
    var touch = {
      channel: text(value.channel), source: text(value.source),
      landing_url: safeUrl(value.landing_url, true),
      referrer: safeUrl(value.referrer, false), at: text(value.at)
    };
    UTM.forEach(function (key) { touch[key] = text(value[key]); });
    return touch.landing_url ? touch : null;
  }
  var params = new URLSearchParams(window.location.search);
  var referrer = safeUrl(document.referrer, false);
  var current = {
    channel: 'direct_or_unknown', source: 'direct_or_unknown',
    landing_url: safeUrl(window.location.href, true), referrer: referrer,
    at: new Date(now).toISOString()
  };
  UTM.forEach(function (key) { current[key] = text(params.get(key)); });
  var marked = UTM.some(function (key) { return !!current[key]; });
  var external = false;
  if (marked) {
    current.channel = 'utm'; current.source = current.utm_source || 'utm_without_source';
  } else if (referrer) {
    var host = new URL(referrer).hostname.toLowerCase();
    external = !/^(www\.)?ukalbert\.ru$/.test(host);
    if (external) {
      current.channel = /(^|\.)(yandex\.(ru|com|by|kz)|ya\.ru|google\.[a-z.]+|bing\.com|search\.mail\.ru|duckduckgo\.com)$/.test(host) ? 'organic_referrer' : 'referral';
      current.source = host;
    }
  }
  var state = null;
  try {
    var stored = JSON.parse(window.localStorage.getItem(KEY));
    if (stored && stored.v === 1 && stored.expires > now && stored.expires <= now + TTL) {
      var first = cleanTouch(stored.first), last = cleanTouch(stored.last);
      if (first && last) state = {v: 1, expires: stored.expires, first: first, last: last, last_campaign: cleanTouch(stored.last_campaign)};
    }
  } catch (_) {}
  if (!state) state = {v: 1, expires: now + TTL, first: current, last: current, last_campaign: marked ? current : null};
  if (marked || external) state.last = current;
  if (marked) state.last_campaign = current;
  try { window.localStorage.setItem(KEY, JSON.stringify(state)); } catch (_) {}

  function read(form) {
    return {
      v: 1, first: state.first, last: state.last, last_campaign: state.last_campaign,
      page_url: safeUrl(window.location.href, true),
      form_id: text(form && (form.id || form.getAttribute('data-form-name')))
    };
  }
  function values(form) {
    var data = read(form), fields = {_kb_form_ukalbert_attribution: JSON.stringify(data)};
    // The existing messenger integration ignores _kb_form_* service fields.
    // Keep attribution out of its payload on legacy Kadence forms.
    var prefix = form && form.matches('.kb-advanced-form,.kadence-form,.kb-form,form[class*="kb-adv"],form[class*="kadence"]') ? '_kb_form_' : '';
    UTM.forEach(function (key) { fields[prefix + key] = data.last[key] || ''; });
    fields[prefix + 'page_url'] = data.page_url;
    fields[prefix + 'attribution_source'] = data.last.source;
    fields[prefix + 'attribution_channel'] = data.last.channel;
    fields[prefix + 'landing_page'] = data.first.landing_url;
    fields[prefix + 'original_referrer'] = data.first.referrer;
    return fields;
  }
  function supported(form) {
    return !!form && form.tagName === 'FORM' && (
      form.matches('[data-live-form],.kb-advanced-form,.kadence-form,.kb-form,.wpcf7-form,.qw-form') ||
      !!form.querySelector('input[type="tel"],input[name="phone"]')
    );
  }
  function fill(form) {
    if (!supported(form)) return;
    var fields = values(form);
    Object.keys(fields).forEach(function (key) {
      var input = form.querySelector('input[name="' + key + '"]');
      if (input && input.type !== 'hidden') return;
      if (!input) {
        input = document.createElement('input'); input.type = 'hidden'; input.name = key;
        input.setAttribute('data-ukalbert-attribution', '1'); form.appendChild(input);
      }
      input.value = fields[key];
    });
  }
  function scan(root) {
    if (root.nodeType !== 1 && root.nodeType !== 9) return;
    if (root.tagName === 'FORM') fill(root);
    root.querySelectorAll('form').forEach(fill);
  }
  window.UKAlbertAttribution = Object.freeze({read: read, fill: fill, fields: values});
  document.addEventListener('submit', function (event) { fill(event.target); }, true);
  // formdata runs after old page scripts set their original tracking fields.
  // It also covers AJAX forms and file uploads without replacing their handlers.
  document.addEventListener('formdata', function (event) {
    if (!supported(event.target)) return;
    var fields = values(event.target);
    Object.keys(fields).forEach(function (key) { event.formData.set(key, fields[key]); });
  }, true);
  function init() {
    scan(document);
    new MutationObserver(function (records) {
      records.forEach(function (record) { record.addedNodes.forEach(scan); });
    }).observe(document.documentElement, {childList: true, subtree: true});
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, {once: true});
  else init();
})();