<?php
// pages/newsletter.php
require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

use Components\Router as R;
use Components\ConfigStore;

$pageKey = 'newsletter';
$targetContainer = \Components\Data\DataRegistry::navigation()->getTargetId($pageKey);

// Load persisted newsletter UI state for the current user
$nlUiState = ConfigStore::getNewsletterUiState();

// Refactor: Load Collections and Flows via hx-get components, preserving selected group
$selectedGroup = mh_get('group', '', 'string'); // slug like 'campaign-<id>' or '' (all)
$selectedListId = mh_get('list_id', 0, 'int');
$selectedScheduleType = mh_get('schedule_type', '', 'string');

// Determine initial selected slug: URL param takes priority, then persisted state,
// then 'smart-active' to avoid loading all items by default.
$persistedSlug = isset($nlUiState['selected_slug']) ? (string)$nlUiState['selected_slug'] : '';
$initialSlug = $selectedGroup !== '' ? $selectedGroup : ($persistedSlug !== '' ? $persistedSlug : 'smart-active');
// Build groupParam from the effective slug (not just the URL param) so that newsletter_items_list
// also receives the correct group on a reload where no URL ?group= is present.
$effectiveGroup = ($initialSlug !== '' && $initialSlug !== 'all') ? $initialSlug : '';
$groupParam = $effectiveGroup !== '' ? ['group' => $effectiveGroup] : [];
if ($selectedListId > 0) { $groupParam['list_id'] = $selectedListId; }
if ($selectedScheduleType !== '') { $groupParam['schedule_type'] = $selectedScheduleType; }
$initialSlugEsc = \Components\Base::h($initialSlug, false);

// Base URL for the items list (no group param); used by the collections:refresh JS listener
// and the newsletter_item:created handler to reload the list for the newly created campaign group.
$itemsListBaseUrl = \Components\Base::h(R::url('newsletter_items_list', ['partial' => 1]), false);
$collectionsListBaseUrl = \Components\Base::h(R::url('newsletter_collection_list', ['partial' => 1]), false);

ob_start();
?>

