<?php
// pages/components/audience_lists.php
// Lists all audience (newsletter) lists with actions opening the global modal
use Components\Router;
use Components\Models\Audience;
use Components\Resources\ResourceList;
use Components\Support\Format;
use Components\Data\Live\LiveBeezUIConfigStoreProvider;

$oob = (int) (mh_get('oob', 0, 'int'));
// Optional filter: kind = customers|prospects
try {
    $kind = (string) mh_get('kind', 'customers');
    $kind = in_array(strtolower($kind), ['customers', 'prospects'], true) ? strtolower($kind) : 'customers';
} catch (\Throwable $e) {
    $kind = 'customers';
}
// Optional custom container id and logical list id (for per-tab preferences)
try {
    $containerId = (string) mh_get('container_id', '');
} catch (\Throwable $e) { $containerId = ''; }
if ($containerId === '') { $containerId = 'audience-lists-' . $kind; }
try {
    $logicalListId = (string) mh_get('list_id', '');
} catch (\Throwable $e) { $logicalListId = ''; }
if ($logicalListId === '') { $logicalListId = 'audience-' . $kind; }

$outerAttrs = 'id="' . \Components\Base::h($containerId) . '"';
// Enable event-based refresh: when Audience CRUD emits HX-Trigger events,
// this container will re-fetch itself.
// Note: initial load is triggered by pages/audience.php; we only listen here for updates.
try {
    $listUrl = Router::url('audience_lists', ['partial' => 1, 'kind' => $kind, 'container_id' => $containerId, 'list_id' => $logicalListId]);
    // Only refresh the whole list on create/delete; rows handle self-refresh on update
    $trigs = [
        'audience_lists:created from:body',
        'audience_lists:deleted from:body',
    ];
    $outerAttrs .= ' hx-get="' . \Components\Base::h($listUrl) . '"'
                . ' hx-trigger="' . \Components\Base::h(implode(', ', $trigs)) . '"'
                . ' hx-swap="outerHTML"';
} catch (\Throwable $e) { /* ignore */ }
if ($oob) { $outerAttrs .= ' hx-swap-oob="outerHTML"'; }

// Audience: force ungrouped mode and hide grouped/ungrouped toggle
$grouped = 0;

// Build items using the Audience model (excludes smartlists per model logic)
$items = [];
try {
    if ($kind === 'prospects') {
        // Prospects lists
        $lists = Audience::typeProspects();
    } else {
        // Customers lists (default)
        $lists = Audience::typeCustomers();
    }
    foreach ($lists as $list) {
        $id = (int)($list->newsletter_list_id ?? 0);
        $name = $list->getLabel();
        $icon = is_callable([$list, 'icon']) ? $list->icon() : ['svg' => \Components\Base::SVG_OUTLINE_PLAY, 'color' => 'indigo', 'size' => 'sm'];
        // Source subtitle (e.g., "All Customers!") resolved from legacy sourcebeez title
        $typeLabel = '';
        try { $typeLabel = method_exists($list, 'getSourceTitle') ? (string)$list->getSourceTitle() : ''; } catch (\Throwable $e) { $typeLabel = ''; }
        // Build subline suffix showing the number of contacts (no badge/icon)
        $sublineSuffixHtml = '';
        // Build a static badge for the number of Newsletter Items that use this Audience
        $nlItemsBadge = null;
        try {
            // Read cached count from the same unified cache used by Audience::getResultCount()
            $ttlSeconds = 900; // 15 minutes
            $rc = (array) $list->getResultCountCache($ttlSeconds);
            $cachedVal = isset($rc['value']) ? $rc['value'] : null;
            $isValid = isset($rc['is_valid']) ? (bool)$rc['is_valid'] : false;

            // Determine label: show cached value (formatted) when present; otherwise an ellipsis
            $label = '…';
            if ($cachedVal !== null) {
                try {
                    $label = Format::humanNumber((int)$cachedVal, [
                        'decimals' => 1,
                        'trim_zeros' => true,
                    ]);
                } catch (\Throwable $e) {
                    $label = (string) (int) $cachedVal;
                }
            }
            // Lazy-load anchor to fetch/refresh the count; include the label as part of the
            // animated content so both number and label pulse/spin during refresh.
            $countHtml = Audience::countAnchorHtml($id, [
                'intersect' => !$isValid, // trigger lazy fetch on first view when stale
                'force' => !$isValid,      // ask backend to recompute and persist when stale
                'label' => $label,
                'suffix_label' => ' ' . (string) mh_lng('MAILBEEZ_CONTACTS', 'contacts'),
            ]);
            $sublineSuffixHtml = $countHtml;
        } catch (\Throwable $e) { $sublineSuffixHtml = ''; }
        // Newsletter items count badge
        try {
            $niCount = (int) $list->newsletterItemsCount();
            $niLabel = (string) $niCount;
            try {
                $niLabel = Format::humanNumber($niCount, [
                    'decimals' => 1,
                    'trim_zeros' => true,
                ]);
            } catch (\Throwable $e) { /* ignore, fallback to plain */ }

            // Build legacy route and use ItemList's clickable badge API (modal_url)
            $legacyUrl = mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/lists_usage.php&module=mb_newsletter&list_id=' . (int)$id );

            $nlItemsBadge = [
                'label' => $niLabel,
                'title' => 'Newsletter items',
                'color' => $niCount ? 'brand' : 'muted',
                'aria' => 'Newsletter items',
                'icon' => \Components\Base::SVG_CHAIN,
                'icon_class' => 'size-4',
                'icon_container_class' => ' -ml-0.5',
                // Important: override default drawer target to use the legacy modal instead
                'panel_id' => 'config-modal',
                'modal_url' => $legacyUrl,      // open in global modal (iframe)
                'modal_size' => '3xl',          // default size
            ];
        } catch (\Throwable $e) { $nlItemsBadge = null; }
        $items[] = [
            'id' => $id,
            'name' => $name,
            'status' => 'on',
            'icon' => $icon,
            'type_label' => $typeLabel,
            '__model' => $list,
            // Expose source for grouping (e.g., "all_customers", "smartlist_order_followup", ...)
            'newsletter_list_source' => (string) ($list->newsletter_list_source ?? ''),
            // Provide extra subline HTML with contacts count (no badge)
            'subline_suffix_html' => $sublineSuffixHtml,
            // Rendered by ItemList as badges area (right side). Keep newsletter items badge only.
            'badges' => array_values(array_filter([$nlItemsBadge])),
        ];
    }
} catch (\Throwable $e) { /* ignore */ }

