<?php
// pages/components/newsletter_item_flow.php
// Renders the flow visualization for a single NewsletterItem, intended for lazy loading via htmx

use Components\Models\NewsletterItem;
use Components\CampaignFlow\FlowViz;

$id = (int) mh_get('id', 0, 'int');
// Safety: always buffer inline HTML

//    sleep(2);

ob_start();

try {
    $item = $id > 0 ? NewsletterItem::find($id) : null;
    if (!$item) {
        ?>
        <div class="p-4 text-sm text-secondary">Item not found.</div>
        <?php
        echo ob_get_clean();
        return;
    }

    if (mh_get('view_mode') === 'performance') {
        echo \Components\Ui\PerformanceDashboard::render('', $id, [
            'context' => $item->getPageMode(),
            'title' => true
        ]);
        echo ob_get_clean();
        return;
    }

    // Render flow via model (handles caching)
    $t = microtime(true);
    echo $item->renderFlow(true, false);
    echo sprintf('<div class="text-xs text-secondary/30 absolute bottom-2">%.2fms</div>', (microtime(true) - $t) * 1000);
} catch (\Throwable $e) {
    ?>
    <div class="p-4 text-xs text-secondary">Failed to render flow.</div>
    <?php
}

echo ob_get_clean();
