<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Visual;

final class DesignerFieldsIntegrationRuntime
{
    public function fieldToGridColumn(array $field): array
    {
        return [
            'id' => (string) ($field['name'] ?? 'field') . '_column',
            'type' => 'grid_column',
            'field' => (string) ($field['name'] ?? 'field'),
            'name' => (string) ($field['name'] ?? 'field'),
            'label' => (string) ($field['label'] ?? $this->humanize((string) ($field['name'] ?? 'field'))),
            'dataType' => (string) ($field['type'] ?? 'text'),
            'source' => 'field-drop',
        ];
    }

    public function fieldToFormControl(array $field): array
    {
        return [
            'id' => (string) ($field['name'] ?? 'field') . '_field',
            'type' => 'field',
            'field' => (string) ($field['name'] ?? 'field'),
            'name' => (string) ($field['name'] ?? 'field'),
            'label' => (string) ($field['label'] ?? $this->humanize((string) ($field['name'] ?? 'field'))),
            'controlType' => $this->controlType((string) ($field['type'] ?? 'text')),
            'source' => 'field-drop',
        ];
    }

    public function fieldBadges(array $fields): array
    {
        return array_map(fn (array $field): array => [
            'name' => (string) ($field['name'] ?? 'field'),
            'label' => (string) ($field['label'] ?? $this->humanize((string) ($field['name'] ?? 'field'))),
            'type' => (string) ($field['type'] ?? 'text'),
            'icon' => $this->iconFor((string) ($field['type'] ?? 'text')),
            'draggable' => true,
        ], $fields);
    }

    private function controlType(string $type): string
    {
        return match ($type) {
            'int','integer','number','decimal','float' => 'number',
            'date' => 'date',
            'datetime','timestamp' => 'datetime',
            'text','longtext' => 'textarea',
            'bool','boolean' => 'checkbox',
            default => 'text',
        };
    }

    private function iconFor(string $type): string
    {
        return match ($type) {
            'int','integer','number','decimal','float' => 'bi-123',
            'date','datetime','timestamp' => 'bi-calendar',
            'email' => 'bi-envelope',
            'bool','boolean' => 'bi-toggle-on',
            default => 'bi-input-cursor-text',
        };
    }

    private function humanize(string $value): string
    {
        return ucwords(str_replace(['_', '-'], ' ', $value));
    }
}
