<?php
namespace Components\Ui;

use Components\Base;
use Components\Data\Live\LiveBeezUIConfigStoreProvider;
use Components\Router;
use Components\Dropdown;
use Components\Button;

final class ListLayout
{
    /** Allowed layout keys */
    public const LAYOUTS = ['stack','grid-2','grid-3','grid-4'];

    public static function current(string $listId): string
    {
        try {
            $p = new LiveBeezUIConfigStoreProvider();
            $val = $p->getListLayout($listId);
            return in_array($val, self::LAYOUTS, true) ? $val : 'stack';
        } catch (\Throwable $e) {
            return 'stack';
        }
    }

    public static function classes(string $layout): string
    {
        switch ($layout) {
            case 'grid-2':
                return 'grid grid-cols-1 md:grid-cols-2 items-start gap-4';
            case 'grid-3':
                return 'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 items-start gap-4';
            case 'grid-4':
                return 'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 items-start gap-4';
            case 'stack':
            default:
                return Card::listStackClass();
        }
    }

    /**
     * Renders layout controls as a Dropdown trigger button with a Columns icon.
     * Items: 1 (stack), 2, 3, 4 columns. Click updates UI immediately via Alpine event and persists via HTMX.
     */
    public static function renderControls(string $listId, array $options = []): string
    {
        $layout = self::current($listId);

        // Build dropdown items (buttons) with HTMX POST + instant Alpine event dispatch
        $makeItem = function (string $key, string $label, string $iconHtml) use ($listId): array {
            return [
                'label' => $label,
                'icon'  => $iconHtml,
                'attrs' => [
                    'hx-post' => Router::url('save_ui_list_layout', ['partial' => 1]),
                    'hx-vals' => Base::h(json_encode(['list_id' => $listId, 'layout' => $key]), false),
                    'hx-swap' => 'none',
                    'data-no-global-loader' => '1',
                    // Update UI immediately using Alpine + a window event; prevent bubbling to parent card click
                    '@click.stop' => "activeLayout='{$key}'; window.dispatchEvent(new CustomEvent('beezui_list_layout_changed', { detail: { listId: '{$listId}', layout: '{$key}' } }));",
                    // Highlight active item reactively inside the menu
                    ':class' => "(activeLayout==='{$key}') ? 'bg-gray-100 text-gray-900!' : ''",
                ],
            ];
        };

        $items = [
            $makeItem('stack', \mh_lng('UI_LAYOUT_LIST', 'List'), Base::SVG_OUTLINE_AUTOFIT_WIDTH),
            $makeItem('grid-2', \mh_lng('UI_LAYOUT_2_COLS', '2 Columns'), Base::SVG_COLUMNS_2),
            $makeItem('grid-3', \mh_lng('UI_LAYOUT_3_COLS', '3 Columns'), Base::SVG_COLUMNS_3),
            $makeItem('grid-4', \mh_lng('UI_LAYOUT_4_COLS', '4 Columns'), Base::SVG_COLUMNS_4),
        ];

        // Allow callers to inject additional menu items (e.g., actions) into the dropdown
        // Options:
        //  - extra_items: list of Dropdown items to append
        //  - divider_before_extra: whether to add a divider before extras (default: true)
        //  - prepend_extra: place items before the defaults (default: false)
        $extraItems = [];
        try {
            if (!empty($options['extra_items']) && is_array($options['extra_items'])) {
                $extraItems = $options['extra_items'];
            }
        } catch (\Throwable $e) {
            $extraItems = [];
        }
        if (!empty($extraItems)) {
            $withDivider = (bool)($options['divider_before_extra'] ?? true);
            if ($withDivider) { $items[] = ['divider' => true]; }
            foreach ($extraItems as $ei) { $items[] = $ei; }
        }

        // Use shared Button (ghost) as the dropdown trigger for consistency
        $triggerButton = Button::render('', [
            'variant' => 'ghost',
            'size'    => 'md',
            'icon'    => Base::SVG_ELLIPSIS_VERTICAL,
            'attrs'   => [
                '@click.stop' => '', // prevent bubbling to parent card click
                'aria-label'  => 'Layout',
                'title'       => 'Layout',
            ],
        ]);

        $dropdownHtml = Dropdown::render([
            'items' => $items,
            'trigger_html' => $triggerButton,
            // Wrap the rendered button without altering its classes
            'trigger_tag' => 'div',
            'wrapper_class' => 'inline-block',
            // Open aligned to end so menu doesn't cover the icon too much in right-aligned toolbars
            'anchor' => 'bottom end',
        ]);

        ob_start();
        ?>
        <div class="inline-block" data-role="list-layout-controls" aria-label="Layout"
             x-data="{ activeLayout: '<?= Base::h($layout) ?>' }"
             @beezui_list_layout_changed.window="if ($event.detail && $event.detail.listId === '<?= Base::h($listId) ?>') { activeLayout = $event.detail.layout }"
        >
            <?= $dropdownHtml ?>
        </div>
        <?php
        return ob_get_clean();
    }
}
