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

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

$pageKey = 'audience';

// 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); ?>' }">
  <?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'), [
        'right' => \Components\Button::render(\mh_lng('MAILBEEZ_NEW_LIST', 'New List'), [
            'variant' => 'secondary',
            'size' => 'sm',
            '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',
                // Stable base URL; pass current tab via hx-vals so it adapts to Customers/Prospects
                'hx-get' => $baseNewUrl,
                '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')],
    ];
    echo \Components\Ui\Tabs::mobile('activeTab', $audienceTabItems, ['ariaLabel' => (string) \mh_lng('UI_AUDIENCE_SELECT_TAB', 'Select audience tab')]);
  ?>

  <div class="hidden sm:block">
    <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>
</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' => [
          '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(4)'
      ],
  ]);
  ?>
  </div>

<script>
  // Concurrency-limited refresh of Audience list counts
  window.BeezUI = window.BeezUI || {};
  window.BeezUI.refreshAudienceCounts = function(limit){
    try {
      var max = parseInt(limit, 10) || 4;
      // Scan across both tabs' lists to refresh all count anchors
      var anchors = Array.prototype.slice.call(document.querySelectorAll('#audience-lists-customers a[data-audience-count="1"], #audience-lists-prospects a[data-audience-count="1"]'));
      if (!anchors.length) { return; }

      var inflight = 0, idx = 0;
      var runId = 'audrc-' + Date.now();

      function pump(){
        if (idx >= anchors.length && inflight === 0) {
          // Optional: signal finished
          try { document.body.dispatchEvent(new CustomEvent('audience_lists:counts:refreshed', { bubbles: true })); } catch(e) {}
          return;
        }
        while (inflight < max && idx < anchors.length) {
          var a = anchors[idx++];
          if (!a || !a.isConnected) { continue; }
          a.setAttribute('data-refresh-run', runId);
          inflight++;
          // Prefer using htmx.ajax if available to preserve hx-* behavior & events
          try {
            if (window.htmx && typeof window.htmx.ajax === 'function') {
              window.htmx.ajax('GET', a.getAttribute('hx-get'), { target: a, swap: a.getAttribute('hx-swap') || 'outerHTML', source: a });
            } else {
              a.click();
            }
          } catch (e) {
            try { a.click(); } catch (_) {}
          }
        }
      }

      function onAfter(ev){
        try {
          var src = ev && ev.detail ? ev.detail.elt : null;
          if (!src) return;
          if (src.getAttribute && src.getAttribute('data-refresh-run') === runId && src.matches('a[data-audience-count="1"]')) {
            inflight = Math.max(0, inflight - 1);
            try { src.removeAttribute('data-refresh-run'); } catch(_) {}
            pump();
          }
        } catch(e) {}
      }

      document.addEventListener('htmx:afterRequest', onAfter, { once: false });
      pump();
    } catch (e) { /* no-op */ }
  };
</script>

<?php
$content = ob_get_clean();

echo layout($pageKey, $content);
