<?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;
use Components\Ui\Tabs;
use Components\Data\Live\LiveBeezUIConfigStoreProvider;
$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 grouping mode and persist per-user similar to MAILBEEZ_CONFIG_BEEZ_UI_LIST_LAYOUT
// Only affects list layout visually, but we keep/persist it consistently via URL+storage
$provider = new LiveBeezUIConfigStoreProvider();
$groupedListId = 'trigger_list_grouped';
$getParams = \Components\Common\Request::all('get');
if (isset($getParams['grouped'])) {
    $grouped = mh_get('grouped', 1, 'int') ? 1 : 0;
    $provider->setListGrouped($groupedListId, (bool)$grouped);
} else {
    $grouped = $provider->getListGrouped($groupedListId, true) ? 1 : 0;
}

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

// Show/Hide inactive items toggle (1 = show inactive, 0 = hide inactive)
// Server-side flag kept for initial render and non-JS fallback. Client-side toggling is done via Alpine store.
$showInactive = mh_get('show_inactive', 1, 'int') ? 1 : 0;

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

// SECTION partial rendering helpers
$renderPrebuild = function () use ($modulesByTouchpoint, $hasFilter, $selectedGroup, $layout, $targetContainer, $subtabParam, $baseArgs, $grouped, $showInactive) {

    $installAutomationAttrs = [
        'command' => 'show-modal',
        'commandfor' => 'config-modal',
        'data-title' => \mh_lng('UI_ADD_AUTOMATION', 'Add Automation'),
        'data-size' => '5xl',
        'hx-get' => \Components\Router::url('trigger_install_dialog', ['partial' => 1, 'layout' => $layout, 'group' => $selectedGroup]),
        'hx-target' => '#config-modal-body',
        'hx-swap' => 'innerHTML',
        'data-no-global-loader' => 'true',
    ];

    $installedModuleCount = 0;
    foreach ($modulesByTouchpoint as $__mods) {
        if (!is_array($__mods)) {
            continue;
        }
        $installedModuleCount += count($__mods);
    }

    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(\mh_lng('UI_SORT_ORDER', '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',
                        ],
                    ],
                    [
                        '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',
                        ],
                    ],
                    [
                        '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',
                        ],
                    ],
                ];
                // echo \Components\ButtonGroup::render($items, [
                //         'size' => 'sm',
                //         'class' => 'border border-divider bg-surface shadow-sm overflow-hidden',
                //         'ariaLabel' => 'Layout mode selector',
                // ]);
                ?>
            </div>
        </div>
-->

        <?php

        if ($installedModuleCount === 0) {
            ?>
            <?= \Components\Ui\EmptyState::render([
                'icon' => \Components\Base::SVG_TRIGGER,
                'icon_color' => 'bg-brand/70 text-white/90',
                'title' => \mh_lng('UI_TRIGGER_EMPTY_TITLE', 'No automations active yet'),
                'text' => \mh_lng('UI_TRIGGER_EMPTY_TEXT', 'Install an automation module to trigger emails automatically, for example after signup, order placement, or cart abandonment.'),
//                'grid_buttons' => [
//                    \mh_lng('UI_TRIGGER_EMPTY_EXAMPLE_SIGNUP', 'After signup'),
//                    \mh_lng('UI_TRIGGER_EMPTY_EXAMPLE_ORDER', 'After order'),
//                    \mh_lng('UI_TRIGGER_EMPTY_EXAMPLE_CART', 'Cart abandonment'),
//                ],
                'action' => [
                    'label' => \mh_lng('UI_TRIGGER_EMPTY_ACTION', 'Choose automation module'),
                    'icon' => \Components\Base::SVG_PLUS,
                    'iconPosition' => 'front',
                    'size' => 'sm',
                    'variant' => 'primary',
                    'attrs' => $installAutomationAttrs,
                ],
            ]); ?>
            <?php
            return ob_get_clean();
        }

        // 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', 'grouped' => $grouped]
));
$customSectionUrl = \Components\Router::url('trigger', array_merge(
    $hasFilter ? ['group' => $selectedGroup] : [],
    ['partial' => 1, 'section' => 'custom', 'layout' => 'tiles', $subtabParam => 'custom']
));

// Prepare tab items once for Tabs component rendering
$tabItems = [
    ['value' => 'prebuild', 'label' => mh_lng('MAILBEEZ_MODULES', 'MailBeez Flows')],
    // To enable the Custom tab in the UI, uncomment the next line:
    // ['value' => 'custom', 'label' => mh_lng('MAILBEEZ_CUSTOM', 'Custom')],
];

