<?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 = 'flow-automation-' . $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 = isset($__precomputedIsOn) ? (bool)$__precomputedIsOn : ConfigStore::isModuleOn($modKey);
$isConfigured = isset($__precomputedIsConfigured) ? (bool)$__precomputedIsConfigured : ConfigStore::isConfigured($modKey);

$isInstalled = (\Components\Common\Request::get('installed_module', '', 'key') === $modKey);
$openModule = (string)\mh_get('open_module', '', 'string');
$openId = (string)\mh_get('open_id', '', 'string');
$highlightStep = (string)\mh_get('highlight_step', '', 'string');

// Card is highlighted if it was just installed, or if it is specifically opened/highlighted
$isHighlighted = $isInstalled 
    || ($openModule !== '' && $openModule === $modKey)
    || ($openId !== '' && $openId === $modKey)
    || ($highlightStep !== '' && strpos($highlightStep, 'step-' . $modKey . '-') === 0)
    || !empty($m['is_highlighted'])
    || !empty($m['is_new']);

$expandPatternBg = $m['expand_pattern_bg'] ?? true;
$expandPatternBgType = $m['expand_pattern_type'] ?? 'dots';

if (mh_get('view_mode') === 'performance') {
    $perfOptions = [
        'title' => true
    ];
    if (($m['group'] ?? '') === 'review_feedback') {
        $perfOptions['context'] = \Components\Ui\PerformanceDashboard::CONTEXT_TRIGGER_TYPE_REVIEW;
    }
    echo \Components\Ui\PerformanceDashboard::render($modKey, 0, $perfOptions);
    return;
}
?>
<?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"
     <?php echo Card::highlightNewData($isHighlighted); ?>
     @click="toggle('<?php echo Base::h($modKey); ?>'); $nextTick(() => setTimeout(() => $dispatch('save-open'), 180))"
        <?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="{
         <?php echo Card::highlightNewXClassRules(); ?>
     }"
     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"><?php echo \mh_lng('UI_CLICK_TO_OPEN', 'Click to open'); ?></div>
            </div>
        </div>

        <div class=" shrink-0 self-center flex items-center gap-2" id="controls-<?php echo Base::h($modKey); ?>">
            <div id="view-mode-toggle-target-<?php echo Base::h($modKey); ?>"></div>
            <!-- 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);

            $isLicenseInvalid = isset($m['cert_check']) && $m['cert_check'] === false;
            if ($isLicenseInvalid) {
                echo Badge::render('error', mh_lng('UI_LICENSE_INVALID', 'License Invalid'), [
                    'variant' => 'solid',
                    'icon' => Base::SVG_EXCLAMATION_TRIANGLE,
                    'attrs' => ['@click.stop' => ''],
                ]);
            }
            ?>

            <?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'] = 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' => 'justify-center transform-gpu will-change-transform transition-transform duration-200 ease-out motion-reduce:transition-none',
                'icon' => \Components\Base::SVG_CHEVRON_DOWN,
                'attrs' => [
                    'aria-label' => 'Toggle module details',
                    ':class' => "openMap['" . Base::h($modKey) . "'] ? 'rotate-180 transform-gpu will-change-transform' : 'rotate-0 transform-gpu will-change-transform'",
                ],
            ]);
            ?>
        </div>
    </div>
    <?php include __DIR__ . '/trigger_module_flow.php'; ?>
</div>
