<?php
// components/Form/Presentation/ValuePresenter.php
// Dispatcher presenter that delegates to specialized presenters for display logic

namespace Components\Form\Presentation;

class ValuePresenter
{
    /**
     * @return array<string, string>
     */
    protected static function pillboxLookup(array $def): array
    {
        $src = [];
        if (isset($def['items']) && is_array($def['items'])) {
            $src = $def['items'];
        } elseif (isset($def['options']) && is_array($def['options'])) {
            $src = $def['options'];
        } elseif (isset($def['values']) && is_array($def['values'])) {
            $src = $def['values'];
        }

        if (empty($src)) {
            return [];
        }

        $out = [];
        $isAssoc = array_keys($src) !== range(0, count($src) - 1);
        if ($isAssoc) {
            foreach ($src as $key => $item) {
                if (is_array($item)) {
                    $id = (string)($item['id'] ?? $item['value'] ?? $item['key'] ?? $key);
                    $name = (string)($item['name'] ?? $item['label'] ?? $item['text'] ?? $id);
                    if ($id !== '') {
                        $out[$id] = $name;
                    }
                    continue;
                }
                $id = (string)$key;
                if ($id !== '') {
                    $out[$id] = (string)$item;
                }
            }
            return $out;
        }

        foreach ($src as $item) {
            if (is_array($item)) {
                $id = (string)($item['id'] ?? $item['value'] ?? $item['key'] ?? '');
                if ($id === '') {
                    continue;
                }
                $out[$id] = (string)($item['name'] ?? $item['label'] ?? $item['text'] ?? $id);
                continue;
            }
            $id = (string)$item;
            if ($id !== '') {
                $out[$id] = $id;
            }
        }
        return $out;
    }

    protected static function renderPillBoxValue($value, array $def): string
    {
        $lookup = self::pillboxLookup($def);

        if (is_string($value)) {
            $trimmed = trim($value);
            if ($trimmed === '') {
                $value = [];
            } else {
                $decoded = json_decode($trimmed, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    $value = $decoded;
                } else {
                    $value = array_map('trim', explode(',', $trimmed));
                }
            }
        }

        $arr = is_array($value) ? $value : [$value];
        $parts = [];
        foreach ($arr as $item) {
            if (is_array($item)) {
                $id = (string)($item['id'] ?? $item['value'] ?? $item['key'] ?? '');
                $name = (string)($item['name'] ?? $item['label'] ?? $item['text'] ?? '');
                if ($name === '' && $id !== '') {
                    $name = $lookup[$id] ?? $id;
                }
                if ($name !== '') {
                    $parts[] = $name;
                }
                continue;
            }
            $id = (string)$item;
            if ($id === '') {
                continue;
            }
            $parts[] = $lookup[$id] ?? $id;
        }

        $parts = array_values(array_unique(array_filter($parts, 'strlen')));
        $text = implode(', ', $parts);
        if ($text === '') {
            $text = \mh_lng('UI_EM_DASH', '—');
        }
        return \Components\Base::h($text);
    }

    /**
     * Render a configuration value for display based on its field definition
     */
    public static function render($value, array $def): string
    {

        $type = strtolower((string)($def['type'] ?? 'input'));
        $vType = strtolower((string)($def['validate']['type'] ?? ''));

        // Rich Select: find label from options
        if (($type === 'rich_select' || $type === 'select') && isset($def['options']) && is_array($def['options'])) {
            $valStr = (string)$value;
            foreach ($def['options'] as $optVal => $optDef) {
                if ((string)$optVal === $valStr) {
                    if (is_array($optDef)) {
                        $label = $optDef['label'] ?? $optDef['text'] ?? $valStr;
                        // Support identity/icon for rich rendering
                        if (isset($optDef['identity']) || isset($optDef['dot_class']) || isset($optDef['icon'])) {
                            $identity = $optDef['identity'] ?? $optDef['dot_class'] ?? 'bg-gray-400';
                            return \Components\Ui\CollectionIdentity::render(\Components\Base::h($label), $identity, $optDef);
                        }
                        return \Components\Base::h($label);
                    }
                    return \Components\Base::h($optDef);
                }
            }
        }

        // Coupon card
        if ($type === 'coupon') {
            return CouponPresenter::render($value, $def);
        }

        // Arrays (e.g., multi-select)
        if ($type === 'pillbox' || $type === 'pill_box') {
            return self::renderPillBoxValue($value, $def);
        }

        if (is_array($value)) {
            if ($type === 'order_status_multiple') {
                return OrderStatusMultiplePresenter::render($value, $def);
            }
            return ArrayPresenter::render($value, $def);
        }

        // Booleans
        if ($type === 'toggle' || $type === 'checkbox' || $vType === 'boolean') {
            return BoolPresenter::render($value, $def);
        }

        // Delay days
        if ($type === 'delay_days') {
            return DelayDaysPresenter::render($value, $def);
        }

        // Order status multiple (CSV string)
        if ($type === 'order_status_multiple') {
            return OrderStatusMultiplePresenter::render($value, $def);
        }

        // Default string rendering
        return DefaultPresenter::render($value, $def);
    }
}
