<?php
// pages/components/newsletter_item_row.php
// Returns a single NewsletterItem row fragment so #item-* can self-refresh (Pattern A)

use Components\Models\NewsletterItem;
use Components\Resources\ItemList;
use Components\Ui\CollectionIdentity;

$id = (int) mh_get('id', 0, 'int');
$selectedGroup = mh_get('group', '', 'string');
$pageMode = mh_get('page_mode', 'newsletter', 'string');

// Smart collection helpers (match newsletter_items_list.php)
$isSmart = false;
if ($selectedGroup && strpos($selectedGroup, 'smart-') === 0) {
    $isSmart = true;
} elseif ($selectedGroup === 'favorite') {
    $isSmart = true;
}

// Campaign identity map for smart collections (name + dot color)
$campaignIdentityMap = [];
if ($isSmart) {
    try {
        $raw = NewsletterItem::campaignOptions();
        foreach ($raw as $cid => $opt) {
            if (!(is_int($cid) || (is_string($cid) && ctype_digit($cid)))) {
                continue;
            }
            if (!is_array($opt)) {
                continue;
            }
            $cidInt = (int)$cid;
            if ($cidInt <= 0) {
                continue;
            }
            $campaignIdentityMap[$cidInt] = [
                'label'     => (string)($opt['label'] ?? ('Campaign ' . $cidInt)),
                'dot_class' => (string)($opt['dot_class'] ?? 'bg-gray-400'),
            ];
        }
    } catch (\Throwable $e) {
        $campaignIdentityMap = [];
    }
}

$buildCampaignBadgeHtml = function (int $campaignId) use ($campaignIdentityMap, $pageMode): string {
    if ($campaignId <= 0) {
        return '';
    }

    $slug = 'campaign-' . $campaignId;
    $info = $campaignIdentityMap[$campaignId] ?? null;

    $label = $info ? (string)($info['label'] ?? ('Campaign ' . $campaignId)) : ('Campaign ' . $campaignId);
    $dot   = $info ? (string)($info['dot_class'] ?? 'bg-gray-400') : 'bg-gray-400';
    if ($dot === '') {
        $dot = 'bg-gray-400';
    }

    $identityHtml = CollectionIdentity::render(\Components\Base::h($label), $dot, [
        'base_class' => 'inline-flex items-center gap-1 min-w-0 truncate',
        'dot_size_class' => 'size-2',
        'class'      => 'max-w-48 px-1 pr-3 py-0 h-4 rounded-full border border-divider/60 bg-muted/20 text-xs text-secondary hover:bg-muted/30',
    ]);

    $attrs = \Components\Base::attrs([
        'href'            => \Components\Router::url('newsletter', ['group' => $slug, 'page_mode' => $pageMode]),
        'hx-get'          => \Components\Router::url('newsletter_items_list', ['partial' => 1, 'group' => $slug, 'page_mode' => $pageMode]),
        'hx-target'       => '#' . $pageMode . '-items-list',
        'hx-swap'         => 'outerHTML',
        'data-no-global-loader' => '1',
        'data-slug'       => $slug,
        '@click.stop'     => "typeof selectedSlug !== 'undefined' && (selectedSlug = '" . \Components\Base::h($slug, false) . "')",
        'onmousedown'     => 'event.stopPropagation();',
        'title'           => 'Open collection',
        'aria-label'      => 'Open collection',
        'class'           => 'inline-flex items-center',
    ]);

    return '<a ' . $attrs . '>' . $identityHtml . '</a>';
};
mh_load_modules_language_files(MH_DIR_MODULE, 'mb_newsletter');

ob_start();

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

    $name = (string)($it->newsletter_item_name ?? ('Item ' . $id));
    $status = (string)($it->status ?? '');
    $flowStatus = (string)($it->flow_status ?? '');
    // Derive compact, localized schedule type label for subline (parity with newsletter_items_list)
    $typeLabel = '';
    try { $typeLabel = (string)$it->scheduleTypeLabel(); } catch (\Throwable $e) { $typeLabel = ''; }
    // Build schedule summary (only shown for relevant states: scheduled, active)
    $scheduleSummary = '';
    try { $scheduleSummary = (string)$it->buildScheduleSummary(); } catch (\Throwable $e) { $scheduleSummary = ''; }
    $sublineSuffixHtml = '';
    $stateKey = '';
    try { $stateKey = $it->scheduleStateKey(); } catch (\Throwable $e) { $stateKey = ''; }
    $showSummary = in_array($stateKey, ['scheduled','active'], true);
    if ($showSummary && $scheduleSummary !== '') {
        $sublineSuffixHtml = \Components\Base::h($scheduleSummary);
    }
    $toggleDisabled = in_array($stateKey, ['draft','ended','completed'], true) || !$it->isInitial();
    // Build status badge config using unified helpers on the model (for OOB updates if needed)
    $statusBadge = null;
    try { $statusBadge = NewsletterItem::buildStatusBadgeConfig($it); } catch (\Throwable $e) { $statusBadge = null; }
    // Build icon + type badge from schedule_type mapping (centralized in the model)
    $iconCfg = [];
    $typeBadge = null;
    try { $iconCfg = $it->scheduleTypeIconConfig(); } catch (\Throwable $e) { $iconCfg = []; }
    try { $typeBadge = $it->scheduleTypeBadgeConfig(); } catch (\Throwable $e) { $typeBadge = null; }

    $items = [[
        'id' => $id,
        'newsletter_campaign_id' => (int)($it->newsletter_campaign_id ?? 0),
        'name' => $name,
        'status' => $status,
        'flow_status' => $flowStatus,
        'type_label' => $typeLabel,
        // Adopt icon + color based on schedule_type (fallback to default when unavailable)
        'icon' => !empty($iconCfg) ? $iconCfg : ($it->icon ?? [ 'svg' => \Components\Base::SVG_MAIL, 'color' => 'bg-indigo-500 text-white', 'variant' => 'solid', 'shape' => 'square' ]),
        '__model' => $it,
        'status_oob_id' => NewsletterItem::statusOobId($id),
        'status_badge' => $statusBadge,
        // Inline favorite (star) control rendered right after the title
        'title_after_html' => (function() use ($it, $isSmart, $buildCampaignBadgeHtml) {
            $parts = [];
            $starHtml = '';
            try { $starHtml = (string)NewsletterItem::renderFavoriteStarHtml($it); } catch (\Throwable $e) { $starHtml = ''; }
            if ($starHtml !== '') {
                $parts[] = $starHtml;
            }
            if ($isSmart) {
                $cid = (int)($it->newsletter_campaign_id ?? 0);
                $badgeHtml = $buildCampaignBadgeHtml($cid);
                if ($badgeHtml !== '') {
                    $parts[] = $badgeHtml;
                }
            }
            if (empty($parts)) {
                return '';
            }
            return '<span class="inline-flex items-center gap-1.5">' . implode('', $parts) . '</span>';
        })(),
        // Add a small type badge (soft palette) next to the status badge
//        'badges' => $typeBadge ? [ $typeBadge ] : [],
        'toggle_disabled' => $toggleDisabled,
        // Add schedule summary to the subline after the schedule type
        'subline_suffix_html' => $sublineSuffixHtml,
    ]];
    // Expand content will be lazy-loaded via ItemList's expand_lazy_url option

    // Render a list with a single item; hx-select on the caller ensures only #item-* is swapped
    echo ItemList::render(NewsletterItem::itemListOptions([
        'title' => '',
        'items' => $items,
    ]));
} catch (\Throwable $e) {
    echo '<div class="p-2 text-xs text-secondary">Failed to render item row.</div>';
}

echo ob_get_clean();
