<?php

namespace Components\Ui;

use Components\Base;

class TopBarCount
{
    public static function render(array $options = []): string
    {
        $showWhen = trim((string)($options['show_when'] ?? ''));
        $countExpression = trim((string)($options['count_expression'] ?? 'count'));
        $wrapperClass = trim((string)($options['wrapper_class'] ?? 'absolute top-0.5 right-0.5 pointer-events-none'));
        $badgeClass = trim('flex items-center justify-center size-4 px-1 text-white text-[10px] leading-none tabular-nums font-bold rounded-full ring ring-1.5 ring-muted ' . (string)($options['badge_class'] ?? ''));
        $badgeBindClass = trim((string)($options['badge_bind_class'] ?? ''));

        $badgeAttrs = [
            'class' => $badgeClass,
            'x-text' => $countExpression,
        ];

        if ($badgeBindClass !== '') {
            $badgeAttrs[':class'] = $badgeBindClass;
        }

        ob_start();
        ?>
        <?php if ($showWhen !== '') : ?>
            <template x-if="<?= Base::h($showWhen, false); ?>">
        <?php endif; ?>
        <span <?= Base::attrs(['class' => $wrapperClass, 'x-cloak' => '']); ?>>
            <span <?= Base::attrs($badgeAttrs); ?>></span>
        </span>
        <?php if ($showWhen !== '') : ?>
            </template>
        <?php endif; ?>
        <?php

        return (string)ob_get_clean();
    }
}
