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

    // Ensure we have the followups tree ready (flow may rely on it)
    if (!isset($item->followups)) {
        try { $item->loadFollowupsTree(true); } catch (\Throwable $e) { /* ignore */ }
    }

    // Build flow items via model method
    $flowItems = [];
    try { $flowItems = is_array($item->flow()) ? $item->flow() : []; } catch (\Throwable $e) { $flowItems = []; }

    // Render flow
    if (empty($flowItems)) {
        ?>
        <div class="p-4 text-xs text-secondary">No flow available.</div>
        <?php
    } else {
        echo FlowViz::render($flowItems, [
            'orientation' => 'horizontal',
            'size' => 'sm',
            'editable' => false,
            'class' => 'py-2',
                'id' => 'flow-viz-' . $id,
        ]);
    }
} catch (\Throwable $e) {
    ?>
    <div class="p-4 text-xs text-secondary">Failed to render flow.</div>
    <?php
}

echo ob_get_clean();
