'use client';

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

export function RocketChatAuth() {
  const { data: session } = useSession();
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    async function authenticateWithRocketChat() {
      if (!session?.user?.email) return;

      try {
        // Call our API to get Rocket.Chat tokens
        const response = await fetch('/api/auth/rocket-login');
        
        if (!response.ok) {
          console.error('Failed to authenticate with Rocket.Chat');
          return;
        }
        
        const data = await response.json();
        
        if (data.rocketChatToken && data.rocketChatUserId) {
          // Store tokens in cookies that can be accessed by the Rocket.Chat iframe
          // Note: These cookies need to have proper domain settings to be accessible
          document.cookie = `rc_token=${data.rocketChatToken}; path=/; SameSite=None; Secure`;
          document.cookie = `rc_uid=${data.rocketChatUserId}; path=/; SameSite=None; Secure`;
          
          // Also store in localStorage which Rocket.Chat might check
          localStorage.setItem('Meteor.loginToken', data.rocketChatToken);
          localStorage.setItem('Meteor.userId', data.rocketChatUserId);
          
          console.log('Successfully authenticated with Rocket.Chat');
          setIsAuthenticated(true);
        }
      } catch (error) {
        console.error('Error authenticating with Rocket.Chat:', error);
      }
    }
    
    authenticateWithRocketChat();
  }, [session]);

  // This component doesn't render anything visible
  return null;
}

export default RocketChatAuth; 