import { __ } from '@wordpress/i18n';
import { 
  InspectorControls, 
  MediaUpload, 
  MediaUploadCheck 
} from '@wordpress/block-editor';
import { useState, 
  useEffect, 
  FC 
} from 'react';
import { useSelect } from '@wordpress/data';
import {
  PanelBody,
  SelectControl,
  Button,
  ToggleControl,
  TextControl,
  __experimentalNumberControl as NumberControl,
  __experimentalUnitControl as UnitControl,
  TabPanel,
  __experimentalBorderControl as BorderControl,
  TextareaControl,
  Popover
} from '@wordpress/components';
import metadata from './block.json';
import './editor.scss';

//Import the LcpGallery component
import LcpGallery from '../components/LightGallery';


const galleryElements = [
  {
    src:
      "https://images.unsplash.com/photo-1542103749-8ef59b94f47e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80",
    responsive:
      "https://images.unsplash.com/photo-1542103749-8ef59b94f47e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=480&q=80 480, https://images.unsplash.com/photo-1542103749-8ef59b94f47e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80 800",
    thumb:
      "https://images.unsplash.com/photo-1542103749-8ef59b94f47e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=240&q=80",
    subHtml: (
      <div className="lightGallery-captions">
        <h4>
          Photo by <a href="https://unsplash.com/@dann">Dan</a>
        </h4>
        <p>Published on November 13, 2018</p>
      </div>
    ),
  },
  {
    src:
      "https://images.unsplash.com/photo-1473876988266-ca0860a443b8?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=1400&q=80",
    responsive:
      "https://images.unsplash.com/photo-1473876988266-ca0860a443b8?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=480&q=80 480, https://images.unsplash.com/photo-1473876988266-ca0860a443b8?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80 800",
    thumb:
      "https://images.unsplash.com/photo-1473876988266-ca0860a443b8?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=240&q=80",
    subHtml: (
      <div className="lightGallery-captions">
        <h4>
          Photo by <a href="https://unsplash.com/@kylepyt">Kyle Peyton</a>
        </h4>
        <p>Published on September 14, 2016</p>
      </div>
    ),
  },
]





// Aspect ratio options
const aspectRatioOptions = [
  { value: '1-1', label: __('1:1', metadata.textdomain) },
  { value: '16-9', label: __('16:9', metadata.textdomain) },
  { value: '3-2', label: __('3:2', metadata.textdomain) },
  { value: '5-7', label: __('5:7', metadata.textdomain) },
  { value: '3-4', label: __('3:4', metadata.textdomain) },
  { value: '4-5', label: __('4:5', metadata.textdomain) },
  { value: '2-3', label: __('2:3', metadata.textdomain) }
];

// Check if JetEngine or ACF/SCF are activated and get their gallery field data
const { apiFetch } = wp;

apiFetch({ path: '/custom/v1/get-gallery-supported-plugins-data' })
  .then((data) => {
      console.log(data);  // Log the entire data object
      if (data.jetengine_active) {
       console.log('Jet Engine is activated');
      // Other logic here
    }
  })
  .catch((error) => {
    console.error('Error fetching Jet Engine status:', error);
  });


const MultiMediaUpload = ({ onSelect }) => {
  const [mediaIds, setMediaIds] = useState([]);

  const handleSelectMedia = (media) => {
    const selectedMedia = media.map((item) => ({
      id: item.id,
      url: item.url,
      alt: item.alt || ''
    }));
    setMediaIds(selectedMedia);
    onSelect(selectedMedia);
  };

  return (
    <MediaUploadCheck>
      <MediaUpload
        onSelect={handleSelectMedia}
        allowedTypes={['image', 'video']}
        multiple
        gallery
        render={({ open }) => (
          <Button onClick={open} isPrimary>
            {__('Open Media Library')}
          </Button>
        )}
      />
    </MediaUploadCheck>
  );
};

