/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-i18n/
 */
import { __ } from "@wordpress/i18n";

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/packages/packages-block-editor/#useblockprops
 */
import { useBlockProps, InnerBlocks } from "@wordpress/block-editor";
import { useEffect, useRef } from "@wordpress/element";

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
import "./editor.scss";
import SidePanel from "./side-panel";

const ALLOWED_BLOCKS = ["orphic-ui/stack-card-item"];
const TEMPLATE = [
	["orphic-ui/stack-card-item"],
	["orphic-ui/stack-card-item"],
	["orphic-ui/stack-card-item"],
];

const DEFAULT_BLOCK = ["orphic-ui/stack-card-item"];

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */
export default function Edit({ attributes, setAttributes }) {
	const { spacing, cardHeight, stickyOffset, cardOffset } = attributes;
	const containerRef = useRef(null);

	useEffect(() => {
		if (containerRef.current) {
			const cardBlock = containerRef.current;
			const cards = cardBlock.querySelectorAll(
				".wp-block-orphic-ui-stack-card-item",
			);
			cardBlock.style.paddingBottom = `${
				Math.max(cards.length, 1) * cardOffset
			}px`;

			let nextOffset = stickyOffset;
			Array.from(cards).forEach((card, i) => {
				if (i === 0) {
					card.style.top = `${stickyOffset}px`;
				} else {
					nextOffset += cardOffset;
					card.style.top = `${nextOffset}px`;
				}
			});
		}
	}, [cardOffset, stickyOffset]);

	const blockProps = useBlockProps({
		style: {
			padding: "2rem",
			position: "relative",
			"--card-height": `${cardHeight}px`,
			"--sticky-offset": `${stickyOffset}px`,
			"--spacing": `${spacing}px`,
		},
	});

	return (
		<div {...blockProps}>
			<SidePanel attributes={attributes} setAttributes={setAttributes} />
			<div className="stack-items-container" ref={containerRef}>
				<InnerBlocks
					allowedBlocks={ALLOWED_BLOCKS}
					template={TEMPLATE}
					templateLock={false}
					defaultBlock={DEFAULT_BLOCK}
				/>
			</div>
		</div>
	);
}
