<?php
// pages/trigger.php (renamed from campaigns.php)
require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

use Components\ModuleLoader;
use Components\SortStore;
use Components\Router;
$pageKey = 'trigger';
$targetContainer = \Components\Data\DataRegistry::navigation()->getTargetId($pageKey);
$subtabParam = \Components\Router::subtabParam();


// Handle save via HTMX POST for campaign sorting (moved from campaigns_sort.php)
if ((mh_server('REQUEST_METHOD', 'GET') === 'POST') && mh_post('order', null) !== null) {
    // Accept either comma-separated string or JSON array under 'order'
    $raw = (string) mh_post('order', '', 'string');
    $list = [];
    if ($raw !== '') {
        if ($raw[0] === '[') {
            $decoded = json_decode($raw, true);
            if (is_array($decoded)) {
                foreach ($decoded as $v) {
                    if (is_string($v)) $list[] = $v;
                }
            }
        } else {
            $parts = explode(',', $raw);
            foreach ($parts as $p) {
                $p = trim($p);
                if ($p !== '') $list[] = $p;
            }
        }
    }
    SortStore::setCampaignOrderFromList($list);

    // Preserve all current URL parameters except routing/partial flags
    $keep = [];
    $pageParam = Router::pageParam();
    $tabParam = Router::tabParam();
    foreach (\Components\Common\Request::all('get') as $k => $v) {
        if ($k === 'partial' || $k === $pageParam || $k === $tabParam) continue;
        $keep[$k] = $v;
    }
    header('HX-Redirect: ' . Router::url('trigger', $keep));
    exit;
}

// Load campaign modules grouped by e-commerce touchpoints from a single source
$modulesByTouchpoint = ModuleLoader::campaignsByGroup();

// Optional group filter coming from Wizard (or direct navigation)
$selectedGroup = mh_get('group', '', 'string');
$selectedGroup = trim($selectedGroup);
$hasFilter = $selectedGroup !== '' && isset($modulesByTouchpoint[$selectedGroup]);
if ($hasFilter) {
    $modulesByTouchpoint = [$selectedGroup => $modulesByTouchpoint[$selectedGroup]];
}

// Apply persisted sort order within groups (0 = top)
$modulesByTouchpoint = SortStore::applyOrderToGrouped($modulesByTouchpoint);

// Read and validate layout mode
$allowedLayouts = ['list', 'tiles', 'compact'];
$layout = mh_get('layout', 'list', 'string');
if (!in_array($layout, $allowedLayouts, true)) {
    $layout = 'tiles';
}

// Read and validate sub-tab selection
$allowedTabs = ['prebuild', 'custom'];
$subtab = mh_get($subtabParam, 'prebuild', 'string');
if (!in_array($subtab, $allowedTabs, true)) {
    $subtab = 'prebuild';
}

// Helper to build a campaigns URL keeping current filters
$baseArgs = ['partial' => 1, 'layout' => $layout, $subtabParam => $subtab];
if ($hasFilter) {
    $baseArgs['group'] = $selectedGroup;
}