ob_start();
?>
    <div>
        <?php
        echo \Components\Ui\PageHeader::render(mh_lng('MAILBEEZ_APP_LABEL_AUTOMATIONS', 'Automations'), [
            'right' => \Components\Button::render(\mh_lng('UI_ADD_AUTOMATION', 'Add Automation'), [
                'icon' => \Components\Base::SVG_PLUS,
                'iconPosition' => 'front',
                'size' => 'sm',
                'variant' => 'secondary',
                'attrs' => [
                    'command' => 'show-modal',
                    'commandfor' => 'config-modal',
                    'data-title' => 'Add Automation',
                    'data-size' => '5xl',
                    'hx-get' => \Components\Router::url('trigger_install_dialog', ['partial' => 1, 'layout' => $layout, 'group' => $selectedGroup]),
                    'hx-target' => '#config-modal-body',
                    'hx-swap' => 'innerHTML',
                    'data-no-global-loader' => 'true',
                ],
            ]),
        ]);
        ?>
    </div>
<div x-data="{ tab: '<?= $subtab; ?>' }">
    <script>
        // Initialize Alpine store for Trigger page filters (used by list layouts and toolbar pill)
        (function () {
            try {
                var seed = <?= $showInactive ? 'true' : 'false'; ?>;
                function ensureTriggerStore() {
                    try {
                        if (!window.Alpine) return;
                        if (!Alpine.store('trigger')) {
                            Alpine.store('trigger', { showInactive: seed });
                        }
                    } catch (e) {}
                }
                // If Alpine is already present, initialize immediately; otherwise wait for alpine:init
                if (window.Alpine && typeof Alpine.store === 'function') {
                    ensureTriggerStore();
                } else {
                    document.addEventListener('alpine:init', ensureTriggerStore, { once: true });
                }
            } catch (e) {}
        })();
    </script>
    <!-- Tabs: mobile select via reusable component -->
    <?= Tabs::mobile('tab', $tabItems, ['ariaLabel' => 'Select a tab']); ?>

    <!-- Tabs: desktop nav via reusable component (actions remain on the right) -->
    <div class="hidden sm:block">
        <div class="border-b border-divider">
            <div class="flex items-center justify-between">
                <?= Tabs::desktopNavOnly('tab', $tabItems); ?>
<?php

                // (Ungroup / Group by touchpoint actions live inside the list layout dropdown menu)
?>
                <?php
                // Alpine-driven Show/Hide Inactive pill (client-side only). No HTMX requests.
                $labelShowAll = mh_lng('UI_SHOWING_ALL', 'Showing all');
                $labelHidden  = mh_lng('UI_INACTIVE_HIDDEN', 'Inactive hidden');
                $titleShow    = mh_lng('UI_SHOW_INACTIVE', 'Show inactive');
                $titleHide    = mh_lng('UI_HIDE_INACTIVE', 'Hide inactive');
                ?>
                <button type="button"
                        class="inline-flex items-center font-semibold rounded-full focus:ring-4 text-sm px-2 py-1.5 gap-x-1.5 ring-1 transition-colors"
                        :class="$store.trigger && $store.trigger.showInactive ? 'ring-gray-200 bg-gray-50 text-secondary hover:bg-gray-100' : 'ring-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100'"
                        @click="$store.trigger && ($store.trigger.showInactive = !$store.trigger.showInactive)"
                        :title="$store.trigger && $store.trigger.showInactive ? $el.dataset.titleHide : $el.dataset.titleShow"
                        data-title-show="<?= \Components\Base::h($titleShow, false); ?>"
                        data-title-hide="<?= \Components\Base::h($titleHide, false); ?>"
                >
                    <span x-show="$store.trigger && $store.trigger.showInactive" class="[&_svg]:size-4" aria-hidden="true"><?php echo \Components\Base::SVG_EYE; ?></span>
                    <span x-show="!($store.trigger && $store.trigger.showInactive)" class="[&_svg]:size-4" aria-hidden="true"><?php echo \Components\Base::SVG_EYE_SLASH; ?></span>
                    <span x-show="$store.trigger && $store.trigger.showInactive"><?php echo \Components\Base::h($labelShowAll); ?></span>
                    <span x-show="!($store.trigger && $store.trigger.showInactive)"><?php echo \Components\Base::h($labelHidden); ?></span>
                </button>
            </div>
        </div>
    </div>

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

    <div x-show="typeof tab !== 'undefined' && 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);
