<?php
namespace Components\Ui;

use Components\Base;
use Components\Ui\Card;
use Components\Ui\ListLayout;
use Components\Ui\ExpandControls;

/**
 * GroupSection: reusable UI component for a section with a heading and content.
 */
class GroupSection
{
    /**
     * Renders a group section.
     *
     * @param string $title The heading text
     * @param string $content The HTML content of the section
     * @param array $options UI options:
     *   - container_class: classes for the content container div (default: 'space-y-4')
     *   - section_class: classes for the outer container (default: '')
     *   - list_id: stable id to persist user-chosen layout (auto from title by default)
     *   - layout_controls: bool to show layout controls and dynamic grid switching (default: true)
     *   - expand_controls: bool to render Expand/Collapse controls in header (default: false)
     *   - expand_group_keys: array of ids used by Alpine openMap to scope expand/collapse to this group
     *   - expand_all_open_init: bool — initial state hint (avoid flicker)
     *   - expand_all_closed_init: bool — initial state hint (avoid flicker)
     * @return string
     */
    public static function render(string $title, string $content, array $options = []): string
    {
        // Determine a stable list id for layout persistence. Can be overridden via options['list_id']
        $listId = $options['list_id'] ?? strtolower(trim(preg_replace('/[^a-z0-9]+/i', '-', $title)));
        $enableLayoutControls = array_key_exists('layout_controls', $options) ? (bool)$options['layout_controls'] : true;
        $currentLayout = $enableLayoutControls ? ListLayout::current($listId) : 'stack';
        // We will bind layout classes dynamically via Alpine; allow callers to pass extra classes only
        $containerClass = $options['container_class'] ?? '';
        $sectionClass = $options['section_class'] ?? '';

        // Expand/Collapse controls configuration (group-scoped)
        $enableExpandControls = (bool)($options['expand_controls'] ?? false);
        $expandKeys = is_array($options['expand_group_keys'] ?? null) ? ($options['expand_group_keys'] ?? []) : [];
        $expandInitAllOpen = (bool)($options['expand_all_open_init'] ?? false);
        $expandInitAllClosed = (bool)($options['expand_all_closed_init'] ?? false);

        // Optional extra header content areas
        // - header_left: raw HTML rendered to the left of the controls, next to the title
        // - header_right: raw HTML appended to the right controls block
        $headerLeft = (string)($options['header_left'] ?? '');
        $hasHeaderLeft = (trim($headerLeft) !== '');
        $headerRight = (string)($options['header_right'] ?? '');

        // When layout controls are disabled and no explicit container classes are provided,
        // default to a simple stacked layout with vertical spacing to match prior behavior.
        if (!$enableLayoutControls && $containerClass === '') {
            $containerClass = 'space-y-4';
        }

        // Ghost header mode: when title is an empty string, render header without bottom border and padding
        $ghostHeader = (trim($title) === '');
        $headerClass = 'flex items-center justify-between mb-4' . ($ghostHeader ? '' : ' border-b border-divider pb-2');

        ob_start();
        ?>
        <div class="<?= $sectionClass ?>">
            <div class="<?= $headerClass ?>">
                <div class="flex items-center min-h-9 <?= $hasHeaderLeft ? ' gap-3' : '' ?>">
                    <?php if ($hasHeaderLeft): ?>
                        <?= $headerLeft ?>
                    <?php endif; ?>
                    <h3 class="text-sm font-semibold text-secondary uppercase tracking-wider">
                        <?= Base::h($title) ?>
                    </h3>
                    <?php if (!empty($options['title_html'])): ?>
                        <?= $options['title_html'] ?>
                    <?php endif; ?>
                </div>
                <div class="shrink-0 flex items-center gap-2  text-secondary/70 hover:text-secondary" aria-label="Section controls">
                    <?php
                    // Header right-side custom HTML (e.g., filters)
                    if ($headerRight !== '') {
                        echo '<span class="flex items-center gap-2">' . $headerRight . '</span>';
                    }

                    if ($enableExpandControls) {
                        // Build default group-scoped handlers that rely on functions defined in parent Alpine scope
                        $keysJson = json_encode(array_values(array_unique(array_map('strval', $expandKeys))));
                        echo ExpandControls::render([
                            'all_open_init' => $expandInitAllOpen,
                            'all_closed_init' => $expandInitAllClosed,
                            // Icon-only mode must be group-scoped (otherwise it would expand/collapse all groups)
                            'all_closed_expr' => "allClosedSome($keysJson)",
                            'expand_action' => "expandSome($keysJson)",
                            'collapse_action' => "collapseSome($keysJson)",
                            'expand_attrs' => [
                                '@click' => "expandSome($keysJson)",
                                'x-show' => "!allOpenSome($keysJson)",
                            ],
                            'collapse_attrs' => [
                                '@click' => "collapseSome($keysJson)",
                                'x-show' => "!allClosedSome($keysJson)",
                            ],
                            'wrapper_class' => 'flex items-center gap-2',
                        ]);
                    }

                    if ($enableLayoutControls) {
                        $layoutOptions = is_array($options['layout_controls_options'] ?? null) ? ($options['layout_controls_options'] ?? []) : [];
                        echo '<span aria-label="List layout">' . ListLayout::renderControls($listId, $layoutOptions) . '</span>';
                    }
                    ?>
                </div>
            </div>
            <?php if ($enableLayoutControls): ?>
                <div 
                    x-data="{ layout: '<?= Base::h($currentLayout) ?>', clsMap: { 'stack':'space-y-4', 'grid-2':'grid grid-cols-1 md:grid-cols-2 items-start gap-4', 'grid-3':'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 items-start gap-4', 'grid-4':'grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 items-start gap-4' } }"
                    data-list-id="<?= Base::h($listId) ?>"
                    @beezui_list_layout_changed.window="if ($event.detail && $event.detail.listId === '<?= Base::h($listId) ?>') { layout = $event.detail.layout }"
                >
                    <div class="<?= $containerClass ?>" :class="clsMap[layout]">
                        <?= $content ?>
                    </div>
                </div>
            <?php else: ?>
                <div>
                    <div class="<?= $containerClass ?>">
                        <?= $content ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }
}
