<?php
use function App\Core\e;

$categories = $categories ?? [];
$selectedId = (int) ($selectedId ?? 0);
$name = $name ?? 'category_id';
$mode = $mode ?? 'mod';
$firstRoot = (int) ($categories[0]['id'] ?? 0);
foreach ($categories as $root) {
    $ids = array_map(static fn (array $item): int => (int) ($item['id'] ?? 0), $root['children'] ?? []);
    $ids[] = (int) ($root['id'] ?? 0);
    if ($selectedId > 0 && in_array($selectedId, $ids, true)) {
        $firstRoot = (int) ($root['id'] ?? 0);
        break;
    }
}
?>
<div class="category-selector" data-category-selector>
    <input type="hidden" name="<?= e($name) ?>" value="<?= $selectedId > 0 ? $selectedId : '' ?>" data-category-value>
    <div class="category-tabs" role="tablist">
        <?php foreach ($categories as $root): ?>
            <?php $rootId = (int) ($root['id'] ?? 0); ?>
            <button class="<?= $rootId === $firstRoot ? 'is-active' : '' ?>" type="button" data-category-tab="<?= $rootId ?>">
                <?= e($root['name'] ?? 'Kategori') ?>
            </button>
        <?php endforeach; ?>
    </div>
    <div class="category-panels">
        <?php foreach ($categories as $root): ?>
            <?php
            $rootId = (int) ($root['id'] ?? 0);
            $children = $root['children'] ?? [];
            $items = $mode === 'music' || $children === [] ? [$root] : $children;
            ?>
            <div class="category-panel <?= $rootId === $firstRoot ? 'is-active' : '' ?>" data-category-panel="<?= $rootId ?>">
                <?php foreach ($items as $item): ?>
                    <?php $itemId = (int) ($item['id'] ?? 0); ?>
                    <button class="category-card-option <?= $selectedId === $itemId ? 'is-selected' : '' ?>" type="button" data-category-option="<?= $itemId ?>" data-category-label="<?= e($item['name'] ?? '') ?>">
                        <strong><?= e($item['name'] ?? 'Kategori') ?></strong>
                        <span><?= e($item['description'] ?? ($item['slug'] ?? '')) ?></span>
                    </button>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
    </div>
    <div class="field-error" data-error-for="<?= e($name) ?>"></div>
</div>
