"use client";

import { useEffect } from 'react';
import { useSession } from 'next-auth/react';

export default function SilentRefresh() {
  const { data: session, status } = useSession();
  
  useEffect(() => {
    // Notify parent window of authentication status
    const notifyParent = (statusType: string) => {
      try {
        // Post message to parent window
        if (window.parent && window.parent !== window) {
          window.parent.postMessage({
            type: 'AUTH_STATUS',
            status: statusType,
            timestamp: Date.now()
          }, '*');
          
          console.log(`Silent refresh: notified parent of ${statusType} status`);
        }
      } catch (error) {
        console.error('Error notifying parent window:', error);
      }
    };
    
    // When session status changes, notify parent
    if (status === 'authenticated' && session) {
      // User is authenticated
      notifyParent('AUTHENTICATED');
    } else if (status === 'unauthenticated') {
      // User is not authenticated
      notifyParent('UNAUTHENTICATED');
    }
    
    // Set up automatic cleanup
    const timeout = setTimeout(() => {
      // Notify parent we're cleaning up (in case we're in loading state forever)
      notifyParent('CLEANUP');
    }, 10000); // 10 second timeout
    
    return () => clearTimeout(timeout);
  }, [session, status]);
  
  return (
    <div className="p-4 text-center">
      <h1 className="text-lg font-medium">Silent Authentication Check</h1>
      <p className="text-sm text-gray-500 mt-2">
        {status === 'loading' && 'Checking authentication status...'}
        {status === 'authenticated' && 'You are authenticated.'}
        {status === 'unauthenticated' && 'You are not authenticated.'}
      </p>
    </div>
  );
} 