# Installation Guide — Xertica UI

---

## 1. Package Installation

Install the library via npm:

```bash
npm install xertica-ui
```

Or with other package managers:

```bash
pnpm add xertica-ui
yarn add xertica-ui
```

### Peer Dependencies

The following packages must be present in your project. They are not auto-installed:

```bash
npm install react@^18 react-dom@^18 react-router-dom@^7
```

### Recommended Companion Packages

These are not peer dependencies but are expected in projects using the CLI scaffold or the `features/` architecture:

```bash
npm install @tanstack/react-query zustand i18next react-i18next
```

| Package                 | Version | Purpose                                                           |
| ----------------------- | ------- | ----------------------------------------------------------------- |
| `@tanstack/react-query` | `^5.x`  | Server state — data fetching, caching, background refetch         |
| `zustand`               | `^5.x`  | Client UI state — filters, toggles, form controls                 |
| `i18next`               | `^26.x` | i18n engine — translation key resolution, language switching      |
| `react-i18next`         | `^17.x` | React binding for i18next — `useTranslation()`, `I18nextProvider` |

See [`docs/state-management.md`](../state-management.md) and [`docs/i18n.md`](../i18n.md) for the full guides.

---

## 2. CSS Import (Required)

You **must** import the library's stylesheet. Without it, components will render without backgrounds, borders, or correct spacing:

```tsx
// main.tsx or index.tsx
import 'xertica-ui/style.css';
```

> **For AI agents**: If components look transparent or unstyled, the CSS import is almost always the cause.

---

## 3. Provider Setup (Required)

Wrap your entire application in `<XerticaProvider>`. This must be done once at the root level:

```tsx
// main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { XerticaProvider } from 'xertica-ui/brand';
import 'xertica-ui/style.css';
import './i18n'; // initialize i18next before any component renders
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
```

### Full recommended stack (with Router, Auth, Query, ErrorBoundary, i18n)

```tsx
// App.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { XerticaProvider } from 'xertica-ui/brand';
import { BrowserRouter as Router } from 'react-router-dom';
import { AppErrorBoundary, PageErrorBoundary } from './shared/error-boundary';
import { AuthProvider } from './app/context/AuthContext';

const queryClient = new QueryClient({
  defaultOptions: { queries: { retry: 1, refetchOnWindowFocus: false } },
});

function App() {
  return (
    <AppErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <XerticaProvider>
          <Router>
            <AuthProvider>
              <PageErrorBoundary>
                <YourRoutes />
              </PageErrorBoundary>
            </AuthProvider>
          </Router>
        </XerticaProvider>
      </QueryClientProvider>
    </AppErrorBoundary>
  );
}
```

Provider stack order matters:

1. `AppErrorBoundary` — outermost; catches any crash including provider failures
2. `QueryClientProvider` — enables React Query for all nested components
3. `XerticaProvider` — theme, layout, toasts, tooltips, maps, assistant context
4. `Router` — required before `AuthProvider` (`useNavigate` dependency)
5. `AuthProvider` — session state and navigation guards
6. `PageErrorBoundary` — isolates page-level errors; app chrome stays alive

### Provider Props

| Prop       | Type        | Default      | Description                                      |
| ---------- | ----------- | ------------ | ------------------------------------------------ |
| `children` | `ReactNode` | _(required)_ | Application content to wrap inside all providers |

> **Note**: `XerticaProvider` is a minimal wrapper that initializes `LayoutProvider`, `TooltipProvider`, `GoogleMapsLoaderProvider`, and `Toaster`. Theme configuration is done via CSS tokens in your project's stylesheet. See `docs/guidelines.md` for token customization.

---

## 4. CSS Token Customization

### Option A: Auto-Injected Tokens (Default)

By default, `XerticaProvider` injects a default token set. The tokens respond to the `dark` class on `<html>`.

### Option B: Custom Token File

Use `useCustomTokens={true}` to disable injection and provide your own token file:

