/**
 * Klaro initialization with local API - sends consent data to backend.
 * show: +show_count, +no_interaction_count. accept/decline/save: +field, -no_interaction_count.
 * Requires: klaroConfig (from config.js) and klaro (from klaro.js)
 */
(function () {
  var SHOW_SENT_KEY = 'cookie_optin_show_sent';
  var INTERACTED_KEY = 'cookie_optin_interacted';

  var SEARCH_ENGINES = ['google.', 'bing.', 'yahoo.', 'duckduckgo.', 'baidu.', 'yandex.', 'ecosia.', 'qwant.'];
  var SOCIAL_DOMAINS = ['facebook.', 'twitter.', 'instagram.', 'linkedin.', 'youtube.', 'tiktok.', 'pinterest.', 'reddit.', 'snapchat.', 'whatsapp.'];

  function getUtmParams() {
    var params = {};
    var search = (location.search || '').replace(/^\?/, '');
    if (!search) return params;
    search.split('&').forEach(function (pair) {
      var parts = pair.split('=');
      if (parts.length >= 2) {
        params[decodeURIComponent(parts[0]).toLowerCase()] = decodeURIComponent(parts.slice(1).join('=')).toLowerCase();
      }
    });
    return params;
  }

  function getReferrerDomain() {
    try {
      var ref = document.referrer || '';
      if (!ref) return null;
      var a = document.createElement('a');
      a.href = ref;
      var host = (a.hostname || '').toLowerCase();
      return host ? host.replace(/^www\./, '') : null;
    } catch (e) {
      return null;
    }
  }

  function getTrafficData() {
    var utm = getUtmParams();
    var domain = getReferrerDomain();

    if (utm.utm_medium && /^(cpc|ppc|cpa|cpm|cpv|paid)$/.test(utm.utm_medium)) {
      return { source: 'paid', referral_domain: domain };
    }
    if (!domain) {
      return { source: 'direct', referral_domain: null };
    }
    var isSearch = SEARCH_ENGINES.some(function (s) { return domain.indexOf(s) === 0; });
    if (isSearch) {
      return { source: 'organic', referral_domain: domain };
    }
    var isSocial = SOCIAL_DOMAINS.some(function (s) { return domain.indexOf(s) === 0; });
    if (isSocial) {
      return { source: 'social', referral_domain: domain };
    }
    return { source: 'referral', referral_domain: domain };
  }

  function init() {
    if (typeof klaro === 'undefined' || typeof klaroConfig === 'undefined') return;

    var apiUrl = (klaroConfig && klaroConfig.apiUrl) || '/cookie-optin/api/';

    function buildPayload(consentData) {
      var payload = {
        location_data: {
          pathname: location.pathname,
          port: location.port !== '' ? parseInt(location.port, 10) : 0,
          hostname: location.hostname,
          protocol: location.protocol.replace(/:$/, '')
        },
        user_data: {
          client_version: klaro.version ? klaro.version() : '0.7',
          client_name: 'klaro:web'
        },
        consent_data: consentData
      };
      payload.traffic_data = getTrafficData();
      return payload;
    }

    function sendToApi(consentData) {
      fetch(apiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(buildPayload(consentData))
      }).catch(function () {});
    }

    function sendShowIfNeeded() {
      if (sessionStorage.getItem(SHOW_SENT_KEY)) return;
      sessionStorage.setItem(SHOW_SENT_KEY, '1');
      sendToApi({
        consents: {},
        changes: {},
        type: 'show',
        config: (klaroConfig && klaroConfig.id) || 'default'
      });
    }

    var localKlaroApi = {
      update: function (notifier, name, data) {
        var configId = (notifier && notifier.config && notifier.config.id) ? notifier.config.id : 'default';
        if (name === 'saveConsents') {
          if (data.type === 'save' && data.changes && Object.keys(data.changes || {}).length === 0) return;
          var isFirstInteraction = !sessionStorage.getItem(INTERACTED_KEY);
          sessionStorage.setItem(INTERACTED_KEY, '1');
          var payload = {
            consents: data.consents || {},
            changes: data.type === 'save' ? (data.changes || {}) : undefined,
            type: data.type || 'save',
            config: configId
          };
          if (isFirstInteraction) {
            payload.first_interaction = true;
          }
          sendToApi(payload);
        } else if (name === 'showNotice') {
          sendShowIfNeeded();
        }
      }
    };

    /* show: false = let Klaro decide from manager.confirmed (stored consent).
       show: true would force the notice on every page load. */
    klaro.render(klaroConfig, { show: false, api: localKlaroApi });

    /* Fallback: detect banner via DOM when showNotice is not fired (e.g. some Klaro versions).
       Observe for #cookie-optin (elementID from config) appearing in the document. */
    var bannerId = (klaroConfig && klaroConfig.elementID) || 'cookie-optin';
    function checkBannerVisible() {
      var el = document.getElementById(bannerId);
      if (el && el.offsetParent !== null) {
        sendShowIfNeeded();
        return true;
      }
      return false;
    }
    if (!checkBannerVisible()) {
      var observer = new MutationObserver(function () {
        if (checkBannerVisible()) {
          observer.disconnect();
        }
      });
      observer.observe(document.body, { childList: true, subtree: true });
      setTimeout(function () {
        checkBannerVisible();
        observer.disconnect();
      }, 1500);
    }

    document.querySelectorAll('[data-cookies-management]').forEach(function (el) {
      el.addEventListener('click', function (ev) {
        ev.preventDefault();
        klaro.show(klaroConfig);
      });
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
