/******/ (() => { // webpackBootstrap
/******/ 	"use strict";
/******/ 	var __webpack_modules__ = ({

/***/ "./src/persistent-banner/view.js":
/*!***************************************!*\
  !*** ./src/persistent-banner/view.js ***!
  \***************************************/
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var https_cdn_jsdelivr_net_npm_motion_11_18_2_esm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! https://cdn.jsdelivr.net/npm/motion@11.18.2/+esm */ "https://cdn.jsdelivr.net/npm/motion@11.18.2/+esm");
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([https_cdn_jsdelivr_net_npm_motion_11_18_2_esm__WEBPACK_IMPORTED_MODULE_0__]);
https_cdn_jsdelivr_net_npm_motion_11_18_2_esm__WEBPACK_IMPORTED_MODULE_0__ = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];
/**
 * Use this file for JavaScript code that you want to run in the front-end
 * on posts/pages that contain this block.
 *
 * When this file is defined as the value of the `viewScript` property
 * in `block.json` it will be enqueued on the front end of the site.
 *
 * Example:
 *
 * ```js
 * {
 *   "viewScript": "file:./view.js"
 * }
 * ```
 *
 * If you're not making any changes to this file because your project doesn't need any
 * JavaScript running in the front-end, then you should delete this file and remove
 * the `viewScript` property from `block.json`.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-metadata/#view-script
 */

// Import Motion au début du fichier


// Définition et initialisation du module AVANT tout
class BannerModule {
  constructor() {
    this.banners = new Map();
    this.eventHandlers = new Map();
  }
  register(name, element) {
    this.banners.set(name, element);
    return this;
  }
  on(bannerName, event, callback) {
    const key = `${bannerName}:${event}`;
    this.eventHandlers.set(key, callback);
    return this;
  }
  emit(bannerName, event, data) {
    const key = `${bannerName}:${event}`;
    const handler = this.eventHandlers.get(key);
    if (handler) handler(data);
  }
}

// Créer l'instance globale immédiatement
window.bannerModule = new BannerModule();
function initializeBanners() {
  const banners = document.querySelectorAll('.orphic-ui-persistent-banner-content');
  if (!banners.length) return;
  const BANNER_SPACING = 20;
  const INITIAL_BOTTOM = 20;
  const MOBILE_BREAKPOINT = 768;

  // Fonctions utilitaires
  const utils = {
    isMobile: () => window.innerWidth < MOBILE_BREAKPOINT,
    getAllVisibleBanners: stacks => {
      if (!utils.isMobile()) return null;
      return Object.values(stacks).flat().filter(banner => banner.style.display !== 'none');
    }
  };

  // Séparer les bannières en deux tableaux
  const rightBanners = Array.from(banners).filter(banner => banner.getAttribute('data-position') === 'right');
  const leftBanners = Array.from(banners).filter(banner => banner.getAttribute('data-position') === 'left');

  // Définir les stacks disponibles
  const stacks = {
    right: rightBanners,
    left: leftBanners
  };

  // Fonction pour réorganiser une stack
  function reorganizeStack(banners, position) {
    if (!banners) return;
    let currentBottom = INITIAL_BOTTOM;
    banners.forEach(banner => {
      if (banner.style.display !== 'none') {
        const animationTarget = {
          bottom: `${currentBottom}px`
        };
        if (position === 'mobile') {
          animationTarget.left = '20px';
          animationTarget.right = '20px';
        } else {
          animationTarget[position === 'left' ? 'left' : 'right'] = '20px';
          animationTarget[position === 'left' ? 'right' : 'left'] = 'auto';
        }
        (0,https_cdn_jsdelivr_net_npm_motion_11_18_2_esm__WEBPACK_IMPORTED_MODULE_0__.animate)(banner, animationTarget, {
          duration: 0.3,
          easing: [.4, 0, .2, 1] // power2.inOut equivalent
        });
        currentBottom += banner.offsetHeight + BANNER_SPACING;
      }
    });
  }

  // Fonction pour réorganiser toutes les stacks
  function reorganizeAllStacks(availableStacks = stacks) {
    if (utils.isMobile()) {
      const allBanners = utils.getAllVisibleBanners(availableStacks);
      reorganizeStack(allBanners, 'mobile');
    } else {
      Object.entries(availableStacks).forEach(([position, banners]) => {
        reorganizeStack(banners.filter(b => b.style.display !== 'none'), position);
      });
    }
  }

  // Fonction générique pour initialiser une stack de bannières
  function initializeBannerStack(banners, position) {
    banners.forEach((banner, index) => {
      const bannerId = banner.dataset.id;
      const isFirstVisit = banner.dataset.firstVisit === 'true';

      // Vérifier si c'est la première visite
      const hasVisited = localStorage.getItem(`bannerFirstVisit-${bannerId}`);

      // Si ce n'est pas la première visite et que la bannière est configurée pour 
      // s'afficher uniquement à la première visite, on cache la bannière
      if (isFirstVisit && hasVisited) {
        banner.style.display = 'none';
        return;
      }
      const agreeButton = banner.querySelector('.orphic-ui-persistent-banner-agree');
      const closeButton = banner.querySelector('.orphic-ui-persistent-banner-close');
      window.bannerModule.register(bannerId, banner);
      banner.style.display = 'block';
      function updateBannerPosition() {
        let bottomPosition = INITIAL_BOTTOM;
        const visibleBanners = utils.isMobile() ? utils.getAllVisibleBanners(stacks) : banners;
        if (visibleBanners) {
          const bannerIndex = visibleBanners.indexOf(banner);
          for (let j = 0; j < bannerIndex; j++) {
            if (visibleBanners[j].style.display !== 'none') {
              bottomPosition += visibleBanners[j].offsetHeight + BANNER_SPACING;
            }
          }
        }

        // Set initial position
        banner.style.transform = 'translateY(100%)';
        banner.style.opacity = '0';
        banner.style.position = 'fixed';
        banner.style.bottom = `${bottomPosition}px`;
        banner.style.zIndex = `${1000 - index}`;
        if (utils.isMobile()) {
          banner.style.left = '20px';
          banner.style.right = '20px';
        } else {
          banner.style.left = position === 'left' ? '20px' : 'auto';
          banner.style.right = position === 'right' ? '20px' : 'auto';
        }
      }
      updateBannerPosition();

      // Animate banner in
      (0,https_cdn_jsdelivr_net_npm_motion_11_18_2_esm__WEBPACK_IMPORTED_MODULE_0__.animate)(banner, {
        transform: 'translateY(0%)',
        opacity: 1
      }, {
        duration: 0.5,
        delay: index * 0.2,
        easing: [.34, 1.56, .64, 1] // back.out(1.7) equivalent
      });
      function hideBanner() {
        (0,https_cdn_jsdelivr_net_npm_motion_11_18_2_esm__WEBPACK_IMPORTED_MODULE_0__.animate)(banner, {
          transform: 'translateY(100%)',
          opacity: 0
        }, {
          duration: 0.3,
          easing: [.4, 0, 1, 1],
          // power2.in equivalent
          onComplete: () => {
            banner.style.display = 'none';
            reorganizeAllStacks(stacks);
          }
        });
      }
      if (agreeButton) {
        agreeButton.addEventListener('click', () => {
          localStorage.setItem(`bannerAgreed-${bannerId}`, 'true');
          if (isFirstVisit) {
            localStorage.setItem(`bannerFirstVisit-${bannerId}`, 'true');
          }
          window.bannerModule.emit(bannerId, 'agree');
          hideBanner();
        });
      }
      if (closeButton) {
        closeButton.addEventListener('click', () => {
          sessionStorage.setItem(`bannerClosed-${bannerId}`, 'true');
          if (isFirstVisit) {
            localStorage.setItem(`bannerFirstVisit-${bannerId}`, 'true');
          }
          window.bannerModule.emit(bannerId, 'close');
          hideBanner();
        });
      }
    });
  }

  // Initialiser les stacks
  initializeBannerStack(rightBanners, 'right');
  initializeBannerStack(leftBanners, 'left');

  // Gérer le redimensionnement
  let resizeTimeout;
  window.addEventListener('resize', () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
      reorganizeAllStacks(stacks);
    }, 100);
  });
}