<div class="" x-data="{
  selectedSlug: '<?= $initialSlugEsc; ?>',
  itemsListBaseUrl: '<?= $itemsListBaseUrl; ?>',
  collectionsListBaseUrl: '<?= $collectionsListBaseUrl; ?>',
  init() {
    document.body.addEventListener('newsletter_item:created', (ev) => {
      const id = ev.detail && ev.detail.id ? ev.detail.id : null;
      if (!id) return;
      const slug = 'campaign-' + id;
      // Set the selected slug so the sidebar highlights the correct collection
      this.selectedSlug = slug;
      // Reload the items list filtered to the newly created campaign group
      htmx.ajax('GET', this.itemsListBaseUrl + '&group=' + encodeURIComponent(slug), {
        target: '#newsletter-items-list',
        swap: 'outerHTML',
      });
      // Refresh the collections list to update item counts; the declarative hx-trigger on
      // #newsletter-campaigns-list also fires for this event, so this explicit call ensures
      // the refreshed list reflects the new selectedSlug highlight immediately.
      htmx.ajax('GET', this.collectionsListBaseUrl + '&group=' + encodeURIComponent(slug), {
        target: '#newsletter-campaigns-list',
        swap: 'outerHTML',
      });
    });
  }
}">
  <?php
  $pageKey = 'newsletter'; // keep $pageKey scoped for layout
  // Persisted sidebar settings (server-side defaults, overridden client-side on init)
  $persistedWidth     = isset($nlUiState['sidebar_width']) ? (int)$nlUiState['sidebar_width'] : 300;
  $persistedCollapsed = !empty($nlUiState['sidebar_collapsed']) ? 'true' : 'false';

  if ($persistedWidth < 280) { $persistedWidth = 300; }
  if ($persistedWidth > 448) { $persistedWidth = 448; }

  $refreshUrl = R::url('newsletter_collection_list', array_merge(['partial' => 1], $groupParam));
  $savedGroupParam = $groupParam; // newsletter_collection_list.php overwrites $groupParam via mh_get()
  ob_start();
  require BEEZUI_ROOT . '/pages/components/newsletter_collection_list.php';
  $collectionsInner = ob_get_clean();
  $groupParam = $savedGroupParam; // restore effective group so lines below use the persisted slug
  // Extract only the inner content (without the outer HTMX-trigger wrapper) for the overlay.
  // This prevents a duplicate #newsletter-campaigns-list element with live hx-trigger attributes
  // from being placed inside the overlay, which would cause double-refresh requests on events.
  // Find the #newsletter-campaigns-list-inner div by its opening tag position.
  // Everything from that tag to the end (minus the final outer </div>) is the overlay content.
  $_innerStart = strpos($collectionsInner, '<div id="newsletter-campaigns-list-inner">');
  $_outerClose = strrpos($collectionsInner, '</div>'); // last </div> closes #newsletter-campaigns-list
  if ($_innerStart !== false && $_outerClose !== false && $_outerClose > $_innerStart) {
      $collectionsOverlayInner = substr($collectionsInner, $_innerStart, $_outerClose - $_innerStart);
  } else {
      $collectionsOverlayInner = $collectionsInner; // fallback
  }
  unset($_innerStart, $_outerClose);

  // Extracted: New Collection button (moved out of the component for flat structure)
  $newCollectionBtn = \Components\Button::render(mh_lng('UI_NEW', 'New'), [
          'variant' => 'ghost',
          'size' => 'sm',
          'icon' => \Components\Base::SVG_PLUS,
          'iconPosition' => 'front',

          'attrs' => [
          'command' => 'show-modal',
          'commandfor' => 'config-modal',
          'data-title' => mh_lng('UI_COLLECTIONS_NEW_TITLE', 'New Collection'),
          'data-size' => 'xl',
          'hx-get' => \Components\Router::url('newsletter_collection_modal', ['partial' => 1, 'mode' => 'new']),
          'hx-target' => '#config-modal-body',
          'hx-swap' => 'innerHTML',
          'data-no-global-loader' => '1',
          'data-no-local-loader' => '1',
      ],
  ]);

  // Save URL for async persistence
  $saveStateUrl = R::url('newsletter_ui_state_save', ['partial' => 1]);

  // Page toolbar: New Flow button — rendered in outer Alpine scope (my-6) so it can read selectedSlug
  $newFlowBaseUrl = \Components\Router::url('newsletter_item_modal', ['partial' => 1, 'mode' => 'new']);
  $newFlowBtn = \Components\Button::render(mh_lng('UI_NEW_FLOW', 'New Flow'), [
      'icon' => \Components\Base::SVG_PLUS,
      'iconPosition' => 'front',
      'size' => 'sm',
      'variant' => 'secondary',
      'attrs' => [
          'command' => 'show-modal',
          'commandfor' => 'config-modal',
          'data-title' => mh_lng('MAILBEEZ_NEWSLETTER_ITEM_MODAL_NEW_TITLE', 'New Newsletter Item'),
          'data-size' => '5xl',
          'hx-get' => $newFlowBaseUrl,
          'hx-target' => '#config-modal-body',
          'hx-swap' => 'innerHTML',
          'data-no-global-loader' => 'true',
//          ':disabled' => "!selectedSlug.startsWith('campaign-')",
//          ':class' => "!selectedSlug.startsWith('campaign-') ? 'opacity-40 cursor-not-allowed pointer-events-none' : ''",
          ':hx-vals' => "(function(){ var m = selectedSlug.match(/^campaign-(\\d+)$/); return m ? JSON.stringify({ newsletter_campaign_id: parseInt(m[1]) }) : '{}' })()",
      ],
  ]);
  echo \Components\Ui\PageHeader::render('Newsletter', [
      'right' => '<div class="flex gap-2">' . $newFlowBtn . '</div>',
  ]);
  ?>

  <div id="newsletter-layout"
       class="relative flex items-stretch my-6"
       :class="collapsed ? 'gap-0' : 'gap-4'"
       x-data="{
         width: <?= $persistedWidth; ?>,
         collapsed: <?= $persistedCollapsed; ?>,
         min: 300,
         max: 448,
         dragging: false,
         startX: 0,
         startW: 0,
         saveUrl: '<?= \Components\Base::h($saveStateUrl, false); ?>',
         ddOpen: false,
         saveTimer: null,
         clamp(v){ return Math.max(this.min, Math.min(this.max, v)); },
         persistState(patch) {
           const body = new URLSearchParams({ state_patch: JSON.stringify(patch) });
           fetch(this.saveUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' }, body: body.toString() }).catch(()=>{});
         },
         setWidth(w){
           this.width = this.clamp(w);
           clearTimeout(this.saveTimer);
           this.saveTimer = setTimeout(() => { this.persistState({ sidebar_width: this.width }); }, 500);
         },
         toggleCollapse(){
           this.collapsed = !this.collapsed;
           this.ddOpen = false;
           this.persistState({ sidebar_collapsed: this.collapsed });
         },
         startDrag(e){ if (this.collapsed) return; this.dragging = true; this.startX = e.clientX; this.startW = this.$refs.sidebar.getBoundingClientRect().width;
           const onMove = (ev)=>{ if(!this.dragging) return; const dx = ev.clientX - this.startX; this.setWidth(this.startW + dx); };
           const onUp = ()=>{ this.dragging=false; window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); };
           window.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onUp);
         },
         init(){
           // Server already provided width/collapsed; watch selectedSlug changes to persist
           this.$watch('selectedSlug', (slug) => { this.persistState({ selected_slug: slug }); });
         }
       }">

      <!-- No floating control anymore; controls are now inline:
           - When expanded: button is rendered beside the Collections title (left)
           - When collapsed: control pill appears inside the items header (header_left slot) -->
      <!-- Sidebar wrapper with resizable/collapsible width -->
      <aside id="newsletter-sidebar" x-ref="sidebar" class="shrink-0 overflow-hidden transition-[width] duration-150 h-full"
             :style="collapsed ? 'width:0px' : `width:${width}px`">
         <div class="h-full flex flex-col">
             <div class="h-full flex flex-col rounded-2xl border border-divider bg-elevated overflow-hidden">
                 <div class="px-3 pt-3 pb-2 flex items-center justify-between shrink-0">
                     <div class="flex items-center gap-2 [&_svg]:size-5">
                         <!-- Toggle button inline with Collections title when expanded -->
                         <button type="button"
                                 x-show="!collapsed"
                                 @click="toggleCollapse()"
                                 class="inline-flex items-center justify-center p-1.5 hover:bg-white/70 focus:outline-none text-secondary/70 hover:text-secondary"
                                 :aria-pressed="(!collapsed).toString()"
                                 title="Hide collections">
                             <?= \Components\Base::SVG_PANEL_CLOSE; ?>
                         </button>
                         <h4 class="text-sm font-semibold text-primary"><?= \Components\Base::h(mh_lng('UI_COLLECTIONS', 'Collections')); ?></h4>
                     </div>
                     <?= $newCollectionBtn; ?>
                 </div>
                 <div class="px-2 pb-3 flex-1 overflow-y-auto">
                    <?= $collectionsInner; ?>
                 </div>
             </div>
         </div>
      </aside>

      <!-- Vertical resizer handle -->
      <div id="newsletter-resizer"
           class="relative flex w-px cursor-col-resize items-center justify-center select-none"
           x-show="!collapsed"
           @mousedown="startDrag"
           @dblclick.prevent="toggleCollapse()"
           title="Drag to resize; double-click to collapse/expand">
          <div class="z-10 flex h-22 w-1.25  shrink-0 rounded-lg bg-divider"></div>
      </div>
      <!-- Main content (flows) -->
      <div class="flex-1 min-w-0 overflow-y-auto">
          <div id="newsletter-items-panel" class="relative h-full">
              <?= \Components\Base::loaderOverlay('loading-newsletter-items', 'z-100 rounded-2xl'); ?>
              <script>
                (function(){
                  try {
                    if(window.MBLoader){
                      MBLoader.bindHtmxOverlay('newsletter-items-panel', 'loading-newsletter-items', 500, function(evt) {
                        var detail = evt.detail;
                        var path = (detail.pathInfo ? detail.pathInfo.requestPath : '') || (detail.requestConfig ? detail.requestConfig.path : '');
                        return (detail.target && detail.target.id === 'newsletter-items-list') || (path && path.indexOf('newsletter_items_list') !== -1);
                      });
                    }
                  } catch (e) { /* no-op */ }
                })();
              </script>
              <div id="newsletter-items-list"
                   class="h-full"
                   hx-get="<?= \Components\Router::url('newsletter_items_list', array_merge(['partial' => 1], $groupParam)); ?>"
                   hx-trigger="load, newsletter:timeframe:updated from:body"
                   hx-swap="outerHTML"
                   hx-on:htmx:afterSwap="htmx.trigger(document.body, 'newsletter:campaigns:refresh')"
              >
                  <div class="relative h-full">
                      <?= \Components\Base::loaderOverlay('loading-newsletter-items-initial', 'z-10 rounded-2xl', '', false); ?>
                  </div>
              </div>
          </div>
      </div>
      <!-- Collections overlay (for collapsed state) -->
      <?php
      // Pre-render dropdown-style collections menu and allow HTMX-based refresh on navigation
      // Ensure we don't duplicate IDs: we render only the inner list here.
      ?>
          <div id="newsletter-collections-overlay"
               x-show="ddOpen" x-transition x-cloak
               @click.outside="ddOpen=false"
               class="absolute left-0 top-14 w-80 max-h-[70vh] overflow-auto rounded-2xl border border-divider bg-elevated shadow-xl p-3 z-50">
              <div id="newsletter-collections-overlay-inner"
                   @click="if ($event.target.closest('[data-slug]')) { ddOpen=false }"
              >
                  <?= $collectionsOverlayInner; ?>
              </div>
            </div>
  </div>

</div>


<?php
$content = ob_get_clean();

echo layout($pageKey, $content);
