<?php
namespace Components\Ui;

use Components\Button;

/**
 * ExpandControls: renders "Expand all" / "Collapse all" buttons for Alpine lists with openMap.
 * All inline HTML is captured with output buffering and returned as a string.
 *
 * Options:
 * - all_open_init: bool — initial state to avoid flicker (hides Expand button if already all open)
 * - all_closed_init: bool — initial state to avoid flicker (hides Collapse button if already all closed)
 * - expand_label: string (default: 'Expand all')
 * - collapse_label: string (default: 'Collapse all')
 * - expand_attrs: array — extra attributes for Expand button (merged)
 * - collapse_attrs: array — extra attributes for Collapse button (merged)
 */
class ExpandControls
{
    public static function render(array $options = []): string
    {
        $allOpenInit = (bool)($options['all_open_init'] ?? false);
        $allClosedInit = (bool)($options['all_closed_init'] ?? false);
        $expandLabel = (string)($options['expand_label'] ?? 'Expand all');
        $collapseLabel = (string)($options['collapse_label'] ?? 'Collapse all');
        $expandAttrs = is_array($options['expand_attrs'] ?? null) ? $options['expand_attrs'] : [];
        $collapseAttrs = is_array($options['collapse_attrs'] ?? null) ? $options['collapse_attrs'] : [];

        // Defaults aligned with trigger_layout_list
        $expandAttrs = array_replace([
            '@click' => 'expandAll()',
            'data-no-global-loader' => '1',
            'x-show' => '!allOpen()',
            'x-cloak' => true,
            'style' => ($allOpenInit ? 'display:none' : null),
        ], $expandAttrs);
        $collapseAttrs = array_replace([
            '@click' => 'collapseAll()',
            'data-no-global-loader' => '1',
            'x-show' => '!allClosed()',
            'x-cloak' => true,
            'style' => ($allClosedInit ? 'display:none' : null),
        ], $collapseAttrs);

        ob_start();
        ?>
        <div class="flex items-center justify-end gap-2 mb-3 ">
            <?php
            echo Button::render($expandLabel, [ 'size' => 'sm', 'variant' => 'ghost', 'attrs' => $expandAttrs ]);
            echo Button::render($collapseLabel, [ 'size' => 'sm', 'variant' => 'ghost', 'attrs' => $collapseAttrs ]);
            ?>
        </div>
        <?php
        return ob_get_clean();
    }
}
