/**
 * 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
 */

const ModuleStackCard = () => {
	const init = () => {
		const cardBlocks = document.querySelectorAll(".stack-items-container");
		cardBlocks.forEach((cardBlock) => {
			const wrapper = cardBlock.closest(
				".wp-block-orphic-ui-stack-card-wrapper",
			);
			const offset = parseFloat(wrapper.dataset.cardOffset);
			const stickyOffset = parseFloat(wrapper.dataset.cardStickyOffset);

			console.log("stickyOffset", stickyOffset);
			console.log("offset", offset);

			cardBlock.style.paddingBottom = `${
				Math.max(cardBlock.children.length, 1) * offset
			}px`;

			let nextOffset = stickyOffset;
			Array.from(cardBlock.children).forEach((card, i) => {
				if (i === 0) {
					card.style.top = `${stickyOffset}px`;
				} else {
					nextOffset += offset;
					card.style.top = `${nextOffset}px`;
				}
			});
		});
	};

	return {
		init,
	};
};

// Initialisation au chargement du DOM
document.addEventListener("DOMContentLoaded", () => {
	const stackCardModule = ModuleStackCard();
	stackCardModule.init();
});
