<?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;

if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

$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);
?>
<div id="<?php echo Base::h($containerId); ?>"
     @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="relative hover:-translate-y-0   shadow-xs hover:ring-2 ring-4 ring-inset ring-white transition-all  bg-elevated hover:bg-canvas rounded-xl overflow-hidden border-0 border-divider  dark:divide-gray-700 dark:bg-zinc-800 cursor-pointer select-none">


    <!-- 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-10'); ?>
    <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 space-x-4 leading-none <?php echo $isOn ? '' : 'grayscale opacity-50'; ?>">
            <!-- Module Icon -->
            <?php
            $iconColor = isset($m['color']) && is_string($m['color']) && $m['color'] !== '' ? $m['color'] : 'bg-indigo-500 text-white';
            $defaultSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"></path></svg>';
            $iconSvg = isset($m['svg_icon']) && is_string($m['svg_icon']) && $m['svg_icon'] !== '' ? $m['svg_icon'] : $defaultSvg;
            ?>
            <div class="flex items-center justify-center shrink-0 rounded-lg size-10 p-2 shadow-sm  <?php echo Base::h($iconColor); ?>"><?php echo $iconSvg; ?></div>
            <div class="flex flex-col justify-between min-w-0 ">
                <div class="text-sm text-primary font-medium"><?php echo Base::h($m['title'] ?? ''); ?></div>
                <div class="text-xs text-nowrap text-ellipsis text-secondary/70 line-clamp-2"><?php echo Base::h($m['desc'] ?? '', ['allow_br'=>false]); ?></div>
            </div>
            <!-- 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-3" id="controls-<?php echo Base::h($modKey); ?>">
            <!-- Status badge (left of toggle): green = active, orange = inactive -->
            <div class="shrink-0" @click.stop role="status" title="<?php echo $isOn ? 'Active' : 'Inactive'; ?>" aria-label="<?php echo $isOn ? 'Active' : 'Inactive'; ?>">
                <div class="block transform rounded-full px-1.5 text-xs ring-1 <?php echo $isOn ? 'bg-green-600 text-white ring-white dark:ring-gray-900' : 'bg-transparent ring-orange-500 text-orange-600'; ?>">
                    <?php echo $isOn ? 'Active' : 'Inactive'; ?>
                </div>
            </div>

            <div id="<?php echo Base::h($statusWrapperId); ?>" >
                <?php
                echo Toggle::render('status', '', $isOn ? 'on' : 'off', [
                        'size' => 'sm',
                    // Important: target the entire card container for a full refresh after toggle
                        'input_attrs' => 'hx-post="' . Base::h($statusUrl) . '" hx-trigger="change" hx-target="#' . Base::h($containerId) . '" hx-indicator="#' . Base::h($loaderId) . '" data-no-global-loader="1"  data-no-local-loader="0" 
                        hx-swap="outerHTML" @click.stop data-no-modal="true" ',
                    // Use green-ish accent when active to emphasize enabled status
                        'active_color' => 'green',
                ]);
                ?>
            </div>
            <div>
                <?php
                echo Button::render('', [
                        'size' => 'sm',
                        'variant' => 'ghost',
                        'icon' => \Components\Base::SVG_GEAR,
                        'class' => 'text-secondary! ',
                        'attrs' => [
                                '@click.stop' => '',
                                'command' => 'show-modal',
                                'commandfor' => 'config-drawer',
                                'hx-get' => Router::url('module_config', ['module' => $modKey, 'partial' => 1, 'drawer' => 1, 'return' => 'module_card']),
                                'hx-target' => '#config-drawer-body',
                                'hx-swap' => 'innerHTML',
                        ]
                ]);
                ?>
            </div>
            <div class="flex items-center text-secondary! w-6">
                <span x-cloak x-show="openMap['<?php echo Base::h($modKey); ?>']">
                    <?= \Components\Base::SVG_CHEVRON_UP; ?>
                </span>
                <span  x-show="!openMap['<?php echo Base::h($modKey); ?>']">
                    <?= \Components\Base::SVG_CHEVRON_DOWN; ?>
                </span>
            </div>
        </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
         x-data="{
            canScrollX: false,
            atStart: true,
            atEnd: false,
            update() {
                const el = this.$refs.scroller || this.$el;
                // compute scroll state
                const max = Math.max(0, el.scrollWidth - el.clientWidth);
                this.canScrollX = el.scrollWidth > (el.clientWidth + 2);
                this.atStart = el.scrollLeft <= 1;
                this.atEnd = el.scrollLeft >= (max - 1);
            },
            scrollBy(dx) {
                const el = this.$refs.scroller || this.$el;
                el.scrollBy({ left: dx, behavior: 'smooth' });
            }
         }"
         x-init="update(); $nextTick(() => update()); setTimeout(() => update(), 60)"
         @resize.window.debounce.120="update()"
         class="relative overflow-hidden bg-divider/0 border-t border-divider/50 dark:border-muted/10 <?php echo $isOn ? '' : '--grayscale-100'; ?>">
        <!-- Fixed background pattern inside expandable area -->
        <svg class="absolute inset-0 rounded-xl 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>
        <!-- Horizontal scroll hint overlays (fixed within the card area) -->
        <div x-cloak x-show="canScrollX && !atStart" x-transition.opacity
             class="pointer-events-none absolute inset-y-0 left-0 flex items-center z-20">
            <button type="button" @click.stop="scrollBy(-280)"
                    class="pointer-events-auto inline-flex items-center justify-center w-6 h-full bg-secondary/20 text-white shadow-sm ring-1 ring-white/20 hover:bg-secondary/30 focus:outline-none">
                <!-- left chevron -->
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-4">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 19.5 8.25 12l7.5-7.5" />
                </svg>

            </button>
        </div>
        <div x-cloak x-show="canScrollX && !atEnd" x-transition.opacity
             class="pointer-events-none absolute inset-y-0 right-0 flex items-center z-20">
            <button type="button" @click.stop="scrollBy(280)"
                    class="pointer-events-auto inline-flex items-center justify-center w-6 h-full bg-secondary/20 text-white shadow-sm ring-1 ring-white/20 hover:bg-secondary/30 focus:outline-none ">
                <!-- right chevron -->
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-4">
                    <path stroke-linecap="round" stroke-linejoin="round" d="m8.25 4.5 7.5 7.5-7.5 7.5" />
                </svg>

            </button>
        </div>
        <!-- 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;
                }
                ?>
            </div>
        </div>
    </div>
</div>
