const { useState, useEffect } = wp.element;

const MandatoryCheckboxGroup = ({
    options = [],       // [{ value, label, IconSvg }]
    selectedValues = [], // array of selected values
    onChange,
    direction = 'vertical',
}) => {
    // Ensure at least one is selected initially
    const [selected, setSelected] = useState(
        selectedValues.length > 0 ? selectedValues : [options[0]?.value].filter(Boolean)
    );

    useEffect(() => {
        // Sync prop changes
        if (selectedValues.length > 0 && JSON.stringify(selectedValues) !== JSON.stringify(selected)) {
            setSelected(selectedValues);
        }
    }, [selectedValues]);

    const toggleValue = (val) => {
        let newSelected;
        if (selected.includes(val)) {
            // Only remove if more than one selected
            if (selected.length > 1) {
                newSelected = selected.filter((v) => v !== val);
            } else {
                // Do not allow unselecting the last one
                return;
            }
        } else {
            // Add new selection
            newSelected = [...selected, val];
        }
        setSelected(newSelected);
        onChange?.(newSelected);
    };

    return (
        <div className={`mandatory-checkbox-group ${direction === 'vertical' ? 'flex flex-col' : 'flex'}`}>
            {options.map(({ value, label, icon }) => {
                const isSelected = selected.includes(value);
                return (
                    <button
                        key={value}
                        type="button"
                        className={`mcg-btn ${isSelected ? 'selected' : ''}`}
                        onClick={() => toggleValue(value)}
                        aria-pressed={isSelected}
                    >
                        {icon && (
                            <span className="mcg-icon">
                                {icon}
                            </span>
                        )}
                        <span className="mcg-label">{label}</span>
                    </button>
                );
            })}
        </div>
    );
};

export default MandatoryCheckboxGroup;
