<?php
// pages/components/newsletter_items_list.php
// Flows list for NewsletterItems using the new ItemList design with expandable rows
use Components\Models\NewsletterItem;
use Components\Models\NewsletterCampaign;
use Components\Resources\ItemList;
use Components\Support\Palette;
use Components\Support\Htmx;
use Components\Ui\CollectionIdentity;
use Components\Ui\EmptyState;
use Components\Newsletter\PageConfig;

mh_load_modules_language_files(MH_DIR_MODULE, 'mb_newsletter');

$pageConfig = PageConfig::fromRequest();
$oob = (int) (mh_get('oob', 0, 'int'));
$selectedGroup = mh_get('group', '', 'string');
$selectedListId = mh_get('list_id', 0, 'int');
$selectedScheduleType = mh_get('schedule_type', null, 'string');
// Smart collection helpers
$isSmart = false;
$smartType = '';
if ($selectedGroup && strpos($selectedGroup, 'smart-') === 0) {
    $isSmart = true;
    $smartType = substr($selectedGroup, strlen('smart-'));
} elseif ($selectedGroup === 'favorite') {
    $isSmart = true;
    $smartType = 'favorite';
}


// Campaign identity map (name + dot color) for smart collections.
// Used to render a compact Collection badge next to the flow title.
$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;
            }
            $id = (int)$cid;
            if ($id <= 0) {
                continue;
            }
            $campaignIdentityMap[$id] = [
                'label'     => (string)($opt['label'] ?? ('Campaign ' . $id)),
                'dot_class' => (string)($opt['dot_class'] ?? 'bg-gray-400'),
            ];
        }
    } catch (\Throwable $e) {
        $campaignIdentityMap = [];
    }
}

$buildCampaignBadgeHtml = function (int $campaignId) use ($campaignIdentityMap, $pageConfig): 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'            => $pageConfig->getBaseUrl('newsletter', ['group' => $slug]),
        'hx-get'          => $pageConfig->getBaseUrl('newsletter_items_list', ['partial' => 1, 'group' => $slug]),
        'hx-target'       => '#' . $pageConfig->getTargetId('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>';
};

$itemsListWrapperAttrs = [
    'id' => $pageConfig->getTargetId('items-list'),
    'class' => 'h-full',
    'hx-trigger' => $pageConfig->getEventName('newsletter_item:deleted') . ' from:body, ' . $pageConfig->getEventName('timeframe:updated') . ' from:body',
    'hx-get' => $pageConfig->getBaseUrl('newsletter_items_list', array_merge(['partial' => 1, 'group' => $selectedGroup], $selectedListId > 0 ? ['list_id' => $selectedListId] : [], $selectedScheduleType !== null ? ['schedule_type' => $selectedScheduleType] : [])),
    'hx-swap' => 'outerHTML',
    'data-no-global-loader' => '1',
];
if ($oob) {
    $itemsListWrapperAttrs['hx-swap-oob'] = 'outerHTML';
}
$itemListInnerAttrs = 'id="' . $pageConfig->getTargetId('items-list-inner') . '"';
$selectedCampaignId = null;
if ($selectedGroup && strpos($selectedGroup, 'campaign-') === 0) {
    $selectedCampaignId = (int)substr($selectedGroup, strlen('campaign-'));
}

// Determine whether the selected campaign is archived (so we don't show a CTA in archive)
$selectedCampaignIsArchived = false;
$selectedCampaignName = '';
if ($selectedCampaignId !== null) {
    try {
        $c = NewsletterCampaign::find($selectedCampaignId);
        if ($c !== null) {
            $selectedCampaignIsArchived = ((int)($c->newsletter_campaign_archived ?? 0) === 1);
            $selectedCampaignName = trim((string)($c->newsletter_campaign_name ?? ''));
        }
    } catch (\Throwable $e) {
        $selectedCampaignIsArchived = false;
        $selectedCampaignName = '';
    }
}

if ($selectedCampaignId !== null && $selectedCampaignName === '') {
    $selectedCampaignName = sprintf(
        (string)mh_lng('UI_NEWSLETTER_COLLECTION_CAMPAIGN_FALLBACK', 'Campaign %s'),
        (string)$selectedCampaignId
    );
}