```css
/* tokens.css */
:root {
  --background: 0 0% 100%;
  --foreground: 222.2 84% 4.9%;
  --primary: 221.2 83.2% 53.3%;
  --primary-foreground: 210 40% 98%;
  --card: 0 0% 100%;
  --card-foreground: 222.2 84% 4.9%;
  --border: 214.3 31.8% 91.4%;
  /* ... other tokens */
}

.dark {
  --background: 222.2 84% 4.9%;
  --foreground: 210 40% 98%;
  /* ... dark variants */
}
```

Import this file in your main entry:

```tsx
import './styles/tokens.css';
import 'xertica-ui/style.css';
```

---

## 5. CLI Setup (Alternative)

For a fully scaffolded new project:

```bash
npx xertica-ui@latest init
```

The CLI will:

- Scaffold a Vite + React + TypeScript project
- Install all dependencies (including `@tanstack/react-query`, `zustand`, `i18next`, `react-i18next`)
- Configure Tailwind CSS v4
- Create the `tokens.css` token file and `src/locales/pt-BR.json`, `en.json`, `es.json`
- Initialize `i18next` in `src/i18n.ts` and import it in `src/main.tsx`
- Set up `XerticaProvider`, `QueryClientProvider`, `AuthProvider`, `AppErrorBoundary`, `PageErrorBoundary`, router, Sidebar, Header, and example pages
- Create a `TemplatePage` with all components demonstrated
- Generate the `features/` directory with mock data, React Query hooks, and Zustand stores ready to swap for real APIs
- Create `src/shared/error-boundary.tsx` and `error-fallbacks.tsx` for all three granularity levels (`App`, `Page`, `Section`)

### Development Quality Scripts

The scaffolded project includes these scripts in `package.json`:

```bash
npm run dev           # Vite dev server
npm run build         # Production build (TypeScript + Vite)
npm run type-check    # npx tsc --noEmit
npm run lint          # ESLint (flat config v9)
npm run lint:fix      # ESLint with auto-fix
npm run format        # Prettier --write
npm run format:check  # Prettier --check (for CI)
npm run check         # type-check + lint (runs before npm publish)
```

---

## 6. Tailwind CSS v4 Configuration

If setting up Tailwind manually (not via CLI), configure it to scan both your app and the library:

```js
// tailwind.config.js
export default {
  content: ['./src/**/*.{ts,tsx}', './node_modules/xertica-ui/**/*.{js,ts,jsx,tsx}'],
};
```

---

## 7. Subpath Imports (v2)

Xertica UI v2 supports granular subpath imports per layer — useful in FSD/FDA architectures:

```tsx
import { Button, Card, CardContent } from 'xertica-ui/ui';
import { Sidebar, Header } from 'xertica-ui/layout';
import { XerticaProvider } from 'xertica-ui/brand';
import { XerticaAssistant } from 'xertica-ui/assistant';
import { VideoPlayer } from 'xertica-ui/media';
import { useLayout } from 'xertica-ui/hooks';
```

The root `from 'xertica-ui'` barrel remains fully supported for backward compatibility.

> **TypeScript**: Subpath exports require `"moduleResolution": "bundler"` in `tsconfig.json`.

---

## 8. Verification

After setup, render a test component to verify the installation:

```tsx
import { Button, Card, CardContent } from 'xertica-ui/ui';

function Test() {
  return (
    <Card className="w-64 m-8">
      <CardContent className="p-6">
        <Button>Installation Success</Button>
      </CardContent>
    </Card>
  );
}
```

If the card has a white/dark background with a border and the button has a styled primary color, the installation is complete.

### Common Issues

| Symptom                               | Cause                                 | Fix                                           |
| ------------------------------------- | ------------------------------------- | --------------------------------------------- |
| Components are transparent / unstyled | Missing CSS import                    | Add `import 'xertica-ui/style.css'`           |
| Dialogs/modals don't appear           | Missing `<XerticaProvider>`           | Wrap app root with provider                   |
| Dark mode doesn't work                | `useCustomTokens` without dark tokens | Add `.dark` class tokens to your CSS          |
| Toast notifications don't show        | Missing provider                      | `XerticaProvider` auto-injects `<Toaster>`    |
| Type errors on components             | Outdated `@types`                     | Run `npm install --save-dev @types/react@^18` |
