/**
 * 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
import { animate } from "https://cdn.jsdelivr.net/npm/motion@11.18.2/+esm";

// 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';
        }

        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
      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() {
        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();
}
