<?php
namespace Components\Resources;

use Components\Base;
use Components\Dropdown;
use Components\Router;
use Components\Ui\CollectionIdentity;

/**
 * CollectionsList: compact, sidebar-style list of "collections" with counts.
 * Intended for NewsletterCampaign collections, but generic enough for similar use.
 * All inline HTML is captured with ob_start and returned as a string.
 *
 * Options:
 * - items: array of [ id, name, slug, dot_class, count, is_archived? ]
 *           for cards layout also: card_bg, card_bg_active, icon
 * - selected_slug: slug of the active collection (string)
 * - page_key: used to determine hx-target container id (defaults to 'newsletter')
 * - layout: 'cards' for card grid layout, anything else = default list layout
 * - new_action: optional array [ label, url, attrs (array), variant ] to open modal/drawer
 * - outer_attrs: string attributes applied to the outer container (e.g., id="..." hx-swap-oob="...")
 *
 * renderSectionDropdown() Options:
 * - items: same dropdown items array as Dropdown::render() (label, attrs, divider, icon)
 * - anchor: dropdown anchor string (default: 'bottom end')
 */
class CollectionsList
{
    /**
     * Render a context dropdown button suitable for a collapsible section title row.
     * Returns HTML string. Uses Dropdown::render() internally for consistency with the
     * item-level dropdowns in the list layout.
     *
     * @param array $opts
     *   - items: array  Dropdown items (same format as Dropdown::render() items)
     *   - anchor: string  (default 'bottom end')
     * @return string
     */
    public static function renderSectionDropdown(array $opts = []): string
    {
        $items  = is_array($opts['items'] ?? null) ? $opts['items'] : [];
        $anchor = (string)($opts['anchor'] ?? 'bottom end');

        if (empty($items)) {
            return '';
        }

        return Dropdown::render([
            'trigger_html'  => Base::SVG_ELLIPSIS_HORIZONTAL_CIRCLE_OUTLINE,
            'trigger_tag'   => 'button',
            'trigger_attrs' => [
                'type'        => 'button',
                'class'       => 'shrink-0 text-secondary opacity-0 group-hover/section:opacity-100 transition-opacity [&_svg]:size-4',
                '@click.stop' => '',
                'onmousedown' => 'event.stopPropagation();',
                'aria-label'  => \mh_lng('UI_COLLECTIONS_SECTION_ACTIONS', 'Section actions'),
            ],
            'wrapper_class' => 'shrink-0 size-4 opacity-50 hover:opacity-100 transition-opacity',
            'anchor'        => $anchor,
            'items'         => $items,
        ]);
    }
    public static function render(array $options): string
    {
        $items = is_array($options['items'] ?? null) ? $options['items'] : [];
        $pageKey = (string)($options['page_key'] ?? 'newsletter');
        $layout  = (string)($options['layout'] ?? 'list');
        $isCards = ($layout === 'cards');
        $showDescription = !empty($options['show_description']);

        ob_start();

        // Helper to render the cards grid layout
        $renderCards = function () use ($items, $pageKey) {
            if (empty($items)) {
                echo '<div class="text-sm ">' . \mh_lng('UI_COLLECTIONS_EMPTY_SMART', 'No smart collections.') . '</div>';
                return;
            }
            echo '<div class="grid grid-cols-2 gap-2 px-1 pt-1">';
            foreach ($items as $c) {
                $slug         = (string)($c['slug'] ?? '');
                $slugEsc      = Base::h($slug, false);
                $name         = Base::h((string)($c['name'] ?? \mh_lng('UI_COLLECTIONS_UNTITLED', 'Untitled')));
                $count        = (int)($c['count'] ?? 0);
                $cardBg       = (string)($c['card_bg'] ?? 'bg-gray-400/70');
                $cardBgActive = (string)($c['card_bg_active'] ?? 'bg-gray-400/90');
                $icon         = (string)($c['icon'] ?? '');
                $full         = Router::url('newsletter', $slug !== '' ? ['group' => $slug] : []);
                $partial      = Router::url('newsletter_items_list', array_merge(['partial' => 1], $slug !== '' ? ['group' => $slug] : []));
                ?>
                <div class="relative flex flex-col rounded-xl text-white hover:opacity-90 p-2.5 cursor-pointer min-h-16 transition-all [&_svg]:size-4"
                     href="<?= $full; ?>"
                     hx-get="<?= $partial; ?>"
                     hx-target="<?= Base::h('#' . $pageKey . '-items-list'); ?>"
                     hx-swap="outerHTML"
                     data-no-global-loader="1"
                     data-no-local-loader="0"
                     data-slug="<?= $slugEsc; ?>"
                     @click="selectedSlug = '<?= $slugEsc; ?>'"
                     :class="selectedSlug === '<?= $slugEsc; ?>' ? '<?= Base::h($cardBgActive, false); ?> ring-2 ring-white/30' : '<?= Base::h($cardBg, false); ?>'"
                     :aria-current="selectedSlug === '<?= $slugEsc; ?>' ? 'true' : 'false'"
                >
                    <div class="flex items-start justify-between">
                        <span class="opacity-90"><?= $icon; ?></span>
                        <span class="text-lg font-bold leading-none normal-nums"><?= $count; ?></span>
                    </div>
                    <div class="mt-auto pt-2 text-sm font-semibold leading-tight"><?= $name; ?></div>
                </div>
                <?php
            }
            echo '</div>';
        };

        // Helper to render just the list body (flat structure)
        $renderList = function () use ($items, $pageKey, $options, $showDescription) {
            if (empty($items)) {
                $extraParams = is_array($options['empty_state_url_params'] ?? null) ? $options['empty_state_url_params'] : [];
                $newUrl = Router::url('newsletter_collection_modal', array_merge(['partial' => 1, 'mode' => 'new'], $extraParams));
                ob_start(); ?>
                <div class="flex flex-col items-center gap-2 py-4 text-center">
                    <p class="text-sm text-secondary"><?= \mh_lng('UI_COLLECTIONS_EMPTY', 'No collections.') ?></p>
                    <?= \Components\Button::render((string)\mh_lng('UI_COLLECTIONS_NEW', 'New collection'), [
                        'variant' => 'ghost',
                        'size' => 'sm',
                        'icon' => \Components\Base::SVG_PLUS,
                        'iconPosition' => 'front',
                        'attrs' => [
                            'command' => 'show-modal',
                            'commandfor' => 'config-modal',
                            'data-title' => \mh_lng('UI_COLLECTIONS_NEW_TITLE', 'New Collection'),
                            'data-size' => 'xl',
                            'hx-get' => $newUrl,
                            'hx-target' => '#config-modal-body',
                            'hx-swap' => 'innerHTML',
                            'data-no-global-loader' => '1',
                        ],
                    ]); ?>
                </div>
                <?php echo ob_get_clean();
                return;
            }
            echo '<nav class="space-y-1">';
            foreach ($items as $c) {
                $id   = (int)($c['id'] ?? 0);
                $slug = (string)($c['slug'] ?? '');
                $full = Router::url('newsletter', $slug !== '' ? ['group' => $slug] : []);
                $partial = Router::url('newsletter_items_list', array_merge(['partial' => 1], $slug !== '' ? ['group' => $slug] : []));
                // Prefer Tailwind classes for the dot; support legacy 'color' key if it already contains utilities.
                $dotClass = (string)($c['dot_class'] ?? '');
                if ($dotClass === '') {
                    $legacyColor = (string)($c['color'] ?? '');
                    if ($legacyColor !== '' && (preg_match('/\b(bg|text|ring|border|fill|stroke)-/i', $legacyColor) || strpos($legacyColor, ' ') !== false)) {
                        $dotClass = $legacyColor; // treat provided utilities as-is
                    }
                }
                if ($dotClass === '') { $dotClass = 'bg-gray-400'; }
                $name  = Base::h((string)($c['name'] ?? \mh_lng('UI_COLLECTIONS_UNTITLED', 'Untitled')));
                $description = trim((string)($c['description'] ?? ''));
                $count = (int)($c['count'] ?? 0);
                // Actions are available only for real (non-smart) campaigns
                $hasActions  = $id > 0;
                $isArchived  = !empty($c['is_archived']);
                $archiveLabel = $isArchived
                    ? \mh_lng('UI_COLLECTIONS_UNARCHIVE', 'Unarchive')
                    : \mh_lng('UI_COLLECTIONS_ARCHIVE', 'Archive');
                $archiveIcon = $isArchived ? Base::SVG_OUTLINE_UNARCHIVE : Base::SVG_OUTLINE_ARCHIVE;
                $slugEsc = Base::h($slug, false);

                $identityOpts = [];
                if ($showDescription && $description !== '') {
                    $identityOpts['secondary_html'] = Base::h($description);
                }
                $identityHtml = CollectionIdentity::render($name, $dotClass, $identityOpts);

                // Build action URLs when needed
                $renameUrl  = $hasActions ? Router::url('newsletter_collection_modal', ['partial' => 1, 'mode' => 'edit', 'id' => $id]) : '';
                $archiveUrl = $hasActions ? Router::url('newsletter_collection_archive', ['id' => $id]) : '';
                $deleteUrl  = ($hasActions && $count === 0) ? Router::url('newsletter_collection_delete', ['partial' => 1, 'id' => $id]) : '';

                // Build dropdown using the Dropdown component (el-dropdown/el-menu handles its own open state)
                $dropdownHtml = '';
                if ($hasActions) {
                    $menuItems = [
                        [
                            'label' => \mh_lng('UI_COLLECTIONS_RENAME', 'Edit'),
                            'icon'  => Base::SVG_EDIT,
                            'attrs' => [
                                '@click.stop'        => '',
                                'command'            => 'show-modal',
                                'commandfor'         => 'config-modal',
                                'data-title'         => \mh_lng('UI_COLLECTIONS_RENAME_TITLE', 'Edit collection'),
                                'data-size'          => 'md',
                                'hx-get'             => $renameUrl,
                                'hx-target'          => '#config-modal-body',
                                'hx-swap'            => 'innerHTML',
                                'data-no-global-loader' => '1',
                            ],
                        ],
                        [
                            'label' => $archiveLabel,
                            'icon'  => $archiveIcon,
                            'attrs' => [
                                '@click.stop'        => '',
                                'hx-post'            => $archiveUrl,
                                'hx-target'          => 'this',
                                'hx-swap'            => 'none',
                                'data-no-global-loader' => '1',
                            ],
                        ],
                    ];

                    if ($count === 0 && $deleteUrl !== '') {
                        $menuItems[] = ['divider' => true];
                        $menuItems[] = [
                            'label' => \mh_lng('UI_COLLECTIONS_DELETE', 'Delete'),
                            'icon'  => Base::SVG_TRASH,
                            'attrs' => [
                                '@click.stop'        => '',
                                'command'            => 'show-modal',
                                'commandfor'         => 'confirm-modal',
                                'data-title'         => \mh_lng('UI_COLLECTIONS_DELETE_TITLE', 'Delete collection'),
                                'data-type'          => 'danger',
                                'hx-get'             => $deleteUrl,
                                'hx-target'          => '#confirm-modal-body',
                                'hx-swap'            => 'innerHTML',
                                'data-no-global-loader' => '1',
                            ],
                        ];
                    }

                    $dropdownHtml = Dropdown::render([
                        'trigger_html' => Base::SVG_ELLIPSIS_HORIZONTAL_CIRCLE_OUTLINE,
                        'trigger_tag'  => 'button',
                        'trigger_attrs' => [
                            'type'        => 'button',
                            'class'       => 'shrink-0 text-secondary opacity-0 group-hover/collection:opacity-100 transition-opacity [&_svg]:size-4',
                            '@click.stop' => '',
                            'onmousedown' => 'event.stopPropagation();',
                            'aria-label'  => \mh_lng('UI_COLLECTIONS_ACTIONS', 'Collection actions'),
                        ],
                        'wrapper_class' => 'shrink-0 size-4 opacity-50 hover:opacity-100 transition-opacity',
                        'anchor'        => 'bottom end',
                        'items' => $menuItems,
                    ]);
                }
                ?>
                <div class="group/collection relative flex <?= $showDescription ? 'items-start' : 'items-center'; ?> gap-1 rounded px-2 py-2 text-sm hover:bg-muted cursor-pointer"
                     href="<?= $full; ?>"
                     hx-get="<?= $partial; ?>"
                     hx-target="<?= Base::h('#' . $pageKey . '-items-list'); ?>"
                     hx-swap="outerHTML"
                     data-no-global-loader="1"
                     data-no-local-loader="0"
                     data-slug="<?= Base::h($slug); ?>"
                     @click="selectedSlug = '<?= $slugEsc; ?>'"
                     :class="selectedSlug === '<?= $slugEsc; ?>' ? 'text-brand ring ring-2 ring-brand/50' : 'text-secondary'"
                     :aria-current="selectedSlug === '<?= $slugEsc; ?>' ? 'true' : 'false'"
                >
                    <?= $identityHtml; ?>
                    <?= $dropdownHtml; ?>
                    <span class="text-xs text-secondary shrink-0 min-w-12 text-right px-1"><?= $count; ?></span>
                </div>
                <?php
            }
            echo '</nav>';
        };


        // Render in the requested layout
        if ($isCards) {
            $renderCards();
        } else {
            $renderList();
        }

        return ob_get_clean();
    }
}
