sequenceDiagram
    participant U as User Browser
    participant SPA as React SPA
    participant MSAL as MSAL.js
    participant AAD as Azure AD
    participant API as FastAPI Backend
    participant DB as PostgreSQL

    U->>SPA: Navigate to app
    SPA->>MSAL: Check authentication
    MSAL-->>SPA: Not authenticated

    SPA->>MSAL: loginPopup()
    MSAL->>AAD: OAuth2 Authorization
    AAD-->>U: Login prompt
    U->>AAD: Enter credentials
    AAD-->>MSAL: ID Token + Access Token
    MSAL-->>SPA: Authentication success

    Note over SPA: User now authenticated

    SPA->>API: GET /api/me (Bearer token)
    API->>API: verify_access_token(jwt)
    API->>API: Decode & validate claims
    API->>DB: get_or_create_from_azure(oid, email, name)

    alt First login
        DB-->>API: Create user (role: basic_user, agency: null)
    else Existing user
        DB-->>API: Return existing user
    end

    API-->>SPA: {id, email, name, role, agencyId, agencyName}

    Note over SPA: Role-based UI rendering

    rect rgb(9, 130, 31)
        Note over SPA,API: super_admin: Full access to all features
    end
    rect rgb(0, 109, 227)
        Note over SPA,API: oversight_admin: Read-only access to all campaigns
    end
    rect rgb(255, 186, 0)
        Note over SPA,API: agency_admin: Full access within own agency
    end
    rect rgb(227, 0, 15)
        Note over SPA,API: basic_user: Limited access within own agency
    end