// SECTION partial rendering helpers
$renderPrebuild = function () use ($modulesByTouchpoint, $hasFilter, $selectedGroup, $layout, $targetContainer, $subtabParam, $baseArgs) {
    ob_start();
    ?>
    <div>
        <div class="flex items-end justify-between gap-4 mb-2 mt-4">
            <div class="hidden">
                <h3 class="text-lg font-semibold text-primary mb-1">Campaign
                    Modules<?= $hasFilter ? (' — ' . \Components\Base::h($selectedGroup)) : ''; ?></h3>
                <p class="text-sm text-secondary">Browse prebuilt automation modules grouped by your e-commerce
                    touchpoints.</p>
            </div>
            <div class="flex items-center gap-3">
                <div class="hidden">
                    <?= \Components\Button::render('Sort order', [
                        'size' => 'sm',
                        'variant' => 'secondary',
                        'attrs' => [
                            'title' => 'Sort order (0 = top)',
                            'command' => 'show-modal',
                            'commandfor' => 'config-drawer',
                            'hx-get' => \Components\Router::url('trigger_sort', array_merge(['partial' => 1, 'layout' => $layout], $hasFilter ? ['group' => $selectedGroup] : [])),
                            'hx-target' => '#config-drawer-body',
                            'hx-swap' => 'innerHTML',
                        ],
                        'icon' => '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-4 ms-2"><path stroke-linecap="round" stroke-linejoin="round" d="M3 7.5 7.5 3m0 0L12 7.5M7.5 3v13.5m13.5 0L16.5 21m0 0L12 16.5m4.5 4.5V7.5"/></svg>',
                    ]); ?>
                </div>

                <?php if ($hasFilter) { ?>
                    <button class="text-sm link"
                            hx-get="<?= \Components\Router::url('trigger', array_merge(['partial' => 1, 'layout' => $layout, $subtabParam => 'prebuild'], [])); ?>"
                            hx-target="<?= $targetContainer; ?>"
                            hx-swap="innerHTML"
                            hx-push-url="<?= \Components\Router::url('trigger', array_merge($hasFilter ? [] : [], ['layout' => $layout, $subtabParam => 'prebuild'])); ?>">
                        Show all
                    </button>
                <?php } ?>
                <?php
                // Layout switcher using ButtonGroup
                $mkUrl = function (string $mode) use ($hasFilter, $selectedGroup, $subtabParam) {
                    $args = ['partial' => 1, 'layout' => $mode, $subtabParam => 'prebuild'];
                    if ($hasFilter) {
                        $args['group'] = $selectedGroup;
                    }
                    return \Components\Router::url('trigger', $args);
                };
                $items = [
                    [
                        'html' => '<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7h16M4 12h16M4 17h16"></path></svg>',
                        'active' => ($layout === 'list'),
                        'attrs' => [
                            'title' => 'List',
                            'hx-get' => $mkUrl('list'),
                            'hx-target' => $targetContainer,
                            'hx-swap' => 'innerHTML',
                            'hx-push-url' => \Components\Router::url('trigger', array_merge($hasFilter ? ['group' => $selectedGroup] : [], ['layout' => 'list', $subtabParam => 'prebuild'])),
                        ],
                    ],
                    [
                        'html' => '<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h7v7H4V6zm9 0h7v7h-7V6zM4 13h7v7H4v-7zm9 0h7v7h-7v-7z"></path></svg>',
                        'active' => ($layout === 'tiles'),
                        'attrs' => [
                            'title' => 'Tiles',
                            'hx-get' => $mkUrl('tiles'),
                            'hx-target' => '<?= $targetContainer; ?>',
                            'hx-swap' => 'innerHTML',
                            'hx-push-url' => \Components\Router::url('trigger', array_merge($hasFilter ? ['group' => $selectedGroup] : [], ['layout' => 'tiles', $subtabParam => 'prebuild'])),
                        ],
                    ],
                    [
                        'html' => '<svg class="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h10M4 12h8M4 16h6"></path></svg>',
                        'active' => ($layout === 'compact'),
                        'attrs' => [
                            'title' => 'Compact',
                            'hx-get' => $mkUrl('compact'),
                            'hx-target' => '<?= $targetContainer; ?>',
                            'hx-swap' => 'innerHTML',
                            'hx-push-url' => \Components\Router::url('trigger', array_merge($hasFilter ? ['group' => $selectedGroup] : [], ['layout' => 'compact', $subtabParam => 'prebuild'])),
                        ],
                    ],
                ];
                // echo \Components\ButtonGroup::render($items, [
                //         'size' => 'sm',
                //         'class' => 'border border-divider bg-surface shadow-sm overflow-hidden',
                //         'ariaLabel' => 'Layout mode selector',
                // ]);
                ?>
            </div>
        </div>

        <?php
        // Render selected layout from extracted partials
        $partialMap = [
            'tiles' => __DIR__ . '/components/trigger_layout_tiles.php',
            'list' => __DIR__ . '/components/trigger_layout_list.php',
            'compact' => __DIR__ . '/components/trigger_layout_compact.php',
        ];
        $partial = $partialMap[$layout] ?? $partialMap['tiles'];
        include $partial; // expects $modulesByTouchpoint in scope
        ?>
        <script>
            (function () {
                try {
                    var refreshUrl = <?= json_encode(\Components\Router::url('trigger', $baseArgs)); ?>;
                    function refresh() {
                        try { htmx.ajax('GET', refreshUrl, '<?= $targetContainer; ?>'); } catch (e) {}
                    }
                    window.addEventListener('campaigns-sort-saved', function () { setTimeout(refresh, 50); });
                } catch (e) {}
            })();
        </script>
    </div>
    <?php
    return ob_get_clean();
};

