/**
 * Mapbox cookie consent callbacks.
 * Override or extend per application via specific templates if needed.
 */

function callback_Mapbox (consent, service) {
}

function onInit_Mapbox (opts) { }

function onAccept_Mapbox(opts) {
  // Dispatch event to notify the Mapbox API that the consent has been accepted
  window.dispatchEvent(new CustomEvent('mapbox-consent-accepted', {
    detail: { service: opts.service, config: opts.config, consents: opts.consents }
  }));
}

function onDecline_Mapbox(opts) {
  var cookies = opts.service.cookies || [];
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    var pattern = typeof cookie === 'string' ? cookie : (Array.isArray(cookie) ? cookie[0] : (cookie && cookie.pattern));
    if (!pattern) continue;
    try {
      if (pattern instanceof RegExp) {
        var keysToRemove = [];
        for (var j = 0; j < localStorage.length; j++) {
          var key = localStorage.key(j);
          if (pattern.test(key)) keysToRemove.push(key);
        }
        keysToRemove.forEach(function(k) { localStorage.removeItem(k); });
      } else if (typeof pattern === 'string' && /^\/.+\/$/.test(pattern)) {
        var regex = new RegExp(pattern.slice(1, -1));
        var keysToRemove = [];
        for (var j = 0; j < localStorage.length; j++) {
          var key = localStorage.key(j);
          if (regex.test(key)) keysToRemove.push(key);
        }
        keysToRemove.forEach(function(k) { localStorage.removeItem(k); });
      } else {
        localStorage.removeItem(pattern);
      }
    } catch (e) {}
    // Dispatch event to notify the Mapbox API that the consent has been declined
    window.dispatchEvent(new CustomEvent('mapbox-consent-declined', {
      detail: { service: opts.service, config: opts.config, consents: opts.consents }
    }));
  }
}
