<?php
// pages/components/campaigns_layout_list.php
// Renders campaign modules as a full-width list (small cards/rows)
// Expects: $modulesByTouchpoint

use Components\Button;
use Components\CampaignFlow\FlowViz;
use Components\Form\Toggle;
use Components\ConfigStore;
use Components\Router;
use Components\Ui\ExpandControls;


if (!isset($modulesByTouchpoint) || !is_array($modulesByTouchpoint)) {
    $modulesByTouchpoint = [];
}

// Collect all module keys to initialize Alpine openMap
$__allKeys = [];
foreach ($modulesByTouchpoint as $__grp => $__mods) {
    if (!is_array($__mods)) continue;
    foreach ($__mods as $__m) {
        if (isset($__m['key'])) $__allKeys[] = (string)$__m['key'];
    }
}
$__openMap = ConfigStore::getUiOpenMap();
// Ensure all keys are present (default false) for Alpine
foreach ($__allKeys as $__k) {
    if (!isset($__openMap[$__k])) { $__openMap[$__k] = false; }
}
// Limit to keys present on this page to avoid mixed states from other pages
$__openMap = array_intersect_key($__openMap, array_flip($__allKeys));
// Compute initial global state to avoid wrong button visibility before Alpine initializes
$__allOpenInit = !empty($__openMap) && !in_array(false, $__openMap, true);
$__allClosedInit = !empty($__openMap) && !in_array(true, $__openMap, true);
?>
<div x-data='{
        openMap: <?php echo json_encode($__openMap, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>,
        toggle(id) { this.openMap[id] = !this.openMap[id]; },
        persistAllOpen() {
            // Single bulk save of all open states via HTMX
            const saver = (this.$refs && this.$refs.bulkSaver) ? this.$refs.bulkSaver : document.getElementById("bulk-open-saver");
            if (saver) {
                saver.dispatchEvent(new CustomEvent("save-open-bulk", { bubbles: true }));
            }
        },
        expandAll() {
            Object.keys(this.openMap).forEach(k => this.openMap[k] = true);
            this.$nextTick(() => this.persistAllOpen());
        },
        collapseAll() {
            Object.keys(this.openMap).forEach(k => this.openMap[k] = false);
            this.$nextTick(() => this.persistAllOpen());
        },
        allOpen() { return Object.values(this.openMap).every(v => v === true); },
        allClosed() { return Object.values(this.openMap).every(v => v === false); }
    }' x-ref="root">

    <!-- Global expand/collapse controls -->
    <?php
    echo ExpandControls::render([
        'all_open_init' => $__allOpenInit,
        'all_closed_init' => $__allClosedInit,
    ]);
    ?>

    <input type="hidden" id="bulk-open-json" name="open_map" :value="JSON.stringify(openMap)" />
    <div id="bulk-open-saver" x-ref="bulkSaver" class="hidden" data-no-global-loader="1"
         hx-post="<?= Router::url('save_ui_open_bulk', ['partial' => 1]); ?>"
         hx-trigger="save-open-bulk"
         hx-include="#bulk-open-json"
         hx-swap="none"></div>

    <?php foreach ($modulesByTouchpoint as $group => $modules): ?>
        <section class="mb-8 ">
            <h4 class="text-xs font-semibold text-secondary mb-3"><?php echo \Components\Base::h($group); ?></h4>
            <div class="space-y-4">
                <?php foreach ($modules as $m): ?>
                    <?php include __DIR__ . '/trigger_module.php'; ?>
                <?php endforeach; ?>
            </div>
        </section>
    <?php endforeach; ?>
</div>
