<?php
// pages/audience.php
use Components\Base;

require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

$pageKey = 'audience';
$viewMode = \Components\ConfigStore::getViewMode($pageKey, 'journey');

// Determine initial tab (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';
}

ob_start();
?>
<div x-data="{ 
    activeTab: '<?php echo \Components\Base::h($kind); ?>',
    viewMode: '<?php echo \Components\Base::h($viewMode); ?>',
    init() {
        if (window.Alpine && Alpine.store('audience')) {
            this.viewMode = Alpine.store('audience').viewMode;
            this.$watch('$store.audience.viewMode', v => { this.viewMode = v; });
        }
    }
}">
  <script>
    // Initialize Alpine store for Audience page (used by global toggle and view synchronization)
    (function () {
        try {
            var viewModeSeed = <?= json_encode($viewMode); ?>;
            function ensureAudienceStore() {
                try {
                    if (!window.Alpine) return;
                    if (!Alpine.store('audience')) {
                        Alpine.store('audience', {
                            viewMode: viewModeSeed
                        });
                    }
                } catch (e) {}
            }
            if (window.Alpine && typeof Alpine.store === 'function') {
                ensureAudienceStore();
            } else {
                document.addEventListener('alpine:init', ensureAudienceStore, { once: true });
            }
        } catch (e) {}
    })();
  </script>
  <?php
    // Move "New List" action into the PageHeader right-side slot
    $baseNewUrl = \Components\Router::url('audience_list_modal', ['partial' => 1, 'mode' => 'new']);
    echo \Components\Ui\PageHeader::render((string) \mh_lng('MAILBEEZ_APP_LABEL_AUDIENCE', 'Audience'), [
        'subtitle' => \mh_lng('MAILBEEZ_APP_LABEL_AUDIENCE_SUBTITLE', 'Manage and segment your customer and prospect database.'),
        'center' => \Components\Ui\FlowHelpers::renderGlobalToggle($pageKey),
        'right' => \Components\Button::render(\mh_lng('MAILBEEZ_NEW_LIST', 'New List'), [
            'variant' => 'secondary',
            'size' => 'md',
            'icon' => Base::SVG_PLUS,
            'iconPosition' => 'front',

            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'config-modal',
                'data-title' => \mh_lng('MAILBEEZ_NEW_LIST', 'New List'),
                'data-size' => '3xl',
                'data-dismissible' => 'false',
                // Stable base URL; pass current tab via hx-vals so it adapts to Customers/Prospects
                'hx-get' => $baseNewUrl . '&page_mode=audience',
                'hx-target' => '#config-modal-body',
                'hx-swap' => 'innerHTML',
                ':hx-vals' => "JSON.stringify({ filter_type: String(activeTab) })",
            ],
        ]),
    ]);

    echo \Components\Notification::render(mh_lng('MAILBEEZ_AUDIENCE_EXPLAINER', 'Audiences are based on database queries and are updated in real-time.<br>They are always automatically refreshed before each mailing.'), [
            'id' => 'audience_explainer',
            'dismissible' => true,
    ]);
  ?>
  <?php
    // Unify with Trigger tabs UI using reusable component
    $audienceTabItems = [
        ['value' => 'customers', 'label' => \mh_lng('MAILBEEZ_AUDIENCE_GROUP_CUSTOMERS', 'Customers')],
        ['value' => 'prospects', 'label' => \mh_lng('MAILBEEZ_AUDIENCE_GROUP_PROSPECTS', 'Prospects')],
        ['value' => 'favorites', 'label' => \mh_lng('MAILBEEZ_AUDIENCE_GROUP_FAVORITES', 'Favorites'), 'icon' => Base::SVG_STAR],
    ];
    echo \Components\Ui\Tabs::mobile('activeTab', $audienceTabItems, ['ariaLabel' => (string) \mh_lng('UI_AUDIENCE_SELECT_TAB', 'Select audience tab')]);
  ?>

  <div class="hidden sm:block" x-cloak>
    <div class="border-b border-divider">
      <div class="flex items-center justify-between gap-3">
        <?= \Components\Ui\Tabs::desktopNavOnly('activeTab', $audienceTabItems); ?>
      </div>
    </div>
  </div>

  <div class="mt-4">
    <div id="audience-lists-customers-wrapper" x-cloak x-show="activeTab==='customers'">
      <?php
      try {
          $_GET['kind'] = 'customers';
          $_GET['container_id'] = 'audience-lists-customers';
          $_GET['list_id'] = 'audience-customers';
      } catch (\Throwable $e) { /* no-op */ }
      require BEEZUI_ROOT . '/pages/components/audience_lists.php';
      ?>
    </div>

    <div id="audience-lists-prospects-wrapper" x-cloak x-show="activeTab==='prospects'">
      <?php
      try {
          $_GET['kind'] = 'prospects';
          $_GET['container_id'] = 'audience-lists-prospects';
          $_GET['list_id'] = 'audience-prospects';
      } catch (\Throwable $e) { /* no-op */ }
      require BEEZUI_ROOT . '/pages/components/audience_lists.php';
      ?>
    </div>

    <div id="audience-lists-favorites-wrapper" x-cloak x-show="activeTab==='favorites'">
      <?php
      try {
          $_GET['kind'] = 'favorites';
          $_GET['container_id'] = 'audience-lists-favorites';
          $_GET['list_id'] = 'audience-favorites';
      } catch (\Throwable $e) { /* no-op */ }
      require BEEZUI_ROOT . '/pages/components/audience_lists.php';
      ?>
    </div>
  </div>
</div>

<div class="mt-6 flex justify-end">
  <?php
  // Add a button to refresh all cached result counts for all audiences
  echo \Components\Button::render(\mh_lng('UI_REFRESH', 'Refresh'), [
      'variant' => 'ghost',
      'size' => 'sm',
      'icon' => Base::SVG_ROTATE_CW,
      'attrs' => [
          'id' => 'audience-refresh-button',
          'data-no-global-loader' => 1,
          // Invalidate all caches on the server but do NOT broadcast the mass refresh event
          'hx-post' => \Components\Router::url('audience_refresh_counts', ['partial' => 1, 'emit' => 0]),
          // We only want to emit an event; no DOM swap needed
          'hx-swap' => 'none',
          'hx-target' => 'body',
          'global-loader' => '0',
          // After invalidation completes, kick off a concurrency-limited client-side refresh
          'hx-on::after-request' => 'window.BeezUI && window.BeezUI.refreshAudienceCounts && window.BeezUI.refreshAudienceCounts(1, { 
              buttonId: "audience-refresh-button",
              spinner: ' . json_encode(str_replace('class="', 'class="animate-spin ', Base::SVG_ROTATE_CW)) . ',
              textRefreshing: ' . json_encode(\mh_lng("UI_REFRESHING", "Aktualisiere...")) . ',
              textProgress: ' . json_encode(\mh_lng("UI_REFRESHING_PROGRESS", "Aktualisiere Liste %s von %s")) . '
          })'
      ],
  ]);
  ?>
  </div>


<?php
$content = ob_get_clean();

echo layout($pageKey, $content);