// Build items from model using DB-level filters to avoid loading the entire dataset
$nlUiState      = \Components\ConfigStore::getNewsletterUiState($pageConfig->mode);
$smartTimeframe = isset($nlUiState['smart_timeframe']) && (int)$nlUiState['smart_timeframe'] > 0 ? (int)$nlUiState['smart_timeframe'] : 180;

$items = [];
if (function_exists('mh_db_query')) {
    $opts = [];
    if ($selectedListId > 0) { $opts['list_id'] = $selectedListId; }
    if ($selectedScheduleType !== null) {
        if ($selectedScheduleType === 'newsletter') {
            $opts['schedule_type'] = ['bulk_mail', 'scheduled_window'];
        } else {
            $opts['schedule_type'] = $selectedScheduleType;
        }
    } else {
        $opts['schedule_type'] = $pageConfig->allowed_types;
    }
    if ($selectedCampaignId !== null) { $opts['campaign_id'] = $selectedCampaignId; }
    // smart types: 'recent', 'active', 'scheduled', 'draft', 'paused', 'completed'
    if ($isSmart) {
        $opts['smart'] = $smartType;
        if (in_array($smartType, ['recent', 'draft', 'completed'], true)) {
            $opts['timeframe'] = $smartTimeframe;
        }
    }
    if ($isSmart && $smartType === 'recent') { $opts['limit'] = 50; }

    $rows = NewsletterItem::fetchRoots($opts);

    foreach ($rows as $it) {
        $id = (int)($it->newsletter_item_id ?? 0);
        if ($id <= 0) { continue; }

        $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 via model helper
        $typeLabel = '';
        try { $typeLabel = (string)$it->scheduleTypeLabel(); } catch (\Throwable $e) { $typeLabel = ''; }
        // Build schedule summary (human-readable); only show for relevant states set below
        $scheduleSummary = '';
        try { $scheduleSummary = (string)$it->buildScheduleSummary(); } catch (\Throwable $e) { $scheduleSummary = ''; }
        $sublineSuffixHtml = '';
        $stateKey = '';
        try { $stateKey = $it->scheduleStateKey(); } catch (\Throwable $e) { $stateKey = ''; }
        // Show schedule summary only when relevant: scheduled, active
        $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 HTML using the unified renderer on the model
        $statusBadge = null;
        try {
            $statusBadge = NewsletterItem::renderStatusBadgeHtml($it, [
                'wrapper_class' => 'shrink-0 self-center p-1.5 inline-flex',
            ]);
        } catch (\Throwable $e) { $statusBadge = null; }

        // Build icon + type badge from schedule_type mapping (centralized in the model)
        $iconCfg = [];
        try { $iconCfg = $it->scheduleTypeIconConfig(); } catch (\Throwable $e) { $iconCfg = []; }

        $titleAfterParts = [];
        $starHtml = '';
        try { $starHtml = (string)NewsletterItem::renderFavoriteStarHtml($it); } catch (\Throwable $e) { $starHtml = ''; }
        if ($starHtml !== '') {
            $titleAfterParts[] = $starHtml;
        }
        if ($isSmart) {
            $cid = (int)($it->newsletter_campaign_id ?? 0);
            $badgeHtml = $buildCampaignBadgeHtml($cid);
            if ($badgeHtml !== '') {
                if ($smartType === 'recent' && !empty($it->last_modified)) {
                    $badgeHtml .= '<span class="text-xs text-secondary/60 ml-1">' . mh_lng('UI_LAST_EDITED', 'last edited') . ' <span x-data="{ date: new Date(\'' . date('Y-m-d\TH:i:s', strtotime($it->last_modified)) . '\') }" x-timeago="date">...</span></span>';
                }
                $titleAfterParts[] = $badgeHtml;
            }
        }
        $titleAfterHtml = '';
        if (!empty($titleAfterParts)) {
            $titleAfterHtml = '<span class="inline-flex items-center gap-1.5">' . implode('', $titleAfterParts) . '</span>';
        }

        $items[] = [
            'id' => $id,
            'newsletter_campaign_id' => (int)($it->newsletter_campaign_id ?? 0),
            'name' => $name,
            'status' => $status,
            'flow_status' => $flowStatus,
            'type_label' => $typeLabel,
            '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,
            'title_after_html' => $titleAfterHtml,
            'toggle_disabled' => $toggleDisabled,
            'subline_suffix_html' => $sublineSuffixHtml,
            'is_new' =>  ($it->last_modified === null),
        ];
    }
}

