import { useBlockProps, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, ToggleControl, Notice, Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useState, useEffect } from '@wordpress/element';
import './editor.scss';
export default function Edit({ attributes, setAttributes }) {
const { sectionOrder, showSectionTitles, collapseByDefault } = attributes;
const [sections, setSections] = useState([]);
// Get sections from localized script
const allSections = window.jvbFaq?.sections || [];
// Initialize sections with proper ordering
useEffect(() => {
if (!allSections.length) return;
if (sectionOrder.length === 0) {
// First time - use default order
const orderedSections = allSections.map(section => ({
id: section.id,
name: section.name,
}));
setSections(orderedSections);
setAttributes({ sectionOrder: orderedSections.map(s => s.id) });
} else {
// Use saved order, add any new sections at the end
const orderedSections = [];
const existingIds = new Set(sectionOrder);
// Add sections in saved order
sectionOrder.forEach(id => {
const section = allSections.find(s => s.id === id);
if (section) {
orderedSections.push({ id: section.id, name: section.name });
}
});
// Add any new sections that weren't in the saved order
allSections.forEach(section => {
if (!existingIds.has(section.id)) {
orderedSections.push({ id: section.id, name: section.name });
}
});
setSections(orderedSections);
}
}, [allSections, sectionOrder]);
const moveSection = (index, direction) => {
const newSections = [...sections];
const newIndex = direction === 'up' ? index - 1 : index + 1;
if (newIndex < 0 || newIndex >= newSections.length) return;
// Swap sections
[newSections[index], newSections[newIndex]] = [newSections[newIndex], newSections[index]];
setSections(newSections);
setAttributes({ sectionOrder: newSections.map(s => s.id) });
};
const blockProps = useBlockProps({
className: 'faq-block-editor',
});
return (
<>
{__('Use the arrow buttons to reorder sections', 'jvb')}
{__('This block will display FAQs organized by sections.', 'jvb')}
{sections.length > 0 ? (