// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { createContext, useContext, useState, useEffect } from 'react';

const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [cryptographicKey, setCryptographicKey] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Fase 36: IAM Aegis Gatekeeper
    const storedToken = localStorage.getItem('XCU_OMNI_TOKEN');
    if (storedToken) {
      try {
        const payload = JSON.parse(atob(storedToken.split('.')[1]));
        if (payload.exp * 1000 < Date.now()) {
          throw new Error('Token Expired');
        }
        setCryptographicKey(storedToken);
        setIsAuthenticated(true);
      } catch (e) {
        localStorage.removeItem('XCU_OMNI_TOKEN');
      }
    }
    setIsLoading(false);
  }, []);

  const aegisAuth = (authType, keyPayload, sessionId = null) => {
    return new Promise((resolve, reject) => {
      const gatekeeperUrl = import.meta.env.VITE_GATEKEEPER_WS_URL || 'ws://localhost:4001';
      const ws = new WebSocket(gatekeeperUrl);
      
      ws.onopen = () => {
        ws.send(JSON.stringify({
          type: 'AEGIS_AUTH_REQUEST',
          payload: { authType, keyPayload, sessionId }
        }));
      };

      ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          if (data.type === 'AUTH_SUCCESS') {
            const token = data.payload.token;
            localStorage.setItem('XCU_OMNI_TOKEN', token);
            setCryptographicKey(token);
            setIsAuthenticated(true);
            ws.close();
            resolve({ success: true });
          } else if (data.type === 'MFA_SEQUENCE_STARTED' || data.type === 'MFA_STEP_REQUIRED') {
            ws.close();
            resolve({ mfa: true, type: data.type, payload: data.payload });
          } else if (data.type === 'AUTH_FAILED') {
            ws.close();
            reject(new Error(data.payload));
          }
        } catch (e) {
          reject(e);
        }
      };

      ws.onerror = (e) => {
        reject(new Error("IAM Gatekeeper Unreachable. Quantum Network down."));
      };
    });
  };

  const logout = () => {
    localStorage.removeItem('XCU_OMNI_TOKEN');
    setCryptographicKey(null);
    setIsAuthenticated(false);
  };

  return (
    <AuthContext.Provider value={{ isAuthenticated, cryptographicKey, aegisAuth, logout, isLoading }}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}