export default function Edit(props) {
  const { attributes, setAttributes } = props;
  const {
    galleryItems = [],
    source,
    sourceMetaField,
    sourceTable,
    sourceColumn,
    includePostThumbnail,
    initialLayout,
    itemsAspectRatio,
    gridColumnsLarge,
    gridColumnsMedium,
    gridColumnsSmall,
    gridGapLarge,
    gridGapMedium,
    gridGapSmall,

    download,

    downloadSize,

    maxInitialItems,
    thumbnail,
    inlineHeightLarge,
    inlineHeightMedium,
    inlineHeightSmall,
    justifiedRowHeightSmall,
    justifiedRowHeightMedium,
    justifiedRowHeightLarge,
    justifiedLastRow,
    thumbnailsBorders,
    thumbnailsBordersSelected,
    thumbnailsStyle,
    thumbnailActiveStyle,
    showCaptions,
    zoomFromOrigin,
    galleryCustomStyles,
    lgSettings
  } = attributes;

  // Handle Updating LightGallery settings
  const [settings, setSettings] = useState(lgSettings);
  

  const [borders, setBorders] = useState(thumbnailsBorders || {
    top: { color: '#000000', style: 'solid', width: '1px' },
    right: { color: '#000000', style: 'solid', width: '1px' },
    bottom: { color: '#000000', style: 'solid', width: '1px' },
    left: { color: '#000000', style: 'solid', width: '1px' }
  });

  const [selectedBorders, setSelectedBorders] = useState(thumbnailsBordersSelected || {
    top: { color: '#000000', style: 'solid', width: '1px' },
    right: { color: '#000000', style: 'solid', width: '1px' },
    bottom: { color: '#000000', style: 'solid', width: '1px' },
    left: { color: '#000000', style: 'solid', width: '1px' }
  });

  const handleSelectMedia = (selectedMedia) => {
    setAttributes({ galleryItems: selectedMedia });
  };

  const handleBorderChange = (newBorders) => {
    setBorders(newBorders);
    setAttributes({ thumbnailsBorders: newBorders });
  };

  const handleBorderSelectedChange = (newBorders) => {
    setSelectedBorders(newBorders);
    setAttributes({ thumbnailsBordersSelected: newBorders });
  };



  // lightGallery Transistion Styles  
  const lgTransitionStyles = [
    { label: 'lg-slide', value: 'lg-slide' },
    { label: 'lg-fade', value: 'lg-fade' },
    { label: 'lg-zoom-in', value: 'lg-zoom-in' },
    { label: 'lg-zoom-in-big', value: 'lg-zoom-in-big' },
    { label: 'lg-zoom-out', value: 'lg-zoom-out' },
    { label: 'lg-zoom-out-big', value: 'lg-zoom-out-big' },
    { label: 'lg-zoom-out-in', value: 'lg-zoom-out-in' },
    { label: 'lg-zoom-in-out', value: 'lg-zoom-in-out' },
    { label: 'lg-soft-zoom', value: 'lg-soft-zoom' },
    { label: 'lg-scale-up', value: 'lg-scale-up' },
    { label: 'lg-slide-circular', value: 'lg-slide-circular' },
    { label: 'lg-slide-circular-vertical', value: 'lg-slide-circular-vertical' },
    { label: 'lg-slide-vertical', value: 'lg-slide-vertical' },
    { label: 'lg-slide-vertical-growth', value: 'lg-slide-vertical-growth' },
    { label: 'lg-slide-skew-only', value: 'lg-slide-skew-only' },
    { label: 'lg-slide-skew-only-rev', value: 'lg-slide-skew-only-rev' },
    { label: 'lg-slide-skew-only-y', value: 'lg-slide-skew-only-y' },
    { label: 'lg-slide-skew-only-y-rev', value: 'lg-slide-skew-only-y-rev' },
    { label: 'lg-slide-skew', value: 'lg-slide-skew' },
    { label: 'lg-slide-skew-rev', value: 'lg-slide-skew-rev' },
    { label: 'lg-slide-skew-cross', value: 'lg-slide-skew-cross' },
    { label: 'lg-slide-skew-cross-rev', value: 'lg-slide-skew-cross-rev' },
    { label: 'lg-slide-skew-ver', value: 'lg-slide-skew-ver' },
    { label: 'lg-slide-skew-ver-rev', value: 'lg-slide-skew-ver-rev' },
    { label: 'lg-slide-skew-ver-cross', value: 'lg-slide-skew-ver-cross' },
    { label: 'lg-slide-skew-ver-cross-rev', value: 'lg-slide-skew-ver-cross-rev' },
    { label: 'lg-lollipop', value: 'lg-lollipop' },
    { label: 'lg-lollipop-rev', value: 'lg-lollipop-rev' },
    { label: 'lg-rotate', value: 'lg-rotate' },
    { label: 'lg-rotate-rev', value: 'lg-rotate-rev' },
    { label: 'lg-tube', value: 'lg-tube' }
  ];

  const galleryClasses = `lcp-gallery ${initialLayout}`;


  const lgPluginRequirements = [
    { setting: 'zoom', plugin: 'lgZoom' },
    { setting: 'thumbnail', plugin: 'lgThumbnail' },
    { setting: 'rotate', plugin: 'lgRotate' },
    { setting: 'autoplay', plugin: 'lgAutoplay' },
    { setting: 'fullScreen', plugin: 'lgFullScreen' },
    { setting: 'download', plugin: 'lgDownload' },
    // Add more settings and corresponding plugins as needed
  ];



// Retrieve current post type, post ID, and check if it's a template mode using useSelect
const { isTemplate, postType, postId } = useSelect((select) => {
    const editor = select('core/editor');
    const currentPostType = editor.getCurrentPostType();
    const currentPostId = editor.getCurrentPostId();
    const isTemplateMode = currentPostType === 'wp_template';

    return {
        isTemplate: isTemplateMode,
        postType: currentPostType,
        postId: currentPostId
    };
}, []); // Empty array ensures the hook runs once during the component lifecycle

    let sourceOptions = [];
    
    if (isTemplate) {
        sourceOptions = [
          { value: 'manual', label: __('Manually Select', metadata.textdomain) },
          { value: 'lcpPostGallery', label: __('Post Gallery', metadata.textdomain) },
          { value: 'metaField', label: __('Meta field of current post', metadata.textdomain) },
          { value: 'linkedTable', label: __('Linked Table', metadata.textdomain) }    ];
        // Add logic to adjust block's behavior when editing a template
    } else {
        sourceOptions = [
          { value: 'manual', label: __('Manually Select', metadata.textdomain) },
          { value: 'lcpPostGallery', label: __('Post Gallery', metadata.textdomain) }
        ];
        // Add logic for post/page editing mode
    }
  
    const updateLgSetting = (key, value) => {
      setAttributes({
        lgSettings: {
          ...lgSettings,
          [key]: value,
        },
      });
    };
  
    // Function to toggle plugins (add/remove a plugin)
    const togglePlugin = (plugin, enable) => {
      setAttributes({
        lgSettings: {
          ...lgSettings,
          plugins: enable
            ? [...lgSettings.plugins, plugin] // Add the plugin if enabled
            : lgSettings.plugins.filter((p) => p !== plugin), // Remove the plugin if disabled
        },
      });
    };
  
    // Toggle Control for enabling 'Hash' and updating the plugin array
    const handleToggleHash = (value) => {
      updateLgSetting('hash', value);
      togglePlugin('lgHash', value); // Add/Remove lgHash plugin based on toggle value
    };
  
    // Example control for enabling 'Zoom' and updating the plugin array
    const handleToggleZoom = (value) => {
      updateLgSetting('zoom', value);
      togglePlugin('lgZoom', value); // Add/Remove lgZoom plugin based on toggle value
    };

  return (
    <>
      
      {/* The Gallery */}
       <LightGallery {...attributes.lgSettings} />
 
      <InspectorControls>
        {/* Settings and Style Tabs */}
        <TabPanel
          className="my-tab-panel"
          activeClass="active-tab"
          tabs={[
            {
              name: 'settings',
              title: __('Settings'),
              className: 'settings-tab'
            },
            {
              name: 'style',
              title: __('Style Settings'),
              className: 'style-tab'
            }
          ]}
        >
          {({ name }) => {
            if (name === 'settings') {
              return (
                <>
                  {/* Source Settings */}
                  <PanelBody title={__('Source Settings')}>
                    <SelectControl
                      label={__('Gallery Items Source', metadata.textdomain)}
                      value={source}
                      onChange={(newValue) => setAttributes({ source: newValue })}
                      options={sourceOptions}
                    />
                    {source === 'manual' && <MultiMediaUpload onSelect={handleSelectMedia} />}
                    {source === 'metaField' && (
                      <TextControl
                        label={__('Meta Field Name')}
                        value={sourceMetaField}
                        onChange={(newValue) => setAttributes({ sourceMetaField: newValue })}
                      />
                    )}
                    {source === 'linkedTable' && (
                      <>
                        <TextControl
                          label={__('Table Name')}
                          value={sourceTable}
                          onChange={(newValue) => setAttributes({ sourceTable: newValue })}
                        />
                        <TextControl
                          label={__('Column Name')}
                          value={sourceColumn}
                          onChange={(newValue) => setAttributes({ sourceColumn: newValue })}
                        />
                      </>
                    )}
                    {/* Parse an element for gallery items */}
                    <ToggleControl
                      checked={attributes.parseElementForItems}
                      label={__('Parse element for gallery items', metadata.textdomain)}
                      onChange={(value) => {
                        setAttributes({
                          parseElementForItems: value, // Set as a boolean directly
                        });
                      }}
                    />

                      {attributes.parseElementForItems && (
                        <TextControl
                          label={__('Elements to parse')}
                          value={attributes.parsedTargetElement} // Corrected to use string directly
                          onChange={(newValue) => setAttributes({ parsedTargetElement: newValue })}
                        />
                      )}
                    <ToggleControl
                      onChange={(isChecked) => setAttributes({ includePostThumbnail: isChecked })}
                      checked={includePostThumbnail}
                      label={__('Include Post Thumbnail (Featured Image)', metadata.textdomain)}
                    />

                  </PanelBody>
                  {/* Display Settings */}
                  <PanelBody title={__('Display Settings')}>
                  <SelectControl
                      label={__('Initial Layout', metadata.textdomain)}
                      value={initialLayout}
                      onChange={(newValue) => {
                        // Update the initialLayout attribute
                        setAttributes({
                          initialLayout: newValue,
                          lgSettings: {
                            ...attributes.lgSettings, // Preserve existing lgSettings
                            closable: newValue !== 'inline',  // Set closable based on the layout choice
                            showMaximizeIcon: newValue === 'inline',  // Show maximize icon only if 'inline' is selected
                          }
                        });
                      }}
                      options={[
                        { value: 'inline', label: __('Inline', metadata.textdomain) },
                        { value: 'grid', label: __('Grid', metadata.textdomain) },
                        { value: 'button', label: __('Button', metadata.textdomain) }
                      ]}
                    />

                    <ToggleControl
                      onChange={(isChecked) => setAttributes({ includePostThumbnail: isChecked })}
                      checked={includePostThumbnail}
                      label={__('Include Post Thumbnail (Featured Image)', metadata.textdomain)}
                    />
                    {initialLayout === 'button' && (
                      <TextControl
                        label={__('Button Text')}
                        value={sourceColumn}
                        onChange={(newValue) => setAttributes({ sourceColumn: newValue })}
                      />
                    )
                    }
              <ToggleControl
                onChange={(isChecked) => {
                  // Check if lgSettings exists, then update thumbnail value
                  setAttributes({
                    lgSettings: {
                      ...attributes.lgSettings,  // Keep the existing lgSettings intact
                      thumbnail: isChecked,  // Update the thumbnail value
                    }
                  });
                }}
                checked={attributes.lgSettings?.thumbnail}  // Ensure the checkbox reflects the current thumbnail setting
                label={__('Show Thumbnails', metadata.textdomain)}
              />

                    {thumbnail && (
                      <>
                        <SelectControl
                          label={__('Thumbnails Position - Desktop', metadata.textdomain)}
                          value={itemsAspectRatio}
                          onChange={(newValue) => setAttributes({ itemsAspectRatio: newValue })}
                          options={[
                            { value: 'bottom', label: __('Bottom', metadata.textdomain) },
                            { value: 'right', label: __('Right', metadata.textdomain) },
                            { value: 'left', label: __('Left', metadata.textdomain) },
                            { value: 'hidden', label: __('Hidden', metadata.textdomain) }
                          ]}
                        />
                        <SelectControl
                          label={__('Thumbnails Position - Tablet', metadata.textdomain)}
                          value={itemsAspectRatio}
                          onChange={(newValue) => setAttributes({ itemsAspectRatio: newValue })}
                          options={[
                            { value: 'bottom', label: __('Bottom', metadata.textdomain) },
                            { value: 'right', label: __('Right', metadata.textdomain) },
                            { value: 'left', label: __('Left', metadata.textdomain) },
                            { value: 'hidden', label: __('Hidden', metadata.textdomain) }
                          ]}
                        />
                        <SelectControl
                          label={__('Thumbnails Position - Mobile', metadata.textdomain)}
                          value={itemsAspectRatio}
                          onChange={(newValue) => setAttributes({ itemsAspectRatio: newValue })}
                          options={[
                            { value: 'bottom', label: __('Bottom', metadata.textdomain) },
                            { value: 'right', label: __('Right', metadata.textdomain) },
                            { value: 'left', label: __('Left', metadata.textdomain) },
                            { value: 'hidden', label: __('Hidden', metadata.textdomain) }
                          ]}
                        />
                      </>
                    )}
                    {initialLayout !== 'inline' && initialLayout !== 'justified' && (
                      <SelectControl
                        label={__('Items Aspect Ratio', metadata.textdomain)}
                        value={itemsAspectRatio}
                        onChange={(newValue) => setAttributes({ itemsAspectRatio: newValue })}
                        options={aspectRatioOptions}
                      />
                    )}
                    {initialLayout !== 'inline' && (
                      <NumberControl
                        label={__('Max Initial Images')}
                        onChange={(newValue) => setAttributes({ maxInitialItems: 1})}
                        value={maxInitialItems}
                        isShiftStepEnabled
                        shiftStep={1}
                        min={0}
                      />
                    )}
                  </PanelBody>
                  {/* Gallery Settings */}
                  <PanelBody title={__('Gallery Settings')}>
                  {/* Include option to show maximize icon if inline gallery */}
                  {attributes.initialLayout === 'inline' && (
                    <ToggleControl
                        label={__('Show maximize icon', metadata.textdomain)}
                        checked={attributes.lgSettings.showMaximizeIcon}
                        onChange={(isChecked) => setAttributes({ 
                        lgSettings: { 
                          ...attributes.lgSettings,  // Preserve existing lgSettings
                          showMaximizeIcon: true, // Set the showMaximizeIcon based on the toggle
                          }
                        })}
                      />
                    )}

                    {/* Dynamic Settings */}
                    <ToggleControl
                      label={__('Dynamic Load', 'lcp')}
                      checked={lgSettings.dynamic}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            ['dynamic']: value,
                          }
                        });
                      }}
                    />
                    {/* Zoom Settings - Zoom requires lgZoom plugin */}
                    <ToggleControl
                      label={__('Enable Zoom', 'lcp')}
                      checked={lgSettings.zoom}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            zoom: value, // Update the zoom setting
                            plugins: value
                              ? [...lgSettings.plugins, 'lgZoom'] // Add lgFullScreen plugin if enabled
                              : lgSettings.plugins.filter(plugin => plugin !== 'lgZoom'), // Remove lgFullScreen plugin if disabled
                          },
                        });
                      }}
                    />
                    {/* Fullscreen Settings - fullScreen requires lgFullscreen plugin */}
                    <ToggleControl
                      label={__('Enable Fullscreen', 'lcp')}
                      checked={lgSettings.fullScreen}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            fullScreen: value, // Update the zoom setting
                            plugins: value
                              ? [...lgSettings.plugins, 'lgFullScreen'] // Add lgFullScreen plugin if enabled
                              : lgSettings.plugins.filter(plugin => plugin !== 'lgFullScreen'), // Remove lgFullScreen plugin if disabled
                          },
                        });
                      }}
                    />
                    {/* Sharing Settings - Sharing requires lgShare plugin */}
                    <ToggleControl
                      label={__('Enable Sharing', 'lcp')}
                      checked={lgSettings.share}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            share: value, // Update the zoom setting
                            plugins: value
                              ? [...lgSettings.plugins, 'lgShare'] // Add lgShare plugin if enabled
                              : lgSettings.plugins.filter(plugin => plugin !== 'lgShare'), // Remove lgShare plugin if disabled
                          },
                        });
                      }}
                    />
                    {/* Autoplay Settings - Autoplay requires lgAutoplay plugin */}
                    <ToggleControl
                      label={__('Enable Autoplay', 'lcp')}
                      checked={lgSettings.autoplay}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            autoplay: value, // Update the zoom setting
                            plugins: value
                              ? [...lgSettings.plugins, 'lgAutoplay'] // Add lgAutoplay plugin if enabled
                              : lgSettings.plugins.filter(plugin => plugin !== 'lgAutoplay'), // Remove lgAutoplay plugin if disabled
                          },
                        });
                      }}
                    />

                    {/* HASH SETTINGS - Hashrequires lghash plugin */}
                    <ToggleControl
                      label={__('Enable Hash', 'lcp')}
                      checked={lgSettings.hash}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            hash: value, // Update the zoom setting
                            plugins: value
                              ? [...lgSettings.plugins, 'lgHash'] // Add lgAutoplay plugin if enabled
                              : lgSettings.plugins.filter(plugin => plugin !== 'lgHash'), // Remove lgAutoplay plugin if disabled
                          },
                        });
                      }}
                    />
                    {/* Hash requires a unique id in lgSettings.galleryId */}
                    {lgSettings.hash && (
                      <TextControl
                        label={__('Hash', 'lcp')}
                        value={lgSettings.hashGalleryId}  // Use an appropriate value for this input
                        onChange={(newValue) => {
                          setAttributes({
                            lgSettings: {
                              ...lgSettings,
                              galleryId: newValue,  // Update the hashValue based on the text input
                            }
                          });
                        }}
                      />
                    )}

                    <ToggleControl
                      label={__('Zoom From Origin', 'lcp')}
                      checked={lgSettings.zoomFromOrigin}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            zoomFromOrigin: value, // Update the zoomFromOrigin setting
                          },
                        });
                      }}
                    />
                    {/*Captions Settings */}
                    <ToggleControl
                      onChange={(isChecked) => setAttributes({ showCaptions: isChecked })}
                      checked={showCaptions}
                      label={__('Show Captions', metadata.textdomain)}
                    />

                    {/*Download Controls - If download is true, show options to set download size */}
                    <ToggleControl
                      checked={lgSettings.download}
                      label={__('Allow Download', metadata.textdomain)}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            ['download']: value,
                          },
                        });
                      }}
                    />
                    {/* Options to set available download size */}
                    {download && (
                      <SelectControl
                        label={__('Download Size', metadata.textdomain)}
                        value={downloadSize}
                        onChange={(newValue) => setAttributes({ downloadSize: newValue })}
                        options={[
                          { value: 'full', label: __('Full', metadata.textdomain) },
                          { value: 'medium', label: __('Medium', metadata.textdomain) },
                          { value: 'large', label: __('Large', metadata.textdomain) }
                        ]}
                      />
                    )}
                    {/* Add the SelectControl for Transition */}
                    <SelectControl
                      label="Transition Style"
                      value={lgSettings.mode || 'lg-slide'} // Default value is 'lg-slide'
                      options={lgTransitionStyles}
                      onChange={(value) => {
                        // Update autoplay
                        setAttributes({
                          lgSettings: {
                            ...lgSettings,
                            ['mode']: value,
                          }
                        });
                      }}
                    />
                    {/* Add the TextControl for specific container to open the gallery in*/}
                    {/* If the initial layout is inline, the gallery opens in .lcp-gallery */}
                    {initialLayout != "inline"}{
                    <TextControl
                          label={__('Open gallery in container')}
                          value={lgSettings.container}
                          onChange={(newValue) => setAttributes({     lgSettings: {
                            ...lgSettings,  // spread the current lgSettings object
                            container: newValue  // update only the container property
                          } })}
                        />
                    }
                  </PanelBody>
                </>
              );
            }

            if (name === 'style') {
              return (
                <PanelBody title={__('Style Settings')}>
                  {initialLayout === 'inline' && (
                    <>
                      <UnitControl
                        label={__('Inline Height - Desktop')}
                        onChange={(value) => setAttributes({ inlineHeightLarge: value })}
                        value={inlineHeightLarge}
                      />
                      <UnitControl
                        label={__('Inline Height - Tablet')}
                        onChange={(value) => setAttributes({ inlineHeightMedium: value })}
                        value={inlineHeightMedium}
                      />
                      <UnitControl
                        label={__('Inline Height - Mobile')}
                        onChange={(value) => setAttributes({ inlineHeightSmall: value })}
                        value={inlineHeightSmall}
                      />
                    </>
                  )}
                  {initialLayout === 'justified' && (
                    <>
                      <SelectControl
                        label={__('Last Row', metadata.textdomain)}
                        value={justifiedLastRow}
                        onChange={(newValue) => setAttributes({ justifiedLastRow: newValue })}
                        options={[
                          { value: 'justify', label: __('Justify', metadata.textdomain) },
                          { value: 'nojustify', label: __('Unjustified', metadata.textdomain) },
                          { value: 'left', label: __('Align Left', metadata.textdomain) },
                          { value: 'center', label: __('Align Center', metadata.textdomain) },
                          { value: 'right', label: __('Align Right', metadata.textdomain) },
                          { value: 'hide', label: __('Hide', metadata.textdomain) }
                        ]}
                      />
                      <UnitControl
                        label={__('Row Height - Desktop')}
                        onChange={(value) => setAttributes({ justifiedRowHeightLarge: value })}
                        value={justifiedRowHeightLarge}
                      />
                      <UnitControl
                        label={__('Row Height - Tablet')}
                        onChange={(value) => setAttributes({ justifiedRowHeightMedium: value })}
                        value={justifiedRowHeightMedium}
                      />
                      <UnitControl
                        label={__('Row Height - Mobile')}
                        onChange={(value) => setAttributes({ justifiedRowHeightSmall: value })}
                        value={justifiedRowHeightSmall}
                      />
                    </>
                  )}
                  {initialLayout === 'grid' && (
                    <>
                      <NumberControl
                        label={__('Grid Columns - Desktop')}
                        onChange={(newValue) => setAttributes({ gridColumnsLarge: newValue })}
                        value={gridColumnsLarge}
                        isShiftStepEnabled
                        shiftStep={1}
                        min={1}
                        max={9}
                      />
                      <NumberControl
                        label={__('Grid Columns - Tablet')}
                        onChange={(newValue) => setAttributes({ gridColumnsMedium: newValue })}
                        value={gridColumnsMedium}
                        isShiftStepEnabled
                        shiftStep={1}
                        min={1}
                        max={9}
                      />
                      <NumberControl
                        label={__('Grid Columns - Mobile')}
                        onChange={(newValue) => setAttributes({ gridColumnsSmall: newValue })}
                        value={gridColumnsSmall}
                        isShiftStepEnabled
                        shiftStep={1}
                        min={1}
                        max={9}
                      />
                      <NumberControl
                        label={__('Grid Gap')}
                        onChange={(newValue) => setAttributes({ gridGapLarge: newValue })}
                        value={gridGapLarge}
                        isShiftStepEnabled
                        shiftStep={1}
                        min={0}
                      />
                    </>
                  )}
                  {thumbnail && (
                    <>
                      <BorderControl
                        label={__('Thumbnail Borders')}
                        value={borders}
                        onChange={handleBorderChange}
                      />
                      <BorderControl
                        label={__('Thumbnail Borders - Selected')}
                        value={thumbnailsBordersSelected}
                        onChange={handleBorderSelectedChange}
                      />
                      <SelectControl
                        label={__('Thumbnail Style', metadata.textdomain)}
                        value={thumbnailsStyle}
                        onChange={(newValue) => setAttributes({ thumbnailsStyle: newValue })}
                        options={[
                          { value: '', label: __('None', metadata.textdomain) },
                          { value: 'lg-thumbnail-blur', label: __('Blur', metadata.textdomain) },
                          { value: 'lg-thumbnail-grayscale', label: __('Monochrome', metadata.textdomain) }
                        ]}
                      />
                      <SelectControl
                        label={__('Thumbnail Style - Selected', metadata.textdomain)}
                        value={thumbnailActiveStyle}
                        onChange={(newValue) => setAttributes({ thumbnailActiveStyle: newValue })}
                        options={[
                          { value: '', label: __('None', metadata.textdomain) },
                          { value: 'lg-thumbnail-active-grayscale', label: __('Monochrome', metadata.textdomain) },
                          { value: 'lg-thumbnail-active-blur', label: __('Blur', metadata.textdomain) }

                        ]}
                      />
                    </>
                  )}


                </PanelBody>
              );
            }
          }}



        </TabPanel>
      </InspectorControls>
    </>
  );
}

