<?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', 'favorites'], 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
    // Favorites tab also refreshes when favorite status changes globally
    $trigs = [
        'audience_lists:created from:body',
        'audience_lists:deleted from:body',
    ];
    if ($kind === 'favorites') {
        $trigs[] = 'audience_lists:favorites:refresh from:body';
    }
    $outerAttrs .= ' hx-get="' . \Components\Base::h($listUrl) . '"'
                . ' hx-trigger="' . \Components\Base::h(implode(', ', $trigs)) . '"'
                . ' hx-swap="outerHTML" data-no-global-loader="1"';
} 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();
    } elseif ($kind === 'favorites') {
        // Favorites lists
        $lists = Audience::allByKind('favorite');
    } 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 = Audience::RESULT_COUNT_CACHE_TTL;
            $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
                'lazy' => true,           // Use the managed observer
                '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_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,
            'title_after_html' => $list->getApplicabilityBadgeHtml() . Audience::renderFavoriteStarHtml($list),
            '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 ?? ''),
            'newsletter_list_applicability' => (string) ($list->newsletter_list_applicability ?? 'both'),
            // 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([
    'config_action' => [
        'url' => \Components\Router::url('audience_list_modal', ['partial' => 1, 'mode' => 'edit', 'page_mode' => 'audience']) . '&id={id}&drawer=1',
    ],
    'title' => '', 
    'items' => $items,
    'outer_attrs' => $outerAttrs,
    'container_id' => $containerId,
    'view_mode_toggle' => true,
    // 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' => false, // disable default pills
    ],
    'filters' => [
        'newsletter_list_applicability' => [
            'type' => 'pills',
            'all_value' => 'both',
            'all_label' => \mh_lng('MAILBEEZ_UI_FILTER_ALL_LABEL', 'All'),
            'options' => [
                'newsletter' => \mh_lng('MAILBEEZ_AUDIENCE_APPLICABILITY_ONLY_NEWSLETTER', 'Only Newsletter'),
                'automation' => \mh_lng('MAILBEEZ_AUDIENCE_APPLICABILITY_ONLY_AUTOMATION', 'Only Automation'),
            ],
            'default' => 'both',
        ],
        'newsletter_list_source' => [
            'type' => 'rich_select',
            'label' => \mh_lng('MAILBEEZ_AUDIENCE_FILTER_SOURCE', 'Source'),
            'all_label' => \mh_lng('MAILBEEZ_AUDIENCE_FILTER_SOURCE_ALL', 'All Sources'),
            'options' => 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',
        'data-dismissible' => 'false',
        'hx-get' => $baseNewUrl . '&page_mode=audience',
        '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');
    $isFavorites = ($kind === 'favorites');
    $opts['empty_html'] = \Components\Ui\EmptyState::render([
        'icon' => $isFavorites ? \Components\Base::SVG_STAR : ($isProspects ? \Components\Base::SVG_USER_GROUP : \Components\Base::SVG_USERS),
        'icon_color' => 'bg-brand/70 text-white/90',
        'title' => $isFavorites
            ? \mh_lng('UI_AUDIENCE_EMPTY_FAVORITES_TITLE', 'No favorite lists yet')
            : ($isProspects
                ? \mh_lng('UI_AUDIENCE_EMPTY_PROSPECTS_TITLE', 'No prospect lists yet')
                : \mh_lng('UI_AUDIENCE_EMPTY_CUSTOMERS_TITLE', 'No customer lists yet')),
        'text' => $isFavorites
            ? \mh_lng('UI_AUDIENCE_EMPTY_FAVORITES_TEXT', 'Star your most used audience lists to find them quickly here.')
            : ($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' => $isFavorites ? null : [
            '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;
