<?php
// pages/components/trigger_module.php
// Reusable renderer for a single trigger/campaign module card (list layout)
// Expects: $m (array with keys: key, title, desc, flow?)

use Components\Button;
use Components\CampaignFlow\FlowViz;
use Components\Form\Toggle;
use Components\Router;
use Components\Base;
use Components\ConfigStore;
use Components\Ui\FlowHelpers;
use Components\Ui\ModuleIdentity;
use Components\Ui\Badge;
use Components\Ui\Card;
use Components\Support\Palette;


$m = isset($m) && is_array($m) ? $m : [];
$modKey = (string)($m['key'] ?? '');
if ($modKey === '') {
    echo '<div class="text-sm text-red-600">Invalid module</div>';
    return;
}

$statusWrapperId = 'status-' . $modKey; // kept for backward compat
$containerId = 'trigger-' . $modKey;
$loaderId = 'loading-' . $containerId;
$statusUrl = Router::url('save_module_config', ['module' => $modKey, 'partial' => 1, 'return' => 'module_card', 'status_toggle' => '1']);
$openStateUrl = Router::url('save_module_config', ['module' => $modKey, 'partial' => 1, 'return' => 'open_state']);
$isOn = ConfigStore::isModuleOn($modKey);
$isConfigured = ConfigStore::isConfigured($modKey);

$isInstalled = (\Components\Common\Request::get('installed_module', '', 'key') === $modKey);

