{{ $name := .Get "name" | default "popup" }}
{{ $next := .Get "next" }}

<div id="popup-{{ $name }}" class="popup-overlay" data-next-target="{{ $next }}">
  <div class="popup-content">
    <button type="button" class="popup-close-trigger" aria-label="Close">&times;</button>
    <div class="popup-body">
      {{ .Inner }}
    </div>
  </div>
</div>

<style>
  .popup-overlay {
    display: none;
    position: fixed;
    inset: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    justify-content: center;
    align-items: center;
    backdrop-filter: blur(8px);
  }
  
  .popup-overlay.active { display: flex; }
  
  .popup-content {
    background: var(--hx-color-dark);
    color: var(--hx-color-gray-100);
    padding: 2.5rem;
    border-radius: 12px;
    max-width: 90%;
    width: 450px;
    position: relative;
    border: 1px solid rgba(255, 255, 255, 0.1);
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5);
  }
  
  .popup-close-trigger {
    position: absolute;
    top: 0.5rem;
    right: 1rem;
    background: none;
    border: none;
    font-size: 2.5rem;
    line-height: 1;
    cursor: pointer;
    color: #999;
    transition: color 0.2s;
  }
  .popup-close-trigger:hover { color: white; }
</style>

<script>
  (function() {
    // Only run the initialization logic once
    if (window.modalScriptLoaded) return;
    window.modalScriptLoaded = true;

    document.addEventListener('DOMContentLoaded', function() {
      // 1. Show the first modal
      const initialModal = document.getElementById('popup-first');
      if (initialModal) {
        setTimeout(() => initialModal.classList.add('active'), 0);
      }

      // 2. Combined click listener for closing and chaining
      document.addEventListener('click', function(e) {
        // Check if we clicked the close button OR the dark overlay background
        const isCloseBtn = e.target.closest('.popup-close-trigger');
        const isOverlay = e.target.classList.contains('popup-overlay');

        if (isCloseBtn || isOverlay) {
          const currentModal = isCloseBtn ? isCloseBtn.closest('.popup-overlay') : e.target;
          const nextName = currentModal.getAttribute('data-next-target');
          
          // Close the current one
          currentModal.classList.remove('active');

          // Trigger the next one if a "next" name was provided
          if (nextName) {
            const nextModal = document.getElementById('popup-' + nextName);
            if (nextModal) {
              // Tiny delay to allow the first one to disappear
              setTimeout(() => {
                nextModal.classList.add('active');
              }, 0);
            } else {
              console.error("Modal sequence error: Could not find id 'popup-" + nextName + "'");
            }
          }
        }
      });
    });
  })();
</script>
