<?php
namespace Components\Resources;

use Components\Base;
use Components\Ui\Card;
use Components\Button;

/**
 * ItemListPresentation: A read-only/selection version of ItemList.
 * Provides visual alignment with ItemList but without management interactions
 * (no toggles, no expand flows, no config buttons).
 *
 * Designed for use in selection modals or as a representation of a collection.
 */
class ItemListPresentation
{
    public static function render(array $options): string
    {
        $items = is_array($options['items'] ?? null) ? $options['items'] : [];
        $idKey = (string)($options['id_key'] ?? 'id');
        $nameKey = (string)($options['name_key'] ?? 'name');
        $titleKey = (string)($options['title_key'] ?? $nameKey);
        $subtitleKey = (string)($options['subtitle_key'] ?? 'subtitle');

        $rowActions = is_array($options['row_actions'] ?? null) ? $options['row_actions'] : [];
        $emptyText = (string)($options['empty_text'] ?? \mh_lng('UI_NO_ENTRIES_FOUND', 'No entries found.'));

        $title = (string)($options['title'] ?? '');
        $search = is_array($options['search'] ?? null) ? $options['search'] : null;
        $jsSearch = (bool)($options['js_search'] ?? false);
        $searchModel = (string)($options['search_model'] ?? 'searchQuery');
        $columns = (int)($options['columns'] ?? 1);
        if ($columns < 1) { $columns = 1; }

        $listClass = Card::listStackClass();
        if ($columns === 2) {
            $listClass = Card::listGridClass('grid-cols-1 md:grid-cols-2');
        } elseif ($columns >= 3) {
            $listClass = Card::listGridClass('grid-cols-1 md:grid-cols-2 xl:grid-cols-3');
        }

        ob_start();
        ?>
        <div class="space-y-4" <?php if ($jsSearch && !isset($options['search_model'])): ?>x-data="{ <?= $searchModel; ?>: '' }"<?php endif; ?>>
            <?php if ($title !== '' || $search): ?>
                <div class="flex items-center justify-between gap-4 mb-4">
                    <?php if ($title !== ''): ?>
                        <h3 class="text-sm font-semibold text-secondary uppercase tracking-wider">
                            <?= Base::h($title); ?>
                        </h3>
                    <?php endif; ?>

                    <?php if ($search):
                        $searchValue = (string)($search['value'] ?? '');
                        $searchPlaceholder = (string)($search['placeholder'] ?? \mh_lng('UI_SEARCH', 'Search...'));
                        $searchAttrs = is_array($search['attrs'] ?? null) ? $search['attrs'] : [];
                        
                        if ($jsSearch) {
                            $searchAttrs['x-model.debounce.200ms'] = $searchModel;
                        } else {
                            if (!isset($searchAttrs['hx-trigger'])) { $searchAttrs['hx-trigger'] = 'keyup changed delay:500ms, search'; }
                            if (!isset($searchAttrs['hx-target']) && isset($search['target'])) { $searchAttrs['hx-target'] = $search['target']; }
                            if (!isset($searchAttrs['hx-get']) && isset($search['url'])) { $searchAttrs['hx-get'] = (string)$search['url']; }
                            if (!isset($searchAttrs['hx-push-url'])) { $searchAttrs['hx-push-url'] = 'false'; }
                        }

                        echo \Components\Form\Input::render('search', 'Search', $searchValue, [
                            'no_label' => true,
                            'container_class' => 'flex-1 max-w-xs ml-auto',
                            'prefix_icon_html' => Base::SVG_SEARCH,
                            'show_reset' => true,
                            'input_type' => 'search',
                            'input_attrs' => 'placeholder="' . Base::h($searchPlaceholder) . '" ' . \Components\Resources\ItemList::renderAttrs($searchAttrs),
                        ]);
                    endif; ?>
                </div>
            <?php endif; ?>

            <div class="<?= $listClass; ?>">
                <?php if (empty($items)): ?>
                    <div class="p-8 text-center text-secondary border border-dashed border-divider rounded-2xl">
                        <?= Base::h($emptyText); ?>
                    </div>
                <?php else: ?>
                    <?php foreach ($items as $it):
                        $id = (string)($it[$idKey] ?? '');
                        $rowTitle = (string)($it[$titleKey] ?? '');
                        $rowSubtitle = (string)($it[$subtitleKey] ?? '');

                        $__icon = \Components\Resources\ItemList::buildIcon($it, $options['icon'] ?? null);
                        $iconWrapCls = $__icon['wrapClass'];
                        $iconSvgHtml = $__icon['svgHtml'];
                        $typeLabel = isset($it['type_label']) ? trim((string)$it['type_label']) : '';

                        $xShow = '';
                        if ($jsSearch) {
                            $conditions = ["({$searchModel} === '')"];
                            foreach ([$rowTitle, $rowSubtitle, $typeLabel] as $term) {
                                if ($term === '') continue;
                                $conditions[] = "(" . json_encode($term) . ".toLowerCase().includes({$searchModel}.toLowerCase()))";
                            }
                            $xShow = \Components\Resources\ItemList::renderAttrs(['x-show' => implode(' || ', $conditions)]);
                        }
                        ?>
                        <div <?= $xShow; ?> class="<?= Card::baseContainerClass(false); ?> flex items-center p-3 space-x-4">
                            <!-- Icon -->
                            <?php if ($iconSvgHtml !== ''): ?>
                                <div class="<?= $iconWrapCls; ?> shrink-0">
                                    <?= $iconSvgHtml; ?>
                                </div>
                            <?php endif; ?>

                            <!-- Content -->
                            <div class="flex-1 min-w-0">
                                <div class="text-sm font-medium text-primary leading-none flex items-center gap-1.5 min-w-0">
                                    <span class="truncate"><?= Base::h($rowTitle); ?></span>
                                    <?php if (!empty($it['title_after_html'])): ?>
                                        <span class="inline-flex items-center shrink-0"><?= $it['title_after_html'] ?></span>
                                    <?php endif; ?>
                                    <?php if (!empty($it['name_suffix_html'])): ?>
                                        <span class="text-xs font-normal text-secondary/70 shrink-0">(<?= $it['name_suffix_html'] ?>)</span>
                                    <?php endif; ?>
                                </div>
                                <?php if ($typeLabel !== '' || $rowSubtitle !== '' || isset($it['subline_suffix_html'])): ?>
                                    <div class="text-xs text-secondary/70 truncate mt-1 leading-none">
                                        <?php if ($typeLabel !== ''): ?>
                                            <?= Base::h($typeLabel); ?>
                                        <?php endif; ?>
                                        <?php if ($rowSubtitle !== ''): ?>
                                            <?= ($typeLabel !== '' ? ' &middot; ' : '') . Base::h($rowSubtitle); ?>
                                        <?php endif; ?>
                                        <?php if (isset($it['subline_suffix_html'])): ?>
                                            <?= ($typeLabel !== '' || $rowSubtitle !== '' ? ' &middot; ' : '') . $it['subline_suffix_html']; ?>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Actions -->
                            <?php if (!empty($rowActions)): ?>
                                <div class="flex items-center gap-2 shrink-0 self-center">
                                    <?php foreach ($rowActions as $action):
                                        $label = (string)($action['label'] ?? '');
                                        $url = (string)($action['url'] ?? '');
                                        // Replace {id} in URL
                                        $url = str_replace(['{id}', '%7Bid%7D'], $id, $url);

                                        $variant = (string)($action['variant'] ?? 'secondary');
                                        $size = (string)($action['size'] ?? 'sm');
                                        $icon = (string)($action['icon'] ?? '');
                                        $iconPosition = (string)($action['iconPosition'] ?? 'back');

                                        $attrs = is_array($action['attrs'] ?? null) ? $action['attrs'] : [];
                                        if ($url !== '') {
                                            $attrs['hx-get'] = $url;
                                        }

                                        echo Button::render($label, [
                                            'variant' => $variant,
                                            'size' => $size,
                                            'icon' => $icon,
                                            'iconPosition' => $iconPosition,
                                            'attrs' => $attrs,
                                        ]);
                                    endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
}