$renderCustom = function () {
    ob_start();
    ?>
    <div class="mt-4">
        <?php
        // Reusable Collections + Flows UI for Trigger → Custom tab
        $selectedGroup = mh_get('group', '', 'string');
        $layout = mh_get('layout', 'tiles', 'string');
        include __DIR__ . '/components/flows_collections.php';
        ?>
    </div>
    <?php
    return ob_get_clean();
};

// Serve partial section only (for htmx lazy-load containers)
$section = mh_get('section', '', 'string');
if (mh_get('partial', 0, 'int') && ($section === 'prebuild' || $section === 'custom')) {
    if ($section === 'prebuild') {
        echo $renderPrebuild();
    } else {
        echo $renderCustom();
    }
    exit;
}

// Build URLs for section lazy loads
$prebuildSectionUrl = \Components\Router::url('trigger', array_merge(
    $hasFilter ? ['group' => $selectedGroup] : [],
    ['partial' => 1, 'section' => 'prebuild', 'layout' => $layout, $subtabParam => 'prebuild']
));
$customSectionUrl = \Components\Router::url('trigger', array_merge(
    $hasFilter ? ['group' => $selectedGroup] : [],
    ['partial' => 1, 'section' => 'custom', 'layout' => 'tiles', $subtabParam => 'custom']
));

ob_start();
?>
<div x-data="{ tab: '<?= $subtab; ?>' }">
    <!-- Tabs: mobile select -->
    <div class="grid grid-cols-1 sm:hidden">
        <select aria-label="Select a tab" class="select col-start-1 row-start-1 w-full appearance-none pr-8" x-model="tab">
            <option value="prebuild">MailBeez Modules</option>
            <option value="custom">Custom</option>
        </select>
        <svg viewBox="0 0 16 16" fill="currentColor" data-slot="icon" aria-hidden="true"
             class="pointer-events-none col-start-1 row-start-1 mr-2 size-5 self-center justify-self-end fill-secondary">
            <path d="M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z"
                  clip-rule="evenodd" fill-rule="evenodd"/>
        </svg>
    </div>

    <!-- Tabs: desktop nav -->
    <div class="hidden sm:block">
        <div class="border-b border-divider">
            <div class="flex items-center justify-between">
                <nav aria-label="Tabs" class="-mb-px flex space-x-8">
                    <a href="#"
                       @click.prevent="tab = 'prebuild'"
                       :aria-current="tab === 'prebuild' ? 'page' : 'false'"
                       :class="tab === 'prebuild' ? 'flex border-b-2 px-1 py-4 text-sm font-medium whitespace-nowrap border-brand text-brand' : 'flex border-b-2 px-1 py-4 text-sm font-medium whitespace-nowrap border-transparent text-secondary hover:border-emphasis hover:text-primary'">
                        MailBeez Modules
                    </a>
<!--
                    <a href="#"
                       @click.prevent="tab = 'custom'"
                       :aria-current="tab === 'custom' ? 'page' : 'false'"
                       :class="tab === 'custom' ? 'flex border-b-2 px-1 py-4 text-sm font-medium whitespace-nowrap border-brand text-brand' : 'flex border-b-2 px-1 py-4 text-sm font-medium whitespace-nowrap border-transparent text-secondary hover:border-emphasis hover:text-primary'">
                        Custom
                    </a>
-->
                </nav>
                <div class="py-2 hidden">
                    <?= \Components\Button::render('+ Add Automation', [
                        'size' => 'sm',
                        'variant' => 'primary',
                        'attrs' => [
                            'command' => 'show-modal',
                            'commandfor' => 'config-modal',
                            'data-title' => 'Add Automation',
                            'data-size' => 'lg',
                            'hx-get' => \Components\Router::url('wizard_step_automation', ['partial' => 1]),
                            'hx-target' => '#config-modal-body',
                            'hx-swap' => 'innerHTML',
                        ],
                    ]);
                    ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Content Sections (lazy-loaded) -->
    <div x-show="tab === 'prebuild'"
         x-cloak
         id="prebuild-section"
         hx-trigger="none"
         hx-get="<?= $prebuildSectionUrl; ?>"
         hx-swap="innerHTML">
        <?= $renderPrebuild(); ?>
    </div>

    <div x-show="tab === 'custom'" x-cloak
         id="custom-section"
         hx-get="<?= $customSectionUrl; ?>"
         hx-trigger="intersect once"
         hx-swap="innerHTML">
    </div>
</div>
<?php
$content = ob_get_clean();

echo layout($pageKey, $content);
