<?php
// pages/components/trigger_install_dialog.php
require_once BEEZUI_ROOT . '/components/index.php';

use Components\ModuleLoader;
use Components\Button;
use Components\Base;
use Components\Ui\ModuleIdentity;
use Components\Ui\GroupSection;

$layout = \Components\Common\Request::get('layout', 'list', 'string');
$selectedGroup = \Components\Common\Request::get('group', '', 'string');

$uninstalledByGroup = ModuleLoader::campaignsByGroup(false);
// Map of group identifier => localized label
$groupLabels = \beez::groupLabels();
//sleep(25);
ob_start();
?>
<div class="space-y-8">
    <?php if (empty($uninstalledByGroup)): ?>
        <div class="text-center py-10">
            <p class="text-secondary"><?= \mh_lng('UI_ALL_TRIGGER_MODULES_INSTALLED', 'All available trigger modules are already installed.'); ?></p>
        </div>
    <?php else: ?>
        <?php foreach ($uninstalledByGroup as $group => $modules):
            // Resolve translatable group label using beez::groupLabels; fallback to raw group id
            $groupKey = (string)$group;
            $groupLabel = $groupLabels[$groupKey] ?? $groupKey;
            ob_start();
            ?>

            <?php foreach ($modules as $m): ?>
                <div class="group p-4 rounded-xl border border-divider hover:bg-surface hover:border-emphasis transition duration-300">
                    <?php
                    $installButton = Button::render('', [
                        'size' => 'md',
                        'variant' => 'secondary',
                        'icon' => \Components\Base::SVG_PLUS,
                        'rounded' => 'full',
                        'attrs' => [
                            'hx-post' => \Components\Router::url('trigger_install', ['module' => $m['key'], 'layout' => $layout, 'group' => $selectedGroup]),
                            'hx-target' => '#prebuild-section',
                            'hx-swap' => 'innerHTML',
                            'command' => 'close',
                            'commandfor' => 'config-modal',
                        ]
                    ]);

                    echo ModuleIdentity::render($m, [
                        'action' => $installButton,
                        'desc_class' => 'text-secondary', // Match original opacity
                    ]);
                    ?>
                </div>
            <?php endforeach; ?>
            <?php
            $groupContent = ob_get_clean();

            echo GroupSection::render($groupLabel, $groupContent, [
                'container_class' => 'grid grid-cols-1 md:grid-cols-2 gap-4',
                // Use a fixed, pre-rendered grid without user-switchable layouts
                'layout_controls' => false,
            ]);
        endforeach; ?>
    <?php endif; ?>
</div>
<?php
echo ob_get_clean();