ob_start();

// URLs and lazy-loading behavior are defined within Audience::itemListOptions

$opts = Audience::itemListOptions([
    'title' => '', // $kind === 'prospects' ? (string) \mh_lng('MAILBEEZ_AUDIENCE_GROUP_PROSPECTS', 'Prospects') : (string) \mh_lng('MAILBEEZ_AUDIENCE_GROUP_CUSTOMERS', 'Customers'),
    'items' => $items,
    'outer_attrs' => $outerAttrs,
    'container_id' => $containerId,
    // Per-tab state: use distinct identifiers for open-state map and layout persistence
    'open_key_prefix' => 'audience-list-' . $kind,
    'list_id' => $logicalListId,
    // Grouping controls mirroring Trigger list behavior
    'group' => [
        'by' => 'newsletter_list_source',
        'label' => 'source',
        'grouped' => false,
        'filters' => true,
        // Provide friendly labels for filter pills based on sourcebeez titles
        'labels_map' => Audience::listSourceLabels($kind),
    ],
    // row_actions can be added here if needed
]);

if (empty($items)) {
    $baseNewUrl = \Components\Router::url('audience_list_modal', ['partial' => 1, 'mode' => 'new']);
    $newAudienceAttrs = [
        'command' => 'show-modal',
        'commandfor' => 'config-modal',
        'data-title' => \mh_lng('MAILBEEZ_NEW_LIST', 'New List'),
        'data-size' => '3xl',
        'hx-get' => $baseNewUrl,
        'hx-target' => '#config-modal-body',
        'hx-swap' => 'innerHTML',
        'hx-vals' => json_encode(['filter_type' => (string)$kind], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        'data-no-global-loader' => 'true',
        'data-no-local-loader' => 'true',
    ];
    $isProspects = ($kind === 'prospects');
    $opts['empty_html'] = \Components\Ui\EmptyState::render([
        'icon' => $isProspects ? \Components\Base::SVG_USER_GROUP : \Components\Base::SVG_USERS,
        'icon_color' => 'bg-brand/70 text-white/90',
        'title' => $isProspects
            ? \mh_lng('UI_AUDIENCE_EMPTY_PROSPECTS_TITLE', 'No prospect lists yet')
            : \mh_lng('UI_AUDIENCE_EMPTY_CUSTOMERS_TITLE', 'No customer lists yet'),
        'text' => $isProspects
            ? \mh_lng('UI_AUDIENCE_EMPTY_PROSPECTS_TEXT', 'Create your first prospect audience to target newsletter signups and leads.')
            : \mh_lng('UI_AUDIENCE_EMPTY_CUSTOMERS_TEXT', 'Create your first customer audience to segment and target your buyers.'),
        'action' => [
            'label' => \mh_lng('MAILBEEZ_AUDIENCE_CREATE', 'Create Audience'),
            'icon' => \Components\Base::SVG_PLUS,
            'iconPosition' => 'front',
            'size' => 'sm',
            'variant' => 'primary',
            'attrs' => $newAudienceAttrs,
        ],
    ]);
}

echo \Components\Resources\ItemList::render($opts);

$__html = ob_get_clean();
echo $__html;
