{%- comment -%}
  BerryCookie for Shopify themes (no app needed).
  1. Online Store > Themes > ... > Edit code > Snippets > Add a new snippet "berrycookie", paste this whole file.
  2. Replace YOUR-WEBSITE-PUBLIC-KEY below with the key from the BerryCookie dashboard (Websites > Install).
  3. In layout/theme.liquid add {% render 'berrycookie' %} as the first line right after <head>,
     before {{ content_for_header }}.
  The script below bc.js passes the visitor's decision to Shopify's Customer Privacy API, so Shopify's pixels,
  apps and checkout follow it. Generated from integrations/shopify/app/extensions/berrycookie/assets/berrycookie-shopify.js.
{%- endcomment -%}
{%- assign berrycookie_key = 'YOUR-WEBSITE-PUBLIC-KEY' -%}
<script id="BerryCookie" src="https://cdn.berrycookie.com/bc.js" data-key="{{ berrycookie_key }}" data-blockingmode="auto"></script>
<script>
// BEGIN berrycookie-shopify.js
/**
 * BerryCookie for Shopify: passes the visitor's BerryCookie decision to Shopify's Customer Privacy API
 * (window.Shopify.customerPrivacy.setTrackingConsent), so Shopify's own analytics, app pixels (Google & YouTube,
 * Facebook & Instagram and others), custom pixels from Customer events and the checkout follow it. Those run in
 * Shopify's pixel sandbox, where bc.js cannot block them; Shopify loads them only with the consent recorded here.
 *
 * BerryCookie category -> Shopify purpose: statistics -> analytics, marketing -> marketing,
 * preferences -> preferences. In regions where Shopify offers a data sale opt-out (saleOfDataRegion(), US states),
 * refusing marketing also sends sale_of_data: false (an opt-out); it never sends true, so an opt-out made through
 * Shopify's own form is never undone from here.
 *
 * Shopify asks that consent be recorded only after a visitor's action, so:
 * - every decision on the banner is sent;
 * - a decision from an earlier visit is sent again only when Shopify's copy differs (cleared cookies, another
 *   subdomain);
 * - nothing is sent before the visitor decides (Shopify applies the regions set in Settings > Customer privacy),
 *   nor for Global Privacy Control, which Shopify reads from the browser itself.
 *
 * Also: a click on a link whose address ends with #berrycookie-settings opens the BerryCookie preferences.
 *
 * Runs after bc.js. Loaded by the app embed (assets/) and copied into the theme snippet (theme/berrycookie.liquid)
 * by npm run integrations: edit this file, not the copy. Keep it free of Liquid delimiters.
 */
(function (win, doc) {
	'use strict';

	var SETTINGS_HASH = '#berrycookie-settings';
	var PURPOSES = { analytics: 'statistics', marketing: 'marketing', preferences: 'preferences' };
	var waiting = [];
	var loading = false;

	function sdk() {
		var bc = win.BerryCookie;
		return bc && typeof bc.hasConsent === 'function' ? bc : null;
	}

	function warn(message) {
		if (win.console && win.console.warn) {
			win.console.warn('[BerryCookie] ' + message);
		}
	}

	function ready(callback) {
		if (doc.readyState === 'loading') {
			doc.addEventListener('DOMContentLoaded', callback);
		} else {
			callback();
		}
	}

	function loaded() {
		var privacy = win.Shopify && win.Shopify.customerPrivacy;
		return privacy && typeof privacy.setTrackingConsent === 'function' ? privacy : null;
	}

	/** Calls back with window.Shopify.customerPrivacy, loading it first when the page has not. */
	function withPrivacy(callback) {
		var privacy = loaded();
		if (privacy) {
			callback(privacy);
			return;
		}
		if (!win.Shopify || typeof win.Shopify.loadFeatures !== 'function') {
			warn('Shopify Customer Privacy API not found; the decision is not passed to Shopify.');
			return;
		}
		waiting.push(callback);
		if (loading) {
			return;
		}
		loading = true;
		win.Shopify.loadFeatures([ { name: 'consent-tracking-api', version: '0.2' } ], function (error) {
			var queued = waiting;
			loading = false;
			waiting = [];
			privacy = loaded();
			if (error || !privacy) {
				warn('Shopify Customer Privacy API could not be loaded; the decision is not passed to Shopify.');
				return;
			}
			for (var i = 0; i < queued.length; i++) {
				queued[i](privacy);
			}
		});
	}

	function trackingConsent(privacy, consent) {
		var categories = consent.cats || [];
		var result = {};
		for (var purpose in PURPOSES) {
			if (Object.prototype.hasOwnProperty.call(PURPOSES, purpose)) {
				result[purpose] = categories.indexOf(PURPOSES[purpose]) >= 0;
			}
		}
		if (!result.marketing && typeof privacy.saleOfDataRegion === 'function' && privacy.saleOfDataRegion()) {
			result.sale_of_data = false;
		}
		return result;
	}

	function differs(privacy, wanted) {
		var current = typeof privacy.currentVisitorConsent === 'function' ? privacy.currentVisitorConsent() : null;
		if (!current) {
			return true;
		}
		for (var purpose in PURPOSES) {
			if (Object.prototype.hasOwnProperty.call(PURPOSES, purpose) && current[purpose] !== (wanted[purpose] ? 'yes' : 'no')) {
				return true;
			}
		}
		return false;
	}

	function send(consent, always) {
		if (!consent || !consent.cats || consent.act === 'GPC') {
			return;
		}
		ready(function () {
			withPrivacy(function (privacy) {
				var wanted = trackingConsent(privacy, consent);
				if (always || differs(privacy, wanted)) {
					privacy.setTrackingConsent(wanted, function () {});
				}
			});
		});
	}

	win.addEventListener('berrycookie:consent', function (event) {
		send(event.detail, true);
	});

	// A decision from an earlier visit (window.Shopify is complete once the head has been read).
	ready(function () {
		var bc = sdk();
		if (bc && bc.consent) {
			send(bc.consent, false);
		}
	});

	doc.addEventListener('click', function (event) {
		var target = event.target;
		var link = target && target.closest ? target.closest('a[href]') : null;
		var href = link ? link.getAttribute('href') || '' : '';
		var bc = sdk();
		if (!bc || href.slice(-SETTINGS_HASH.length) !== SETTINGS_HASH) {
			return;
		}
		event.preventDefault();
		bc.show();
	});
}(window, document));
// END berrycookie-shopify.js
</script>