// Expandable content will be lazy-loaded via ItemList's expand_lazy_url option

// Title per selection
$title = (string)mh_lng('MAILBEEZ_NEWSLETTER_ITEM_LIST_TITLE_ALL_FLOWS', 'All Flows');
if ($selectedCampaignId !== null) {
    $title = sprintf(
        (string)mh_lng('MAILBEEZ_NEWSLETTER_ITEM_LIST_TITLE_FLOWS_IN_COLLECTION', 'Flows in Collection: %s'),
        $selectedCampaignName
    );
} elseif ($isSmart) {
    $title = $pageConfig->getSmartFilterLabel($smartType);
}

$titleHtml = null;
if ($isSmart && in_array($smartType, ['recent', 'draft', 'completed'], true)) {
    $timeframeOptions = \Components\Models\NewsletterItem::smartTimeframeOptions();
    $timeframeLabel = $timeframeOptions[$smartTimeframe] ?? ($smartTimeframe . ' days');

    $dropdownItems = [];
    foreach ($timeframeOptions as $days => $label) {
        $isActive = ($smartTimeframe === $days);
        $dropdownItems[] = [
            'label' => $label,
            'icon'  => $isActive ? \Components\Base::SVG_MICRO_CHECK : '<span class="opacity-0">' . \Components\Base::SVG_MICRO_CHECK . '</span>',
            'attrs' => [
                'hx-post'               => \Components\Router::url('newsletter_smart_config_toggle', ['toggle' => 'set_timeframe', 'timeframe' => $days, 'page_mode' => $pageConfig->mode]),
                'hx-target'             => '#' . $pageConfig->getTargetId('campaigns-list'), // refresh sidebar
                'hx-swap'               => 'outerHTML',
                'data-no-global-loader' => '1',
            ],
        ];
    }

    $triggerHtml = '<span class="-ml-3! text-sm font-semibold text-secondary uppercase tracking-wider"> - ' . \Components\Base::h($timeframeLabel) . '</span>' .
                   '<span class="ml-1 text-sm">' . \Components\Base::SVG_CHEVRON_DOWN . '</span>';

    $headerTimeFrameHtml = \Components\Dropdown::render([

        'trigger_html' => $triggerHtml,
            'wrapper_class' => 'inline-block text-sm',
        'trigger_attrs' => [
            'class' => 'inline-flex items-center cursor-pointer hover:bg-muted/30 px-1 rounded group',
        ],
        'items' => $dropdownItems,
        'anchor' => 'bottom end',
    ]);

    $titleHtml = $headerTimeFrameHtml;
}


// Inline control pill for collapsed state (aligned with the list header)
$groupParam = $selectedGroup !== '' ? ['group' => $selectedGroup] : [];
if ($pageConfig->mode !== PageConfig::MODE_NEWSLETTER) {
    $groupParam['page_mode'] = $pageConfig->mode;
}
$headerLeft = function() use ($groupParam) {
    ob_start();
    ?>
    <div class="relative z-20 inline-flex items-center rounded-md [&_svg]:size-5 px-1.5"
         x-show="collapsed" x-cloak @keyup.escape.window="ddOpen=false">
        <!-- Toggle (expand Collections) -->
        <button type="button"
                @click="toggleCollapse()"
                class="inline-flex items-center justify-center p-1 hover:bg-white/70 focus:outline-none text-secondary/70 hover:text-secondary"
                :aria-pressed="collapsed.toString()"
                title="Show collections">
            <?= \Components\Base::SVG_PANEL_OPEN; ?>
        </button>
        <!-- Dropdown opener for quick access to Collections while collapsed -->
        <div class="relative [&_svg]:size-5 text-secondary/70 hover:text-secondary ">
            <button type="button" @click="ddOpen=!ddOpen"
                    class="inline-flex items-center justify-center p-1"
                    :aria-expanded="ddOpen.toString()" title="Collections menu">
                <?= \Components\Base::SVG_CHEVRON_DOWN; ?>
            </button>
            <!-- Note: The actual overlay content is now rendered once in pages/newsletter.php
                 and simply shown/hidden via Alpine (ddOpen). This avoids stale content and
                 repeated HTMX loads. -->
        </div>
    </div>
    <?php
    return ob_get_clean();
};

