<?php

namespace Components\Ui;

use Components\Base;

/**
 * Reusable UI component to display where a specific resource (template, coupon, audience, etc.) is used.
 */
final class UsageList
{
    /**
     * Renders a categorized and grouped list of usage items.
     *
     * @param array $usage List of usage items as returned by template_manager::resolve_usage_key()
     * @param array $options Configuration options for titles and messages
     * @return string HTML
     */
    public static function render(array $usage, array $options = []): string
    {
        $usageCount = count($usage);
        $title = $options['title'] ?? mh_lng('UI_TITLE_USAGE', 'Nutzung');
        $summarySubject = $options['summary_subject'] ?? '';
        $summaryTemplate = $options['summary_template'] ?? mh_lng('UI_TEXT_USAGE_SUMMARY', '<span class="font-medium text-gray-800">%s</span> wird an <span class="font-medium text-gray-800">%d Stellen</span> verwendet.');
        $emptyMessage = $options['empty_message'] ?? mh_lng('UI_TEXT_USAGE_NOT_USED', 'Dieses Element wird derzeit nicht verwendet.');
        $showGroupingHeader = $options['show_grouping_header'] ?? true;
        $headerActions = $options['header_actions'] ?? [];

        $categories = [
            'Automation' => [
                'title' => mh_lng('UI_LABEL_AUTOMATIONS', 'Automations'),
                'groups' => []
            ],
            'Newsletter' => [
                'title' => mh_lng('UI_LABEL_NEWSLETTERS', 'Newsletters'),
                'groups' => []
            ],
        ];

        foreach ($usage as $item) {
            $type = $item['type'] ?? '';
            $category = ($type === 'newsletter') ? 'Newsletter' : 'Automation';

            // Grouping key: module for traditional Flow, open_key for mb_newsletter
            if ($type === 'flow') {
                $groupKey = 'flow:' . ($item['module'] ?? '');
            } elseif ($type === 'newsletter' || $type === 'automation') {
                $groupKey = $item['open_key'] ?? '';
            } else {
                $groupKey = 'other:' . ($item['module'] ?? 'standalone');
            }

            if (!isset($categories[$category]['groups'][$groupKey])) {
                $categories[$category]['groups'][$groupKey] = [
                    'name' => $item['group_name'] ?? $item['name'] ?? 'Unknown',
                    'items' => []
                ];
            }
            $categories[$category]['groups'][$groupKey]['items'][] = $item;
        }

        ob_start();
        ?>
        <div class="flex flex-col h-full max-h-[inherit]">
            <!-- Header -->
            <?php if ($showGroupingHeader): ?>
            <div class="">
                <div class="rounded-lg bg-divider/30 px-3 py-3 flex items-start justify-between">
                    <div class="min-w-0">
                        <h2 class="text-base font-semibold text-secondary truncate"><?= Base::h($title) ?></h2>
                        <p class="mt-0.5 text-xs text-gray-500">
                            <?= sprintf(
                                $summaryTemplate,
                                Base::h($summarySubject),
                                $usageCount
                            ) ?>
                        </p>
                    </div>
                    <?php if (!empty($headerActions)): ?>
                        <div class="flex items-center gap-1.5 shrink-0 ml-4">
                            <?php foreach ($headerActions as $action): ?>
                                <button type="button"
                                        class="p-1.5 rounded-md text-secondary hover:text-primary hover:bg-white/50 transition-colors [&>svg]:size-4"
                                        <?= Base::attrs($action['attrs'] ?? []) ?>>
                                    <?= $action['icon'] ?? '' ?>
                                </button>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Content -->
            <div class="px-3 py-4 space-y-4 flex-1 overflow-y-auto">
                <?php if ($usageCount > 0): ?>

                <div class="text-xs text-secondary/70"><?= mh_lng('UI_TEXT_USAGE_CLICK_TO_VIEW', 'Klicke auf einen Schritt, um ihn im Flow anzuzeigen.') ?></div>

                <?php foreach ($categories as $catData): ?>
                    <?php if (!empty($catData['groups'])): ?>
                        <!-- <?= Base::h($catData['title']) ?> Section -->
                        <section>
                            <div class="mb-3 flex items-center justify-between border-b border-divider/50 pb-1">
                                <h3 class="text-[10px] font-bold tracking-wider text-secondary/50 uppercase"><?= Base::h($catData['title']) ?></h3>
                            </div>

                            <div class="space-y-6">
                                <?php foreach ($catData['groups'] as $group): ?>
                                    <div class="">
                                        <div class="flex items-center justify-between gap-2">
                                            <div class="min-w-0 truncate text-sm font-medium text-secondary">
                                                <?= Base::h($group['name']) ?>
                                            </div>
                                        </div>

                                        <div class="mt-2 flex flex-wrap gap-1.5">
                                            <?php foreach ($group['items'] as $item): ?>
                                                <?php
                                                $dom_id = $item['dom_id'] ?? '';
                                                $item_dom_id = $item['page_params']['item_dom_id'] ?? $dom_id;
                                                $nav_url = $item['nav_url'] ?? '';
                                                $open_key = $item['open_key'] ?? '';
                                                $type = $item['type'] ?? '';

                                                $highlight_attrs = $item_dom_id ? [
                                                    '@mouseenter' => "\$dispatch('mb:highlight-step', { id: '$item_dom_id' })",
                                                    '@mouseleave' => "\$dispatch('mb:highlight-step', { id: null })",
                                                ] : [];

                                                $detail = [
                                                    'active' => $nav_url,
                                                    'params' => $item['page_params'] ?? [],
                                                    'openKey' => $open_key,
                                                    'highlightId' => $item_dom_id,
                                                    'group' => $item['page_params']['group'] ?? '',
                                                    'type' => $type
                                                ];

                                                $locate_click = "\$dispatch('mb:navigate', " . json_encode($detail) . ")";

                                                $linkAttrs = [];
                                                if (!empty($item['editor_dialog'])) {
                                                    $dialog = $item['editor_dialog'];
                                                    if (($dialog['type'] ?? '') === 'beezui') {
                                                        $linkAttrs = [
                                                            'hx-get' => $dialog['url'],
                                                            'hx-target' => '#' . ($dialog['modal_id'] ?? 'config-modal') . '-body',
                                                            'hx-swap' => 'innerHTML',
                                                            'command' => 'show-modal',
                                                            'commandfor' => ($dialog['modal_id'] ?? 'config-modal'),
                                                            'data-title' => $dialog['title'] ?? '',
                                                            'data-size' => $dialog['size'] ?? 'full',
                                                            'data-body-class' => $dialog['body_class'] ?? ''
                                                        ];
                                                    }
                                                }

                                                $step_label = (!empty($item['step_label'])) ? $item['step_label'] : ($item['name'] ?? 'Step');
                                                ?>
                                                <div class="group inline-flex max-w-full items-center rounded-lg bg-white ring-1 ring-divider hover:bg-brand-50 hover:ring-blue-200 transition-all" <?= Base::attrs($highlight_attrs) ?>>
                                                    <button class="pl-1 pr-2 py-1 text-xs text-gray-700 group-hover:text-blue-600 text-left flex items-center gap-1 [&>svg]:size-3.5! min-w-0" @click="<?= Base::h($locate_click, false) ?>">
                                                        <span class="shrink-0 [&>svg]:size-3.5! text-gray-400 group-hover:text-blue-500"><?= Base::SVG_CHEVRON_LEFT ?></span>
                                                        <span class="truncate">
                                                            <?php if (!empty($item['step_title'])): ?>
                                                                <span class="text-gray-400 group-hover:text-blue-500"><?= Base::h($item['step_title']) ?></span>
                                                            <?php endif; ?>
                                                            <?= Base::h($step_label) ?>
                                                        </span>
                                                    </button>

                                                    <?php if (!empty($linkAttrs)): ?>
                                                        <button <?= Base::attrs($linkAttrs) ?> class="border-l shrink-0 [&>svg]:size-3.5! border-divider px-1.5 py-1 text-gray-400 hover:text-gray-700 opacity-0 group-hover:opacity-100 transition-opacity" title="<?= mh_lng('UI_TITLE_OPEN_EDITOR', 'Editor öffnen') ?>">
                                                            <?= Base::SVG_EDIT ?>
                                                        </button>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </section>
                    <?php endif; ?>
                <?php endforeach; ?>

                <?php else: ?>
                    <div class="py-12 text-center border-2 border-dashed border-divider rounded-lg bg-surface">
                        <p class="text-sm text-secondary"><?= Base::h($emptyMessage) ?></p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }
}
