'use client';

import { useState, useEffect, ReactNode } from 'react';

/**
 * ModeGuard - Conditional rendering component based on application mode
 *
 * Usage:
 * <ModeGuard mode="pre-launch">
 *   <PreLaunchContent />
 * </ModeGuard>
 *
 * <ModeGuard mode="alpha">
 *   <FullPlatformContent />
 * </ModeGuard>
 */

export type GuardMode = 'pre-launch' | 'alpha';

interface ModeGuardProps {
  mode: GuardMode;
  children: ReactNode;
  fallback?: ReactNode;
}

/**
 * Client-side mode guard component
 * Note: For initial page load, rely on middleware for route protection
 * This component is for conditional UI rendering within accessible pages
 */
export function ModeGuard({ mode, children, fallback = null }: ModeGuardProps) {
  const [isMounted, setIsMounted] = useState(false);
  const [currentMode, setCurrentMode] = useState<GuardMode>('pre-launch');

  useEffect(() => {
    setIsMounted(true);
    setCurrentMode(getClientMode());
  }, []);

  if (!isMounted) {
    return <>{fallback}</>;
  }

  if (currentMode !== mode) {
    return <>{fallback}</>;
  }

  return <>{children}</>;
}

/**
 * Get mode on client side from injected environment variable
 * Falls back to 'pre-launch' if not available
 */
function getClientMode(): GuardMode {
  if (typeof window === 'undefined') {
    return 'pre-launch';
  }
  
  const mode = process.env.NEXT_PUBLIC_GRIDPILOT_MODE;
  
  if (mode === 'alpha') {
    return 'alpha';
  }
  
  return 'pre-launch';
}

/**
 * Hook to get current mode in client components
 */
export function useAppMode(): GuardMode {
  return getClientMode();
}

/**
 * Hook to check if in pre-launch mode
 */
export function useIsPreLaunch(): boolean {
  return getClientMode() === 'pre-launch';
}

/**
 * Hook to check if in alpha mode
 */
export function useIsAlpha(): boolean {
  return getClientMode() === 'alpha';
}