// Initialize with DOM state check
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initializeBanners);
} else {
  initializeBanners();
}
__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ "https://cdn.jsdelivr.net/npm/motion@11.18.2/+esm":
/*!*******************************************************************!*\
  !*** external "https://cdn.jsdelivr.net/npm/motion@11.18.2/+esm" ***!
  \*******************************************************************/
/***/ ((module) => {

module.exports = import("https://cdn.jsdelivr.net/npm/motion@11.18.2/+esm");;

/***/ })

/******/ 	});
/************************************************************************/
/******/ 	// The module cache
/******/ 	var __webpack_module_cache__ = {};
/******/ 	
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/ 		// Check if module is in cache
/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
/******/ 		if (cachedModule !== undefined) {
/******/ 			return cachedModule.exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = __webpack_module_cache__[moduleId] = {
/******/ 			// no module.id needed
/******/ 			// no module.loaded needed
/******/ 			exports: {}
/******/ 		};
/******/ 	
/******/ 		// Execute the module function
/******/ 		__webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/ 	
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/ 	
/************************************************************************/
/******/ 	/* webpack/runtime/async module */
/******/ 	(() => {
/******/ 		var webpackQueues = typeof Symbol === "function" ? Symbol("webpack queues") : "__webpack_queues__";
/******/ 		var webpackExports = typeof Symbol === "function" ? Symbol("webpack exports") : "__webpack_exports__";
/******/ 		var webpackError = typeof Symbol === "function" ? Symbol("webpack error") : "__webpack_error__";
/******/ 		var resolveQueue = (queue) => {
/******/ 			if(queue && queue.d < 1) {
/******/ 				queue.d = 1;
/******/ 				queue.forEach((fn) => (fn.r--));
/******/ 				queue.forEach((fn) => (fn.r-- ? fn.r++ : fn()));
/******/ 			}
/******/ 		}
/******/ 		var wrapDeps = (deps) => (deps.map((dep) => {
/******/ 			if(dep !== null && typeof dep === "object") {
/******/ 				if(dep[webpackQueues]) return dep;
/******/ 				if(dep.then) {
/******/ 					var queue = [];
/******/ 					queue.d = 0;
/******/ 					dep.then((r) => {
/******/ 						obj[webpackExports] = r;
/******/ 						resolveQueue(queue);
/******/ 					}, (e) => {
/******/ 						obj[webpackError] = e;
/******/ 						resolveQueue(queue);
/******/ 					});
/******/ 					var obj = {};
/******/ 					obj[webpackQueues] = (fn) => (fn(queue));
/******/ 					return obj;
/******/ 				}
/******/ 			}
/******/ 			var ret = {};
/******/ 			ret[webpackQueues] = x => {};
/******/ 			ret[webpackExports] = dep;
/******/ 			return ret;
/******/ 		}));
/******/ 		__webpack_require__.a = (module, body, hasAwait) => {
/******/ 			var queue;
/******/ 			hasAwait && ((queue = []).d = -1);
/******/ 			var depQueues = new Set();
/******/ 			var exports = module.exports;
/******/ 			var currentDeps;
/******/ 			var outerResolve;
/******/ 			var reject;
/******/ 			var promise = new Promise((resolve, rej) => {
/******/ 				reject = rej;
/******/ 				outerResolve = resolve;
/******/ 			});
/******/ 			promise[webpackExports] = exports;
/******/ 			promise[webpackQueues] = (fn) => (queue && fn(queue), depQueues.forEach(fn), promise["catch"](x => {}));
/******/ 			module.exports = promise;
/******/ 			body((deps) => {
/******/ 				currentDeps = wrapDeps(deps);
/******/ 				var fn;
/******/ 				var getResult = () => (currentDeps.map((d) => {
/******/ 					if(d[webpackError]) throw d[webpackError];
/******/ 					return d[webpackExports];
/******/ 				}))
/******/ 				var promise = new Promise((resolve) => {
/******/ 					fn = () => (resolve(getResult));
/******/ 					fn.r = 0;
/******/ 					var fnQueue = (q) => (q !== queue && !depQueues.has(q) && (depQueues.add(q), q && !q.d && (fn.r++, q.push(fn))));
/******/ 					currentDeps.map((dep) => (dep[webpackQueues](fnQueue)));
/******/ 				});
/******/ 				return fn.r ? promise : getResult();
/******/ 			}, (err) => ((err ? reject(promise[webpackError] = err) : outerResolve(exports)), resolveQueue(queue)));
/******/ 			queue && queue.d < 0 && (queue.d = 0);
/******/ 		};
/******/ 	})();
/******/ 	
/******/ 	/* webpack/runtime/make namespace object */
/******/ 	(() => {
/******/ 		// define __esModule on exports
/******/ 		__webpack_require__.r = (exports) => {
/******/ 			if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 				Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 			}
/******/ 			Object.defineProperty(exports, '__esModule', { value: true });
/******/ 		};
/******/ 	})();
/******/ 	
/************************************************************************/
/******/ 	
/******/ 	// startup
/******/ 	// Load entry module and return exports
/******/ 	// This entry module used 'module' so it can't be inlined
/******/ 	var __webpack_exports__ = __webpack_require__("./src/persistent-banner/view.js");
/******/ 	
/******/ })()
;
//# sourceMappingURL=view.js.map