---
/**
 * AuthLoader Component
 * 
 * Provides a loading state for authentication-protected pages to prevent
 * flashing of content before auth verification completes.
 * 
 * Usage:
 * - Wraps the content of pages that require authentication
 * - Shows a loading spinner while auth is being verified server-side
 * - Prevents flash of unauthenticated content
 */

export interface Props {
  /** Custom loading message */
  message?: string;
  /** Show minimal loader without background */
  minimal?: boolean;
}

const { 
  message = "Verifying authentication...",
  minimal = false 
} = Astro.props;
---

<div class="auth-loader-wrapper" data-minimal={minimal}>
  {minimal ? (
    <!-- Minimal loader for components -->
    <div class="auth-loader-minimal">
      <div class="auth-loader-spinner-small"></div>
      <span class="auth-loader-text-small">{message}</span>
    </div>
  ) : (
    <!-- Full page loader -->
    <div class="auth-loader-fullscreen">
      <div class="auth-loader-content">
        <div class="auth-loader-card">
          <div class="auth-loader-spinner"></div>
          <h3 class="auth-loader-title">Authenticating</h3>
          <p class="auth-loader-message">{message}</p>
        </div>
      </div>
    </div>
  )}
  
  <!-- Content slot (hidden initially, shown after auth verification) -->
  <div class="auth-content" style="display: none;">
    <slot />
  </div>
</div>

<style>
  .auth-loader-wrapper {
    position: relative;
    min-height: 100vh;
  }
  
  .auth-loader-wrapper[data-minimal="true"] {
    min-height: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 2rem;
  }
  
  /* Full screen loader */
  .auth-loader-fullscreen {
    position: fixed;
    inset: 0;
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--bg-gradient, linear-gradient(135deg, #0f172a 0%, #1e293b 100%));
    backdrop-filter: blur(10px);
  }
  
  .auth-loader-content {
    text-align: center;
    max-width: 400px;
    padding: 2rem;
  }
  
  .auth-loader-card {
    background: rgba(30, 41, 59, 0.8);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 1.5rem;
    padding: 3rem 2rem;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
  }
  
  /* Minimal loader */
  .auth-loader-minimal {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 1rem;
    background: rgba(30, 41, 59, 0.6);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 0.75rem;
  }
  
  /* Spinners */
  .auth-loader-spinner {
    width: 3rem;
    height: 3rem;
    margin: 0 auto 1.5rem;
    border: 3px solid rgba(96, 165, 250, 0.2);
    border-top: 3px solid rgb(96, 165, 250);
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .auth-loader-spinner-small {
    width: 1.5rem;
    height: 1.5rem;
    border: 2px solid rgba(96, 165, 250, 0.2);
    border-top: 2px solid rgb(96, 165, 250);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    flex-shrink: 0;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  /* Typography */
  .auth-loader-title {
    color: var(--glass-text-primary, #ffffff);
    font-size: 1.5rem;
    font-weight: 600;
    margin: 0 0 0.5rem;
    letter-spacing: -0.025em;
  }
  
  .auth-loader-message {
    color: var(--glass-text-secondary, rgba(255, 255, 255, 0.8));
    font-size: 1rem;
    margin: 0;
    font-weight: 400;
  }
  
  .auth-loader-text-small {
    color: var(--glass-text-secondary, rgba(255, 255, 255, 0.8));
    font-size: 0.875rem;
    font-weight: 500;
  }
  
  /* Responsive design */
  @media (max-width: 640px) {
    .auth-loader-card {
      margin: 1rem;
      padding: 2rem 1.5rem;
    }
    
    .auth-loader-title {
      font-size: 1.25rem;
    }
    
    .auth-loader-message {
      font-size: 0.875rem;
    }
  }
  
  /* Theme overrides for light mode */
  [data-theme="light"] .auth-loader-fullscreen {
    background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  }
  
  [data-theme="light"] .auth-loader-card {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid rgba(0, 0, 0, 0.1);
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.15);
  }
  
  [data-theme="light"] .auth-loader-minimal {
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid rgba(0, 0, 0, 0.1);
  }
  
  [data-theme="light"] .auth-loader-title {
    color: #1e293b;
  }
  
  [data-theme="light"] .auth-loader-message,
  [data-theme="light"] .auth-loader-text-small {
    color: #64748b;
  }
</style>

<script>
  /**
   * AuthLoader behavior
   * 
   * On pages where server-side auth has already been verified,
   * immediately show the content and hide the loader.
   * 
   * This script runs after the component mounts to ensure
   * a smooth transition from loading to content.
   */
  
  class AuthLoader {
    private wrapper: HTMLElement | null = null;
    private loader: HTMLElement | null = null;
    private content: HTMLElement | null = null;
    
    constructor() {
      this.init();
    }
    
    private init() {
      console.log('[AuthLoader] Initializing...');
      
      this.wrapper = document.querySelector('.auth-loader-wrapper');
      this.loader = document.querySelector('.auth-loader-fullscreen, .auth-loader-minimal');
      this.content = document.querySelector('.auth-content');
      
      console.log('[AuthLoader] Found elements:', {
        wrapper: !!this.wrapper,
        loader: !!this.loader,
        content: !!this.content
      });
      
      if (!this.content) {
        console.error('[AuthLoader] Content element not found - cannot proceed');
        return;
      }
      
      if (!this.wrapper) {
        console.warn('[AuthLoader] Wrapper element not found, but proceeding anyway');
      }
      
      if (!this.loader) {
        console.warn('[AuthLoader] Loader element not found, but proceeding anyway');
      }
      
      // For pages where auth was verified server-side, show content immediately
      this.showContentInternal();
    }
    
    private showContentInternal() {
      if (this.content) {
        console.log('[AuthLoader] Showing content, hiding loader');
        
        // Show content
        this.content.style.display = 'block';
        
        // Hide loader with smooth transition (if it exists)
        if (this.loader) {
          this.loader.style.opacity = '0';
          this.loader.style.transition = 'opacity 0.3s ease-out';
          
          setTimeout(() => {
            if (this.loader) {
              this.loader.style.display = 'none';
            }
          }, 300);
        } else {
          console.warn('[AuthLoader] Loader element not found, but showing content anyway');
        }
      } else {
        console.error('[AuthLoader] Cannot show content - content element not found');
      }
    }
    
    // Public method to show loading state (for dynamic auth checks)
    public showLoading(message?: string) {
      if (this.loader && this.content) {
        console.log('[AuthLoader] Showing loading state');
        
        this.content.style.display = 'none';
        this.loader.style.display = 'flex';
        this.loader.style.opacity = '1';
        
        if (message) {
          const messageEl = this.loader.querySelector('.auth-loader-message, .auth-loader-text-small');
          if (messageEl) {
            messageEl.textContent = message;
          }
        }
      } else {
        console.warn('[AuthLoader] Cannot show loading - elements not found:', {
          content: !!this.content,
          loader: !!this.loader
        });
      }
    }
    
    // Public method to hide loading and show content
    public showContent() {
      this.showContentInternal();
    }
  }
  
  // Initialize on DOM ready with a small delay to ensure elements are available
  function initializeAuthLoader() {
    console.log('[AuthLoader] Document ready state:', document.readyState);
    
    // Add a small delay to ensure DOM elements are available
    setTimeout(() => {
      new AuthLoader();
    }, 10);
  }
  
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeAuthLoader);
  } else {
    initializeAuthLoader();
  }
  
  // Expose globally for dynamic usage
  (window as any).AuthLoader = AuthLoader;
</script>