# Futureverse Auth UI

A client-side React UI library that provides customizable authentication components and flows for Web3 wallets and Pass custodial authentication. Works with both [Futureverse Auth React](https://www.npmjs.com/package/@futureverse/auth-react) for standard React applications and [@futureverse/next-auth](https://www.npmjs.com/package/@futureverse/next-auth) for Next.js applications, enabling seamless integration of both decentralized wallet connections and custodial Pass authentication.

## Installation

```bash
npm install @futureverse/auth-ui
# or
yarn add @futureverse/auth-ui
# or
pnpm add @futureverse/auth-ui
# or
bun add @futureverse/auth-ui
```

### Peer Dependencies

Make sure to install the required peer dependencies:

```bash
npm install wagmi viem @tanstack/react-query
# or
yarn add wagmi viem @tanstack/react-query
# or
pnpm add wagmi viem @tanstack/react-query
# or
bun add wagmi viem @tanstack/react-query
```

## Features

- 🎨 **Pre-built Themes** - Ready-to-use Futureverse theming
- 🔧 **Fully Customizable** - Adapt components to match your brand
- 🏷️ **White-labeling** - Custom logos, colors, and branding
- 🧩 **Plug & Play** - Drop-in React components for rapid development

## Quick Start

> **Prerequisites:** Make sure you have set up your `authClient` by following the [@futureverse/auth-react](https://www.npmjs.com/package/@futureverse/auth-react) documentation.

### 1. Create Wagmi Configuration

```typescript
// wagmi-config.ts
import { createWagmiConfig } from '@futureverse/wagmi-connectors';
import { mainnet, sepolia } from 'viem/chains';
import { cookieStorage, createStorage } from 'wagmi';
import { authClient } from './auth';

export const wagmiConfig = createWagmiConfig({
  walletConnectProjectId: 'YOUR_WALLETCONNECT_PROJECT_ID',
  xamanAPIKey: 'YOUR_XAMAN_API_KEY', // Optional
  authClient,
  ssr: true, // Set to true for SSR apps
  chains: [mainnet, sepolia], // Add your required chains
  storage: createStorage({
    storage: cookieStorage,
  }),
  metamaskDappMetadata: {
    name: 'Your App Name',
    url: 'http://localhost:3000',
  },
}); 
```

### 2. Setup Providers

```typescript
'use client';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { type ThemeConfig, AuthUiProvider, DefaultTheme } from '@futureverse/auth-ui';
import React from 'react';
import { authClient } from './auth';
import { wagmiConfig } from './wagmi-config';

const queryClient = new QueryClient();

const customThemeConfig: ThemeConfig = {
  ...DefaultTheme,
  defaultAuthOption: 'web3',
};

export default function Providers({ children }: { children: React.ReactNode }) {
  return (
    <QueryClientProvider client={queryClient}>
      <AuthUiProvider 
        themeConfig={customThemeConfig} 
        authClient={authClient}
        wagmiConfig={wagmiConfig}
      >
        {children}
      </AuthUiProvider>
    </QueryClientProvider>
  );
}
```

### 3. Use Authentication Hook

```typescript
import { useAuthUi } from '@futureverse/auth-ui';

export default function LoginButton() {
  const { openLogin, closeLogin, isLoginOpen, currentState } = useAuthUi();

  return <button onClick={() => openLogin()}>{isLoginOpen ? 'Close Login' : 'Open Login'}</button>;
}
```

## API Reference

### Providers

#### AuthUiProvider

The main provider component that wraps your application with Auth UI functionality.

```typescript
import { AuthUiProvider } from '@futureverse/auth-ui';

<AuthUiProvider 
  themeConfig={themeConfig} 
  authClient={authClient}
  wagmiConfig={wagmiConfig}
  legalLinks={{
    privacyPolicyUrl: 'https://yourcompany.com/privacy-policy',
    termsOfServiceUrl: 'https://yourcompany.com/terms-of-service',
  }}
>
  {children}
</AuthUiProvider>;
```

##### Props

| Prop                  | Type                    | Required | Description                        |
| --------------------- | ----------------------- | -------- | ---------------------------------- |
| `themeConfig`         | `ThemeConfig`           | Yes      | Theme configuration object         |
| `authClient`          | `FutureverseAuthClient` | Yes      | Auth client instance               |
| `wagmiConfig`         | `Config`                | Yes      | Wagmi configuration instance       |
| `locale`              | `Locale`                | No       | Localization settings              |
| `orderedConnectorIds` | `string[]`              | No       | Custom order for wallet connectors |
| `legalLinks`          | `LegalLinks`            | No       | Company legal links                |

##### legalLinks

The `legalLinks` prop allows you to customize the branding and legal information displayed in authentication flows, particularly in session prompt.

```typescript
type LegalLinks = {
  privacyPolicyUrl: string;    // URL to privacy policy
  termsOfServiceUrl: string;   // URL to terms of service
};
```

**Example usage:**

```typescript
const legalLinks = {
  privacyPolicyUrl: 'https://yourcompany.com/privacy',
  termsOfServiceUrl: 'https://yourcompany.com/terms',
};

<AuthUiProvider
  themeConfig={themeConfig}
  authClient={authClient}
  wagmiConfig={wagmiConfig}
  legalLinks={legalLinks}
>
  {children}
</AuthUiProvider>
```

When provided, this information will be displayed in session prompts with text like: "Before connecting, review this app’s privacy policy and terms of service."

#### AuthThemeProvider

Advanced theme provider for custom authentication flows. Used internally by `AuthUiProvider`.

```typescript
import { AuthThemeProvider } from '@futureverse/auth-ui';

<AuthThemeProvider themeConfig={themeConfig}>{children}</AuthThemeProvider>;
```

### Hooks

#### useAuthUi()

Access authentication modal state and controls.

```typescript
import { useAuthUi } from '@futureverse/auth-ui';

const {
  isLoginOpen, // Boolean: modal open state
  openLogin, // Function: open the modal
  closeLogin, // Function: close the modal
} = useAuthUi();
```

#### useAuthTheme()

Access the current theme configuration.

```typescript
import { useAuthUi, useAuthTheme } from '@futureverse/auth-ui';

const { isLoginOpen, openLogin, closeLogin } = useAuthUi();
const { themeConfig } = useAuthTheme();
```

## Theming

- **DefaultTheme**: Delivers the classic Futureverse aesthetic, ready to use out of the box.
- **CoreColors**: Includes essential colors, such as black, white, and transparent variants for versatile styling.
- **Other Typesafe Theme Types**: Access additional types like ThemeConfig, AuthOption, Colors, Fonts, BorderRadius for enhanced customization.
- **Whitelabeling**: Add a modal logo image or a background image to seamlessly integrate the auth UI modal with your personalized brand identity.

```typescript
import { type ThemeConfig, DefaultTheme, AuthOption, CoreColors } from '@futureverse/auth-ui';
```

```typescript
type ThemeConfig = {
  defaultAuthOption?: AuthOption; // 'web3' | 'custodial'
  showCloseButton?: boolean;
  colors: Colors;
  font: Fonts;
  titleFont?: Fonts; // Optional separate title font
  borderRadius: BorderRadius;
  blur?: number; // Blur effect intensity
  images?: {
    background?: string; // Background image URL
    logo?: string; // Logo image URL
  };
  // Visibility controls
  hideWeb3?: boolean;
  hideCustodial?: boolean;
  hideConnectors?: Array<string>;
};
```

```typescript
type AuthOption = 'web3' | 'custodial';

type Colors = {
  /** Primary */
  primaryBackground: string;
  primaryForeground: string;
  primaryHover: string;
  primaryActive: string;
  primaryBackgroundDisabled: string;
  primaryForegroundDisabled: string;

  /** Secondary */
  secondaryBackground: string;
  secondaryForeground: string;
  secondaryHover: string;
  secondaryActive: string;
  secondaryBackgroundDisabled: string;
  secondaryForegroundDisabled: string;

  /** Border */
  border: string;
  borderHover: string;
  borderActive: string;
  borderError: string;

  /** Shared Stylings */
  errorForeground: string;
  body: string;
  muted: string;
  surface: string;
  page: string;
};

type Fonts = {
  fontUrl: string;
  fontName: string;
};

type BorderRadius = {
  none: number;
  default: number;
  large: number;
};
```

#### Overwrite Theming and Font Examples

- **Color Values**: All color properties must be specified using RGBA values for consistency and transparency control.
- **Font Customization**: You can easily integrate custom fonts by providing the font URL and name. By default, title and body fonts will utilize the same font, but you have freedom to set a title font.
- **Border Radius**: The ability to tweak the border-radius px number values of auth-ui components to your liking.
- **Blur**: You are able to tweak the blur px value for various components such as Card, Dialog, Dropdown.
- **Comprehensive Theming**: The theme object allows you to customize various aspects. You can either create a completely custom theme or selectively override specific elements while inheriting the rest from the default theme.

```typescript
import { type ThemeConfig } from '@futureverse/auth-ui';

const customThemeConfig: ThemeConfig = {
  defaultAuthOption: 'web3',
  colors: {
    // Primary colors
    primaryBackground: 'rgba(255, 255, 255, 0.1)',
    primaryForeground: 'rgba(255, 255, 255, 1)',
    primaryHover: 'rgba(255, 255, 255, 0.2)',
    primaryActive: 'rgba(133, 133, 133, 1)',
    primaryBackgroundDisabled: 'rgba(218, 218, 218, 0.2)',
    primaryForegroundDisabled: 'rgba(165, 163, 164, 1)',

    // Secondary colors
    secondaryBackground: 'rgba(0, 0, 0, 1)',
    secondaryForeground: 'rgba(165, 163, 164, 1)',
    secondaryHover: 'rgba(207, 207, 207, 1)',
    secondaryActive: 'rgba(207, 207, 207, 1)',
    secondaryBackgroundDisabled: 'rgba(218, 218, 218, 0.2)',
    secondaryForegroundDisabled: 'rgba(165, 163, 164, 1)',

    // Border colors
    border: 'rgba(68, 68, 68, 1)',
    borderHover: 'rgba(255, 255, 255, 1)',
    borderActive: 'rgba(255, 255, 255, 1)',
    borderError: 'rgba(171, 21, 57, 1)',

    // Utility colors
    errorForeground: 'rgba(171, 21, 57, 1)',
    body: 'rgba(255, 255, 255, 1)',
    muted: 'rgba(182, 182, 182, 1)',
    surface: 'rgba(0, 0, 0, 0.5)',
    page: 'rgba(24, 24, 24, 1)',
  },
  font: {
    fontUrl: 'https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap',
    fontName: 'Inter',
  },
  borderRadius: {
    none: 0,
    default: 8,
    large: 24,
  },
  blur: 8,
};
```

```typescript
const customThemeConfig: ThemeConfig = {
  ...DefaultTheme,
  colors: {
    ...DefaultTheme.colors,
    muted: 'rgba(1, 1, 1, 1)',
  },
  borderRadius: {
    ...DefaultTheme.borderRadius,
    default: 10,
  },
  blur: 8,
};
```

### `orderedConnectorIds` Prop

You can control the display order of connector options in the Auth UI modal by passing the `orderedConnectorIds` prop to `AuthUiProvider`. This prop should be an array of connector IDs (strings). Both Web3 and Custodial connector options will be sorted to match the order specified in this array. Any connectors not listed will appear after the ordered ones, in their default order.

**Example:**

```tsx
<AuthUiProvider themeConfig={customThemeConfig} authClient={authClient} orderedConnectorIds={['metaMaskSDK', 'xaman', 'futureverseCustodialGoogle', 'futureverseCustodialFacebook']} />
```

- Connectors are displayed in the order specified
- Unlisted connectors appear after ordered ones in their default order
- Works for both Web3 and Custodial authentication options

### Components

Futureverse Auth UI provides a comprehensive set of components to build your authentication interface. All components accept standard React props, including style and className for custom styling.

**Base Components**

- Button: Customizable action button
- Card: Container for grouped content
- Dialog: Modal dialog for important information
- Icon / IconFactory: Render and manage icons
- Image: Optimized image display
- Typography: Text styling component
- Modal: Customizable modal overlay
- Divider: Visual separator for content sections
- FormattedMessage: Render translated text

**Plug 'n' Play Components**

- Avatar: User profile avatar UI with fallback customization
- ProfileAuthButton: Profile authentication UI
- CustodialAuthButton / CustodialAuthOptions: Custodial authentication UI
- Web3AuthButton / Web3AuthOptions: Web3 authentication UI
- FuturePassAuthOptions: FuturePass-specific auth options
- LoaderAnimation: Loading indicator for async operations
- Input / OTPInput: Text and OTP input fields
- Dropdown: Selectable options in a dropdown format
- Checkbox: Toggleable tick checkbox
