const {
  Config,
  Helper,
  Cookie,
  LocalStorage,
  Pixel,
  DataLayer,
  Browser,
  URL,
  Click,
  SPA,
  Triggers,
  pixelFunc,
  pixelEndpoint
} = core;

/* #CONFIG# */

if (typeof Helper.getElementClasses !== 'function') {
  Helper.getElementClasses = function (el, maxClasses) {
    if (maxClasses == null) maxClasses = 6;
    const raw = typeof el.className === 'string' ? el.className : el.getAttribute('class') || '';
    const cls = raw.trim().split(/\s+/).filter(Boolean).slice(0, maxClasses);
    return cls.length ? cls.join(' ') : null;
  };
}
if (typeof Helper.normalizePayload !== 'function') {
  Helper.normalizePayload = function (obj) {
    return Object.fromEntries(Object.entries(obj).filter(function ([, v]) {
      if (v == null || v === '') return false;
      if (Array.isArray(v) && v.length === 0) return false;
      if (typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length === 0) return false;
      return true;
    }));
  };
}
if (typeof Helper.safe !== 'function') {
  Helper.safe = function (fn) {
    try {
      fn();
    } catch (err) {
      console.error(err);
    }
  };
}
if (typeof Helper.getAttrs !== 'function') {
  Helper.getAttrs = function (el, keys) {
    if (!el || !el.getAttribute) return null;
    if (!Array.isArray(keys) || !keys.length) return null;
    const res = {};
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (!key) continue;
      const val = el.getAttribute(key);
      if (val != null && val !== '') res[key] = val;
    }
    return Object.keys(res).length ? res : null;
  };
}
if (!core.Triggers) {
  class Triggers {
    constructor(options = {}) {
      this.options = {
        ...options
      };
    }
    rules(type) {
      const config = typeof Config !== 'undefined' && Config.triggers || this.options.triggers;
      if (!Array.isArray(config)) {
        return [];
      }
      return config.filter(t => t && t.type === type);
    }
    handle(type, data, ctx = {}) {
      const rules = this.rules(type);
      if (!rules.length || data == null) {
        return [];
      }
      const out = [];
      for (const rule of rules) {
        const matched = this.match(type, rule, data);
        if (!matched) {
          continue;
        }
        out.push({
          rule,
          ...matched
        });
      }
      return out;
    }
    match(type, rule, data) {
      let result = null;
      if (rule.selector && data && data.el && data.el.nodeType === 1) {
        result = this.matchSelector(rule, data.el);
      }
      return result;
    }
    matchSelector(rule, el) {
      try {
        const node = el.closest(rule.selector);
        if (!node) return null;
        if (rule.when && !this.matchWhen(rule.when, node)) return null;
        return {
          el: node
        };
      } catch (e) {
        return null;
      }
    }
    matchWhen(when, el) {
      if (!when || typeof when !== 'object') return true;
      const conditions = when.conditions;
      if (!Array.isArray(conditions) || !conditions.length) return true;
      const logic = when.logic === 'or' ? 'or' : 'and';
      const check = cond => this.matchCondition(cond, el);
      return logic === 'or' ? conditions.some(check) : conditions.every(check);
    }
    matchCondition(cond, el) {
      if (!cond || typeof cond !== 'object') return false;
      const operator = cond.operator;
      if (!operator) return false;
      if (cond.text) {
        const actual = String(el.innerText || '').replace(/\s+/g, ' ').trim();
        return this.compare(actual, String(cond.text), operator);
      }
      if (cond.href) {
        if (!el || el.tagName !== 'A') return false;
        const href = el.getAttribute('href');
        if (href == null) return false;
        return this.compare(String(href).trim(), String(cond.href), operator);
      }
      return false;
    }
    compare(actual, expected, operator) {
      switch (operator) {
        case 'eq':
          return actual === expected;
        case 'neq':
          return actual !== expected;
        case 'contains':
          return actual.includes(expected);
        case 'not_contains':
          return !actual.includes(expected);
        case 'starts_with':
          return actual.startsWith(expected);
        default:
          return false;
      }
    }
  }
  core.Triggers = Triggers;
}
const triggers = core.triggers || new core.Triggers();
core.triggers = triggers;
if (!core.Click || core.Click.version != 2) {
  class ClickV2 {
    static version = 2;
    constructor(options = {}) {
      this.options = {
        maxText: 120,
        maxDepth: 5,
        maxClasses: 6,
        dedupeMs: 1000,
        filter: el => false,
        trackCursor: false,
        ...options
      };
      this.triggers = options.triggers || null;
      this.attempts = new WeakMap();
      this.init();
    }
    init() {
      document.addEventListener('click', e => Helper.safe(() => this.onClick(e)), {
        capture: true
      });
      document.addEventListener('auxclick', e => Helper.safe(() => this.onClick(e)), {
        capture: true
      });
    }
    onClick(e) {
      if (!(e instanceof MouseEvent)) return;

      // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
      if (typeof e.button === 'number' && e.button !== 0 && e.button !== 1) return;
      const target = this.resolveTarget(e.target);
      if (!target) return;
      if (e.type === 'auxclick') {
        if (target.tagName !== 'A' || !target.hasAttribute('href')) return;
      }
      this.attemptClick(target);
    }
    attemptClick(el) {
      const last = this.attempts.get(el);
      if (last && Helper.now() - last.ts < this.options.dedupeMs) {
        return;
      }
      this.attempts.set(el, {
        ts: Helper.now()
      });
      const basePayload = this.buildPayload(el);
      const matches = this.triggers ? this.triggers.handle('click', {
        el
      }) : [];
      if (!matches.length) {
        this.process(['event', 'custom_click', Helper.normalizePayload(basePayload)]);
        return;
      }
      for (const hit of matches) {
        const payload = {
          ...basePayload
        };
        if (hit.rule.selector) payload.selector = hit.rule.selector;
        // if (hit.rule.eventName) eventName = hit.rule.eventName;

        const attrs = Helper.getAttrs(hit.el, hit.rule.attrs);
        if (attrs) payload.attrs = attrs;
        this.process(['event', 'custom_click', Helper.normalizePayload(payload)]);
      }
    }
    resolveTarget(el) {
      let target = el;
      let depth = 0;
      if (target && target.nodeType === 3) target = target.parentElement; // text node

      while (target && target !== document && target !== document.documentElement) {
        if (target.nodeType === 1 && (this.isTrackable(target) || this.options.filter(target))) {
          return target;
        }
        target = target.parentElement;
        if (++depth > this.options.maxDepth) break;
      }
      return null;
    }
    isTrackable(el) {
      if (!el || el.nodeType !== 1) return false;
      if (el.disabled || el.getAttribute('aria-disabled') === 'true') return false;
      const tag = el.tagName.toUpperCase();

      // links
      if (tag === 'A' && el.hasAttribute('href')) return true;

      // buttons
      if (tag === 'BUTTON') {
        const buttonType = (el.type || 'submit').toLowerCase();
        if (buttonType === 'button') return true;
        if (buttonType === 'reset') return false;
        if (buttonType === 'submit') return !(el.form instanceof HTMLFormElement);
      }

      // input buttons
      if (tag === 'INPUT') {
        const type = (el.type || '').toLowerCase();
        if (type === 'button' || type === 'image') return true;
        if (type === 'submit' && !(el.form instanceof HTMLFormElement)) return true;
        return false;
      }
      const role = (el.getAttribute('role') || '').toLowerCase();
      if (role === 'button' || role === 'link' || role === 'tab' || role === 'menuitem') {
        return true;
      }
      if (this.options.trackCursor) {
        try {
          if (el.style.cursor === 'pointer' || getComputedStyle(el).cursor === 'pointer') return true;
        } catch (e) {}
      }
      if (this.triggers) {
        for (const rule of this.triggers.rules('click')) {
          if (!rule.selector) continue;
          try {
            if (el.matches(rule.selector)) {
              if (rule.when && !this.triggers.matchWhen(rule.when, el)) continue;
              return true;
            }
          } catch (e) {}
        }
      }
      return false;
    }
    buildPayload(el) {
      const id = this.getId(el);
      const tag = el.tagName.toLowerCase();
      const text = this.getText(el);
      const href = this.getHref(el);
      const classes = this.getClasses(el);
      return {
        id,
        tag,
        text,
        href,
        classes
      };
    }
    getId(el) {
      return el.getAttribute('id')?.trim() || null;
    }
    getText(el) {
      let text = '';
      if (el.tagName === 'INPUT') {
        text = el.getAttribute('value') || el.getAttribute('alt') || el.getAttribute('aria-label') || '';
      } else {
        text = el.textContent || el.getAttribute('aria-label') || el.getAttribute('title') || el.getAttribute('data-text') || el.innerText || '';
      }
      text = String(text).replace(/\s+/g, ' ').trim();
      if (!text) return null;
      return text.length > this.options.maxText ? text.slice(0, this.options.maxText) : text;
    }
    getHref(el) {
      if (!el) return null;
      let href = null;
      if (el.tagName === 'A') {
        try {
          href = el.href || null;
        } catch {
          href = null;
        }
        if (!href) href = el.getAttribute('href');
      }
      if (!href || href === '' || href === '#') {
        href = el.getAttribute('data-href') || el.getAttribute('data-url') || el.getAttribute('data-link') || null;
      }
      return href ? String(href).trim() : null;
    }
    getClasses(el) {
      return Helper.getElementClasses(el, this.options.maxClasses);
    }
    process(...args) {
      pixelFunc.process.apply(this, ...args);
    }
  }
  core.Click = ClickV2;
  try {
    new ClickV2({
      triggers
    });
  } catch (e) {}
}
if (!core.Form) {
  class Form {
    constructor(options = {}) {
      this.options = {
        maxClasses: 6,
        dedupeMs: 1000,
        ...options
      };
      this.triggers = options.triggers || null;
      this.attempts = new WeakMap();
      this.init();
    }
    init() {
      document.addEventListener('submit', e => Helper.safe(() => this.handleSubmit(e)), {
        capture: true
      });
      document.addEventListener('click', e => Helper.safe(() => this.onClick(e)), {
        capture: true
      });
      document.addEventListener('keydown', e => Helper.safe(() => this.onKeydown(e)), {
        capture: true
      });
    }
    handleSubmit(e) {
      const form = this.resolveForm(e);
      if (!form) return;
      this.attemptSubmit(form, 'submit');
    }
    onKeydown(e) {
      if (e.key !== 'Enter') return;
      const el = e.target;
      if (!el || el.tagName !== 'INPUT') return;
      if (/^(submit|button|image|reset|checkbox|radio|file)$/i.test(el.type)) return;
      if (el.form) this.attemptSubmit(el.form, 'enter');
    }
    onClick(e) {
      const el = e.target;
      if (!el || !el.closest) return;
      const btn = el.closest('button, input[type="submit"], input[type="image"]');
      if (!btn) return;
      if (btn.tagName === 'BUTTON') {
        const t = (btn.getAttribute('type') || 'submit').toLowerCase();
        if (t !== 'submit') return;
      }
      if (btn.form) this.attemptSubmit(btn.form, 'click');
    }
    attemptSubmit(form, type = 'submit') {
      const last = this.attempts.get(form);
      if (last && Helper.now() - last.ts < this.options.dedupeMs) {
        return;
      }
      this.attempts.set(form, {
        ts: Helper.now()
      });
      const basePayload = this.buildPayload(form);
      const matches = this.triggers ? this.triggers.handle('form', {
        el: form
      }) : [];
      if (!matches.length) {
        this.process(['event', 'custom_form', Helper.normalizePayload(basePayload)]);
        return;
      }
      if (this.triggers) {
        for (const hit of matches) {
          const payload = {
            ...basePayload
          };
          if (hit.rule.selector) payload.selector = hit.rule.selector;
          // if (hit.rule.eventName) eventName = hit.rule.eventName;

          const attrs = Helper.getAttrs(hit.el, hit.rule.attrs);
          if (attrs) payload.attrs = attrs;
          this.process(['event', 'custom_form', Helper.normalizePayload(payload)]);
        }
      }
    }
    resolveForm(e) {
      const t = e && e.target;
      return t && t.tagName && t.tagName.toUpperCase() === 'FORM' ? t : null;
    }
    buildPayload(form) {
      const id = this.getId(form);
      const name = this.getName(form);
      const action = this.getAction(form);
      const method = this.getMethod(form);
      const classes = this.getClasses(form);
      return {
        id,
        name,
        action,
        method,
        classes
      };
    }
    getAction(form) {
      let action = typeof form.action === 'string' && form.action ? form.action : form.getAttribute('action');
      if (!action) action = String(window.location.href);
      return action;
    }
    getId(form) {
      return form.getAttribute('id')?.trim() || null;
    }
    getName(form) {
      return form.getAttribute('name')?.trim() || null;
    }
    getMethod(form) {
      const m = form.getAttribute('method')?.toLowerCase().trim();
      return m || 'no_method';
      // return m === 'post' || m === 'dialog' ? m : 'get';
    }
    getClasses(el) {
      return Helper.getElementClasses(el);
    }
    process(...args) {
      pixelFunc.process.apply(this, ...args);
    }
  }
  core.Form = Form;
  try {
    new Form({
      triggers
    });
  } catch (e) {}
}
if (!core.Metrika) {
  class Metrika {
    constructor(options = {}) {
      this.options = {
        filter: options.filter || null,
        exclude: options.exclude || [],
        ...options
      };
      this.queue = null;
      this.originalPush = null;
      this.polling = null;
      this.cursor = 0;
      this.init();
    }
    init(interval = 1000, maxTime = 5000) {
      if (this.polling) return;
      let startTime = null;
      this.polling = setInterval(() => {
        const queue = this.get();
        if (queue) {
          if (!startTime) startTime = Helper.now();
          if (!this.originalPush) {
            this.originalPush = queue.push;
            queue.push = (...args) => {
              const ret = this.originalPush.apply(queue, args);
              for (const item of args) {
                try {
                  this.handle(item);
                } catch (err) {}
              }
              return ret;
            };
            this.process(queue);
            this.stopPolling();
            return;
          }
        }
        if (startTime && Helper.now() - startTime >= maxTime) {
          this.stopPolling();
        }
      }, interval);
    }
    stopPolling() {
      if (!this.polling) return;
      clearInterval(this.polling);
      this.polling = null;
    }
    process(queue) {
      for (let i = this.cursor; i < queue.length; i++) {
        this.handle(queue[i]);
      }
      this.cursor = queue.length;
    }
    get() {
      if (this.queue) return this.queue;
      const ym = window.ym;
      if (typeof ym !== 'function' || !Array.isArray(ym.a)) return null;
      this.queue = ym.a;
      return this.queue;
    }
    handle(args) {
      if (args == null) return null;
      const method = args[1];
      if (method !== 'reachGoal') return null;
      const goal = args[2];
      if (goal == null || goal === '') return null;
      const params = args[3];
      const counterId = args[0];
      if (this.isExcluded(goal)) return;
      if (typeof this.options.filter === 'function' && !this.options.filter({
        goal,
        counterId,
        params
      })) {
        return;
      }
      const payload = Helper.normalizePayload({
        goal,
        counterId,
        params
      });
      try {
        if (JSON.stringify(payload).length < 6000) {
          pixelFunc.process.apply(this, ['event', 'reach_goal', payload]);
        }
      } catch (err) {}
    }
    isExcluded(goal) {
      const exclude = this.options.exclude;
      if (!exclude || !exclude.length) return false;
      return exclude.includes(goal);
    }
  }
  core.Metrika = Metrika;
  try {
    new Metrika({});
  } catch (e) {}
}