/**
 * Field Palette - Drag-and-drop source for form fields
 */

import { __ } from '@wordpress/i18n';
import { Icon } from '@wordpress/icons';
import { FIELD_CATEGORIES, getFieldTypesByCategory } from '../../config/fieldTypes';
import './FieldPalette.css';

export default function FieldPalette({ onDragStart }) {
    const fieldTypesByCategory = getFieldTypesByCategory();
    const categories = Object.values(FIELD_CATEGORIES).sort((a, b) => a.order - b.order);

    const handleDragStart = (event, fieldType) => {
        event.dataTransfer.effectAllowed = 'copy';
        event.dataTransfer.setData('formipay-field-type', fieldType);
        onDragStart?.(fieldType);
    };

    return (
        <div className="formipay-field-palette">
            <h3>{ __('Add Field', 'formipay') }</h3>

            {categories.map((category) => {
                const fields = fieldTypesByCategory[category.label] || [];
                if (fields.length === 0) return null;

                return (
                    <div key={category.label} className="formipay-palette-category">
                        <h4>{ category.label }</h4>
                        <div className="formipay-palette-items">
                            {fields.map((field) => (
                                <div
                                    key={field.type}
                                    className="formipay-palette-item"
                                    draggable
                                    onDragStart={(e) => handleDragStart(e, field.type)}
                                    title={field.label}
                                >
                                    <Icon icon={field.icon} />
                                    <span>{ field.label }</span>
                                </div>
                            ))}
                        </div>
                    </div>
                );
            })}
        </div>
    );
}
