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

/**
 * Use Effect Hook
 */
import { useEffect, useRef } from '@wordpress/element';

/**
 * WordPress dependencies
 */
import { useSelect, useDispatch } from '@wordpress/data';
import { useBlockProps, InnerBlocks } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';

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

/**
 * 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, clientId }) {
  const wrapperRef = useRef(null);
  const { insertBlock } = useDispatch('core/block-editor');

  // Get the count of inner blocks
  const innerBlocksCount = useSelect(select => {
    const { getBlockCount } = select('core/block-editor');
    return getBlockCount(clientId);
  }, [clientId]);

  // Update the CSS variable when count changes
  useEffect(() => {
    if (wrapperRef.current) {
      wrapperRef.current.style.setProperty('--section-count', innerBlocksCount);
    }
  }, [innerBlocksCount]);

  const blockProps = useBlockProps({
    className: 'parallax-slider-container',
    ref: wrapperRef
  });

  const ALLOWED_BLOCKS = ['orphic-ui/parallax-slider-unit'];
  const TEMPLATE = [
    ['orphic-ui/parallax-slider-unit']
  ];

  const addNewSlide = () => {
    const block = wp.blocks.createBlock('orphic-ui/parallax-slider-unit');
    insertBlock(block, innerBlocksCount, clientId);
  };

  return (
      <div {...blockProps}>
        <SidePanel attributes={attributes} setAttributes={setAttributes} />
        <InnerBlocks
        allowedBlocks={ALLOWED_BLOCKS}
        template={TEMPLATE}
        renderAppender={() => null}
      />
       <Button
        className="add-slide-button"
        variant="primary"
        onClick={addNewSlide}
      >
        {__('Add slide', 'orphic-ui')}
      </Button>
    </div>
  );
}