$expandPatternBg = $m['expand_pattern_bg'] ?? true;
$expandPatternBgType = $m['expand_pattern_type'] ?? 'dots';
?>
<?php $inactiveCfg = (!$isOn && $isConfigured) ? '1' : '0'; ?>
<div id="<?php echo Base::h($containerId); ?>"
     data-inactive="<?php echo Base::h($inactiveCfg); ?>"
     x-show="$store.trigger ? ($store.trigger.showInactive || $el.dataset.inactive !== '1') : true"
     x-data="{ highlighted: <?php echo $isInstalled ? 'true' : 'false'; ?> }"
     x-init="<?php echo $isInstalled ? 'setTimeout(() => $el.scrollIntoView({behavior: \'smooth\', block: \'center\'}), 800); setTimeout(() => highlighted = false, 5000);' : ''; ?>"
     @click="toggle('<?php echo Base::h($modKey); ?>'); $nextTick(() => $dispatch('save-open'))"
        <?php if (!empty($oobSwap)) {
            echo 'hx-swap-oob="' . Base::h($oobSwap) . '"';
        } ?>
     hx-post="<?php echo Base::h($openStateUrl); ?>"
     hx-trigger="save-open"
     hx-include="#ui-open-<?php echo Base::h($modKey); ?>"
     hx-swap="none"
     data-no-global-loader="1"
     data-no-local-loader="1"
     :class="highlighted ? 'ring-4 ring-brand border-brand' : 'ring-0 border-divider'"
     class="<?php echo Base::h(Card::baseContainerClass(true, 'dark:divide-gray-700')); ?>">


    <!-- Persist expand/collapse state via HTMX; hidden inputs included in request -->
    <input type="hidden" id="ui-open-<?php echo Base::h($modKey); ?>" name="ui_open"
           :value="openMap['<?php echo Base::h($modKey); ?>'] ? 'on' : ''"/>
    <?php echo Base::loaderOverlay($loaderId, 'z-100'); ?>
    <script>
        (function () {
            try {
                if (window.MBLoader) {
                    MBLoader.bindHtmxOverlay('<?php echo Base::h($containerId); ?>', '<?php echo Base::h($loaderId); ?>', 150);
                }
            } catch (e) { /* no-op */
            }
        })();
    </script>
    <div class="flex items-start justify-between p-3   ">
        <div class="group/clickhint truncate relative flex flex-grow items-center leading-none">
            <?= ModuleIdentity::render($m, [
                    'is_on' => $isOn,
                    'desc_class' => 'text-nowrap text-ellipsis'
            ]); ?>
            <!-- Hover overlay shown on card hover, but only over the left content area (not over controls) -->
            <div x-cloak x-show="!openMap['<?php echo Base::h($modKey); ?>']"
                 class="pointer-events-none absolute inset-0 flex items-center justify-end px-6 opacity-0 group-hover/clickhint:opacity-100 transition-opacity delay-500 duration-100">
                <div class="px-2 py-1 text-xs font-medium rounded-md bg-primary/30 text-white shadow-sm ring-1 ring-white/20">
                    Click to open
                </div>
            </div>
        </div>

        <div class=" shrink-0 self-center flex items-center gap-2" id="controls-<?php echo Base::h($modKey); ?>">
            <!-- Status badge: reuse the same flat pill style as NewsletterItem badges -->
            <?php
            // Map trigger states to newsletter-like state keys to reuse Palette::newsletterStateBadgeClass()
            // - Active        ? 'active' (green)
            // - Requires Conf ? 'draft' (orange)
            // - Inactive      ? 'paused' (yellow)
            $badgeLabel = $isOn
                    ? mh_lng('UI_ACTIVE', 'Active')
                    : (!$isConfigured ? mh_lng('UI_REQUIRES_CONFIGURATION', 'Requires Configuration') : mh_lng('UI_INACTIVE', 'Inactive'));
            $stateKey = $isOn ? 'active' : (!$isConfigured ? 'draft' : 'paused');
            $badgeClass = Palette::newsletterStateBadgeClass($stateKey);

            // Improve "Requires Configuration" badge by adding a right-pointing arrow icon on the right
            $options = [
                    'class' => $badgeClass,                     // default: flat soft pill classes
                    'wrapper_class' => 'shrink-0',
                    'attrs' => ['@click.stop' => ''],
            ];
            if (!$isOn && !$isConfigured) {
                // Render the "Requires Configuration" badge as a primary-looking solid pill
                // to emphasize the next action. Keep the arrow indicator on the right.
                $options['class'] = 'bg-brand-600 text-white ring-1 ring-brand-500'; // primary/brand solid style
                $options['content_html'] = '<span>' . Base::h($badgeLabel) . '</span>'
                        . '<span class="ml-1 -mr-0.5 [&_svg]:size-3 [&_svg]:align-middle">' . Base::SVG_ARROW_RIGHT . '</span>';
            }

            echo Badge::render('status', $badgeLabel, $options);
            ?>

            <?php // Status toggle moved into dropdown menu ?>
            <div>
                <?php
                // Replace single config button with Dropdown trigger (ellipsis) + menu item for current configuration action
                // Build the trigger using the shared Button component (icon-only)
                // When the module is not configured, emphasize the action by using a primary button style
                $triggerVariant = $isConfigured ? 'ghost' : 'primary';
                $triggerExtraCls = 'justify-center' . ($isConfigured ? ' text-secondary hover:bg-gray-100 dark:hover:bg-white/10' : '');
                $triggerBtnHtml = Button::render('', [
                        'variant' => $triggerVariant,
                        'size' => 'md',
//                        'rounded' => 'md',
                        'icon' => Base::SVG_ELLIPSIS_HORIZONTAL,
                        'class' => $triggerExtraCls,
                        'attrs' => [
                                '@click.stop' => '',
                                'aria-label' => 'Options',
                        ],
                ]);

                // Build dropdown items dynamically so we can inject add-on actions
                // 1) Base Configure action
                $menuItems = [[
                    'label' => mh_lng('UI_CONFIGURE', 'Configure'),
                    'icon'  => \Components\Base::SVG_GEAR,
                    'attrs' => [
                        '@click.stop' => '',
                        'command' => 'show-modal',
                        'commandfor' => 'config-drawer',
                        'hx-get' => Router::url('module_config', ['module' => $modKey, 'partial' => 1, 'drawer' => 1, 'return' => 'module_card', 'mode' => 'edit']),
                        'hx-target' => '#config-drawer-body',
                        'hx-swap' => 'innerHTML',
                    ],
                ]];

                // 2) Inject contextual add-on actions (moved from expanded area)
                try {
                    $addonActions = \Components\Data\DataRegistry::addonActions()->getActionsForModule($modKey);
                } catch (\Throwable $e) {
                    $addonActions = [];
                }
                if (!empty($addonActions)) {
                    $lastGroup = 'primary';
                    foreach ($addonActions as $act) {
                        $group = (string)($act['group'] ?? 'other');
                        if ($group !== $lastGroup) {
                            $menuItems[] = ['divider' => true];
                            $lastGroup = $group;
                        }
                        $menuItems[] = [
                            'label' => (string)($act['label'] ?? ''),
                            'icon'  => (string)($act['icon'] ?? ''),
                            // Ensure menu click does not bubble and reuse provided HTMX/modal attrs
                            'attrs' => array_merge(['@click.stop' => ''], (array)($act['attrs'] ?? [])),
                        ];
                    }
                }

                // 3) Divider before status toggle
                $menuItems[] = ['divider' => true];

                // 4) Status toggle (Pause/Activate)
                $menuItems[] = [
                    'label' => $isOn ? mh_lng('UI_PAUSE', 'Pause') : mh_lng('UI_ACTIVATE', 'Activate'),
                    'icon'  => $isOn ? \Components\Base::SVG_OUTLINE_PAUSE : \Components\Base::SVG_OUTLINE_PLAY,
                    'attrs' => (function() use ($isOn, $statusUrl, $containerId, $loaderId) {
                        $attrs = [
                            '@click.stop' => '',
                            'hx-post' => Base::h($statusUrl),
                            'hx-target' => '#' . Base::h($containerId),
                            'hx-indicator' => '#' . Base::h($loaderId),
                            'hx-swap' => 'outerHTML',
                            // Ensure expand/collapse state (ui_open) is NOT posted with status toggle
                            'hx-params' => 'not ui_open',
                            'data-no-global-loader' => '1',
                            'data-no-local-loader' => '0',
                        ];
                        if (!$isOn) {
                            $attrs['hx-vals'] = Base::h(json_encode(['status' => 'on']));
                        }
                        return $attrs;
                    })(),
                ];

                echo \Components\Dropdown::render([
                    'wrapper_attrs' => [
                        'x-data' => '{ menuOpen: false }',
                    ],
                    // Wrap the Button HTML inside a neutral container to avoid nested <button>
                    'trigger_tag' => 'div',
                    'trigger_html' => $triggerBtnHtml,
                    'trigger_attrs' => [
                        '@click.stop' => '',
                    ],
                    'anchor' => 'bottom start',
                    'items' => $menuItems,
                ]);
                ?>
            </div>
            <?php
            // Refactor: use Button (ghost) for the expand/collapse chevron indicator (keeps bubbling to card @click)
            echo Button::render('', [
                'variant' => 'ghost',
                'size' => 'md',
//                'rounded' => 'md',
//                'class' => 'w-6 h-6 justify-center text-secondary/50 hover:text-secondary',
                'icon' =>
                    '<span x-cloak x-show="openMap[\'' . Base::h($modKey) . '\']">' . \Components\Base::SVG_CHEVRON_UP . '</span>' .
                    '<span x-show="!openMap[\'' . Base::h($modKey) . '\']">' . \Components\Base::SVG_CHEVRON_DOWN . '</span>',
                'attrs' => [
                    'aria-label' => 'Toggle module details',
                ],
            ]);
            ?>
        </div>
    </div>
    <div id="flow-<?php echo Base::h($modKey); ?>"
         x-cloak
         x-show="openMap['<?php echo Base::h($modKey); ?>']"
         x-collapse.duration.100ms
         @click.stop
         hx-get="<?php echo Router::url('trigger_module', ['module' => $modKey, 'partial' => 1]); ?>"
         hx-trigger="<?php echo Base::h($modKey); ?>:expandable:refresh from:body"
         hx-target="#flow-<?php echo Base::h($modKey); ?>"
         hx-select="#flow-<?php echo Base::h($modKey); ?>"
         hx-swap="outerHTML"
         hx-disinherit="*"
         data-no-global-loader="1"
         x-data="<?= Base::h(FlowHelpers::alpineData(), false); ?>"
         x-init="update(); $nextTick(() => update()); setTimeout(() => update(), 60)"
         @resize.window.debounce.120="update()"
         @htmx:before-request="$event.detail.elt === $el ? refreshing = true : null"
         @htmx:after-request="$event.detail.elt === $el ? refreshing = false : null"
         class="<?= Card::flowClasses() ?> <?php echo $isOn ? '' : '--grayscale-100'; ?>">
        <div x-show="refreshing" x-cloak
             class="pointer-events-none absolute inset-0 z-50 flex items-center justify-center bg-white/50 dark:bg-gray-900/50 transition-opacity duration-100 ease-in-out">
            <div class="flex items-center gap-2 text-secondary">
                <?= \Components\Base::SVG_SPINNER; ?>
            </div>
        </div>
        <?php if ($expandPatternBg && $expandPatternBgType === 'lines'): ?>
            <!-- Fixed background pattern inside expandable area -->
            <svg class="absolute inset-0 rounded-2xl size-full stroke-divider/90 dark:stroke-muted/10 pointer-events-none z-0"
                 fill="none" aria-hidden="true">
                <defs>
                    <pattern id="pattern-<?php echo Base::h($modKey); ?>" x="0" y="0" width="8" height="8"
                             patternUnits="userSpaceOnUse">
                        <path d="M-1 5L5 -1M3 9L8.5 3.5" stroke-width="0.5"></path>
                    </pattern>
                </defs>
                <rect stroke="none" fill="url(#pattern-<?php echo Base::h($modKey); ?>)" width="100%"
                      height="100%"></rect>
            </svg>
        <?php endif; ?>
        <?= FlowHelpers::renderScrollHints(); ?>
        <?= FlowHelpers::renderRefreshButton($modKey, 0, $modKey); ?>

        <!-- Inner horizontal scroller: content scrolls beneath the fixed buttons; scrollbar stays here -->
        <div x-ref="scroller" @scroll.passive="update()" class="relative overflow-x-auto overflow-y-hidden">
            <div class="inline-block relative z-10 p-8">
                <?php
                /*
                if (!empty($m['flow']) && is_array($m['flow'])) {
                    $bodyHtml = FlowViz::render($m['flow'], [
                            'orientation' => 'horizontal',
                            'size' => 'sm',
                            'editable' => false,
                            'class' => ''
                    ]);
                    echo $bodyHtml;
                */

                try {
                    echo \mailbeez_pro::renderFlowStatic($m, true);
                } catch (\Throwable $e) {
                    echo '<div class="text-xs text-red-600">' . Base::h($e->getMessage()) . '</div>';
                }
                ?>
            </div>
        </div>
    </div>
</div>
