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

const IamContext = createContext();

export function IamProvider({ children }) {
  const [activeIdentity, setActiveIdentity] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);
  const { cryptographicKey, isAuthenticated } = useAuth();

  useEffect(() => {
    // If not authenticated, clear identity and stop loading
    if (!isAuthenticated || !cryptographicKey) {
      setActiveIdentity(null);
      setIsLoading(false);
      return;
    }

    // Decode JWT from AuthContext
    try {
      const payload = JSON.parse(atob(cryptographicKey.split('.')[1]));
      
      // Initially set identity from JWT (Phase 30)
      setActiveIdentity({
        role: payload.role,
        tenant_id: payload.tenant_id,
        username: payload.role === 'supreme_admin' ? 'SUPREME COMMAND' : payload.tenant_id,
        packages: payload.packages || []
      });
      setIsLoading(false);

      // (Optional) Phase 33: Fetch live DuckDB Matrix data over API
      // We skip fetch if it's not implemented yet to avoid red error screen
    } catch (e) {
      console.error("JWT Decode Error:", e);
      setError("Failed to decode Quantum Token");
      setIsLoading(false);
    }
  }, [cryptographicKey, isAuthenticated]);

  if (error) {
    return <div style={{color: 'red', padding: '50px'}}>CRITICAL IAM ERROR: {error}</div>;
  }

  return (
    <IamContext.Provider value={{ identity: activeIdentity }}>
      {children}
    </IamContext.Provider>
  );
}

export function useIam() {
  return useContext(IamContext);
}