$opts = NewsletterItem::itemListOptions([
    'title' => $title,
    'title_html' => $titleHtml,
    'items' => $items,
    'outer_attrs' => $itemListInnerAttrs,
    // Move creation action to the PageHeader toolbar; suppress local header button
    'new_action' => null,
    'view_mode_toggle' => true,
    'perf_context' => $pageConfig->mode,
]);
$opts['header_left'] = $headerLeft();

// Newsletter empty state: use context-aware messages and CTA behavior.
if (empty($items)) {
    if ($isSmart) {
        $smartEmptyState = $pageConfig->getSmartEmptyState($smartType);
        $opts['empty_html'] = EmptyState::render([
            'icon' => \Components\Base::SVG_INFORMATION_CIRCLE,
            'icon_color' => 'bg-info/20 text-info',
            'title' => (string)($smartEmptyState['title'] ?? ''),
            'text' => (string)($smartEmptyState['text'] ?? ''),
            'action' => null,
        ]);
    } elseif (!$selectedCampaignIsArchived) {
        $newFlowUrl = $pageConfig->getBaseUrl('newsletter_audience_selection_modal', ['partial' => 1, 'step' => 'existing']);
        $newFlowAttrs = [
            'command' => 'show-modal',
            'commandfor' => 'config-modal',
            'data-title' => $pageConfig->creation_modal_title,
            'data-size' => '5xl',
            'data-dismissible' => 'false',
            'hx-get' => $newFlowUrl,
            'hx-target' => '#config-modal-body',
            'hx-swap' => 'innerHTML',
            'hx-push-url' => 'false',
            'data-no-global-loader' => 'true',
            'data-no-local-loader' => 'true',
        ];
        if ($selectedCampaignId !== null) {
            $newFlowAttrs['hx-vals'] = json_encode(['newsletter_campaign_id' => (int)$selectedCampaignId], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }

        $opts['empty_html'] = EmptyState::render([
            'icon' => $pageConfig->empty_state_icon,
            'icon_color' => 'bg-brand/70 text-white/90',
            'title' => $pageConfig->empty_state_title,
            'text' => $pageConfig->empty_state_text,
            'action' => [
                'label' => $pageConfig->new_button_label,
                'icon' => \Components\Base::SVG_PLUS,
                'iconPosition' => 'front',
                'size' => 'md',
                'variant' => 'primary',
                'attrs' => $newFlowAttrs,
            ],
        ]);
    }
}

$smartExplainerHtml = '';
if ($isSmart) {
    $smartTypeId = preg_replace('/[^a-z0-9_-]+/i', '-', strtolower((string)$smartType));
    if (!is_string($smartTypeId) || $smartTypeId === '') {
        $smartTypeId = 'smart';
    }

    $smartExplainerHtml = \Components\Notification::render($pageConfig->getSmartFilterExplainer($smartType), [
        'id' => $pageConfig->mode . '_smart_filter_explainer_' . $smartTypeId,
        'dismissible' => true,
        'margin' => false,
        'class' => 'relative',
        'expandedClass' => 'mb-4',
        'minimizedClass' => 'absolute -right-6 top-0 z-30 h-9 flex items-center',
    ]);
}

echo '<div ' . \Components\Base::attrs($itemsListWrapperAttrs) . '>';
if ($smartExplainerHtml !== '') {
    echo $smartExplainerHtml;
}
echo ItemList::render($opts);
echo '</div>';
