# Xertica UI

> **Enterprise-grade React design system** built on Tailwind CSS v4, Radix UI, and Lucide Icons — with a robust AI-first documentation layer for precise LLM-driven composition and autonomous agent interaction.

[![npm version](https://img.shields.io/badge/npm-2.5.3-blue)](https://www.npmjs.com/package/xertica-ui)
[![license](https://img.shields.io/badge/license-proprietary-red)](./LICENSE)

---

## 🤖 AI-First Single Source of Truth

Xertica UI is specifically designed to be consumed by AI Agents (LLMs, code assistants, autonomous agents). We provide dedicated entry points for AI context:

| File                                     | Purpose                                                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------- |
| [`llms.txt`](./llms.txt)                 | Standard index for AI crawlers and context-aware agents.                                    |
| [`llms-compact.txt`](./llms-compact.txt) | **Compact documentation** of all components in a single file for LLMs with limited context. |
| [`llms-full.txt`](./llms-full.txt)       | **Complete documentation** of all components in a single file for LLMs with large-context.  |
| `docs/llms.md`                           | Master index for agents to navigate the documentation folder.                               |

---

## 🚀 Quick Start — CLI (Recommended)

Scaffold a full application with pre-configured routing, layout, and components:

```bash
npx xertica-ui@latest init my-app
cd my-app
npm run dev
```

During `init`, the CLI walks you through:

| Prompt                             | Choices                                                  |
| ---------------------------------- | -------------------------------------------------------- |
| Pages to include                   | Login, Home, Template (multi-select)                     |
| **Languages to support**           | Português (BR), English, Español — select **1, 2, or 3** |
| Default color theme                | Xertica, Slate, Blue, Violet, Rose, Emerald, …           |
| **Enable dark mode support?**      | yes (default) / no                                       |
| **Include AI Assistant**           | yes (default) / no                                       |
| Install dependencies automatically | yes / no                                                 |

The CLI generates a tailored project with:

- Only the locale JSON files for the languages you picked (no orphan files)
- `src/i18n.ts` with imports + `resources` for exactly those languages
- `src/app/App.tsx` with the `availableLanguages` prop on `<XerticaProvider>` (omitted when all 3 defaults are selected) and `disableDarkMode={true}` if dark mode support was disabled
- A persisted selection in `src/locales/.languages.json` so the `update` command can preserve it
- Feature flags in `.xertica.json` (e.g. `hasAssistant`, `disableDarkMode`) so the `update` command can read the current state

### Monolingual mode (transparent)

If you select only one language, the project becomes **monolingual** — the `<LanguageSelector>` automatically renders `null` (there is nothing to switch to). A header comment in the generated `App.tsx` documents this behavior. To force the selector visible anyway, pass `<LanguageSelector showWhenMonolingual />`.

### Updating languages later

```bash
npx xertica-ui update      # then choose "Languages"
```

The flow shows your current selection, lets you toggle languages, and on confirmation:

- copies any newly-added locale JSON from `node_modules/xertica-ui/templates/src/locales/`
- removes JSONs of unselected languages
- regenerates `src/i18n.ts` and `src/app/App.tsx`
- updates `src/locales/.languages.json`

The `update` → **Project files** flow also reads `.languages.json` and preserves your selection — overwrites of `App.tsx` and `i18n.ts` won't reset your languages to defaults.

### Enabling or disabling Dark Mode support later

```bash
npx xertica-ui update      # then choose "Dark Mode"
```

The flow detects the current state (via `.xertica.json`) and prompts you to enable or disable dark mode. On confirmation, it updates `.xertica.json` and regenerates `App.tsx` with the updated `disableDarkMode` flag (which hides the `ThemeToggle` and template settings tab switch when disabled).

### Adding or removing the AI Assistant later

```bash
npx xertica-ui update      # then choose "Assistant"
```

The flow detects the current state (via `.xertica.json` or file presence) and shows the appropriate action:

- **Add**: copies `src/features/assistant/` and `src/pages/AssistantPage.tsx`, adds the `/assistente` route to `AuthGuard.tsx`, and updates `HomePage.tsx` / `TemplatePage.tsx` to include the assistant panel.
- **Remove**: deletes those files, removes the route, and regenerates the page files without assistant imports.

Feature flags are persisted in `.xertica.json` at the project root.

> **Note:** Always use `@latest` with npx. Without it, npx may execute a locally cached older version instead of fetching the latest from the registry.

---

## 📦 Installation as a Library

To add Xertica UI to an existing React project:

```bash
npm install xertica-ui
```

**1. Import the stylesheet** in your entry file (`main.tsx` or `App.tsx`):

```tsx
import 'xertica-ui/style.css';
```

**2. Import components from the matching subpath**:

```tsx
import { Button, Card } from 'xertica-ui/ui';

export function Example() {
  return (
    <Card className="p-4">
      <Button>Continue</Button>
    </Card>
  );
}
```

**3. Optionally wrap your app** with `XerticaProvider` when you want coordinated theme, layout, assistant, maps, tooltip, API-key, language, and toast services:

```tsx
import { XerticaProvider } from 'xertica-ui/brand';

function App() {
  return (
    <XerticaProvider>
      <YourApp />
    </XerticaProvider>
  );
}
```

**Configuring languages at runtime** — `<XerticaProvider>` accepts `availableLanguages` to override the default set. When only one language is configured, the `LanguageSelector` auto-hides:

```tsx
import { XerticaProvider, DEFAULT_LANGUAGES } from 'xertica-ui';
import fr from './locales/fr.json';

// Monolingual English (no language picker)
<XerticaProvider availableLanguages={[{ code: 'en', label: 'English' }]}>

// Defaults + a custom locale (bundle auto-registered with i18next)
<XerticaProvider
  availableLanguages={[
    ...DEFAULT_LANGUAGES,
    { code: 'fr', label: 'Français', shortLabel: 'FR', resources: fr },
  ]}
>
```

See [`docs/i18n.md`](./docs/i18n.md) for the full `LanguageDefinition` and `registerLanguageResource` API.

---

## 📂 Subpath Imports (FSD/FDA)

Xertica UI v2 exposes **granular subpath entries** — import only what your layer needs without loading the entire library:

```tsx
import { Button, Card, Input } from 'xertica-ui/ui'; // shared/ui — primitives
import { QuickActionCard } from 'xertica-ui/blocks'; // composed blocks
import { Sidebar, Header } from 'xertica-ui/layout'; // layout shell
import { XerticaProvider } from 'xertica-ui/brand'; // app-level — providers & brand
import { XerticaAssistant } from 'xertica-ui/assistant'; // feature — AI assistant
import { VideoPlayer, AudioPlayer } from 'xertica-ui/media'; // feature — media players
import { useLayout, useOptionalLayout, useTheme } from 'xertica-ui/hooks'; // shared/lib — hooks & contexts
import { TemplatePage } from 'xertica-ui/pages'; // optional page templates
import 'xertica-ui/style.css'; // styles — import once at root
```

The root `from 'xertica-ui'` barrel remains available for full backward compatibility.

> **TypeScript**: requires `"moduleResolution": "bundler"` (or `"node16"` / `"nodenext"`) in `tsconfig.json` to resolve subpath exports.

### Component Independence Contract

`xertica-ui/style.css` is the only required global import. Public components are designed to render independently whenever possible, so importing one component into a consumer project should also bring the runtime logic that component needs.

`XerticaProvider` remains the recommended app-level convenience wrapper, but it is not required for most primitives. It composes the library providers for theme, brand colors, language, layout, assistant state, API keys, Google Maps, tooltips, and toasts.

Components with unavoidable external configuration, such as Google Maps, should render a configuration or error state instead of crashing the app.

---

## 🛠️ The Layout System

Xertica UI features an autonomous layout system managed by `LayoutContext`.

### Mandatory Page Structure

Every page **must** use the `<PageHeader>` component for its title and primary actions. Never use raw `h1` or `div` for headers.

```tsx
import { PageHeader, PageHeaderHeading, Button } from 'xertica-ui/ui';

export function MyPage() {
  return (
    <>
      <PageHeader>
        <PageHeaderHeading>Dashboard</PageHeaderHeading>
        <Button>Action</Button>
      </PageHeader>
      <div className="p-6">{/* Page Content */}</div>
    </>
  );
}
```

### `useLayout()` Hook

Access the sidebar state, width, and toggle functions anywhere in the component tree:

```tsx
import { useLayout } from 'xertica-ui/hooks';

const { sidebarWidth, isSidebarOpen, toggleSidebar } = useLayout();
```

Use `useLayout()` when a page must fail early without a layout provider. Use `useOptionalLayout()` inside reusable components that should still render with internal fallbacks when imported in isolation.

```tsx
import { useOptionalLayout } from 'xertica-ui/hooks';

const layout = useOptionalLayout();
const sidebarWidth = layout?.sidebarWidth ?? 0;
```

---

## 🏗️ CLI Template — FSD/FDA Architecture

Projects scaffolded with `npx xertica-ui@latest init` follow **Feature-Sliced Design (FSD) + Feature-Driven Architecture (FDA)**:

```
src/
  app/              ← BrowserRouter, XerticaProvider, AuthGuard, AppLayout
  shared/
    config/         ← navigation.ts (route definitions)
    lib/            ← auth.ts (localStorage helpers)
    types/          ← auth.ts (User interface)
  features/
    auth/ui/        ← LoginContent, ForgotPasswordContent, VerifyEmailContent, ResetPasswordContent
    home/
      data/mock.ts  ← typed fetch + factory functions like getMockRichSuggestions()
      hooks/        ← useFeatureCards() — language-aware queryKey
      ui/           ← HomeContent
    template/ui/    ← TemplateContent, FormTemplate
    assistant/      ← AssistantConfig + useAssistantConfig() (only when AI Assistant is included)
  pages/            ← thin wrappers: LoginPage, HomePage, TemplatePage, AssistantPage, …
  styles/           ← index.css, xertica/tokens.css
  i18n.ts           ← generated by CLI — imports/resources for selected languages only
  locales/
    pt-BR.json
    en.json         ← only files for the languages you selected
    es.json
    .languages.json ← persisted selection (read by `npx xertica-ui update`)
```

Each feature only imports from `shared/` or its own domain. Pages only compose features. Server-state hooks (e.g. `useFeatureCards`) include the active **language** in their `queryKey` so locale switching invalidates and refetches automatically. See `templates/guidelines/Guidelines.md` for the full architecture guide.

---

## 🧩 Component Catalog (100+ Components)

### Layout & Navigation

`Header` · `Sidebar` · `PageHeader` · `Breadcrumb` · `NavigationMenu` · `Tabs` · `Pagination` · `Accordion` · `Collapsible`

### Core Surfaces

`Card` · `Separator` · `ScrollArea` · `AspectRatio` · `Resizable` · `Skeleton` · `Empty`

### Forms & Inputs

`Form` · `Input` · `Textarea` · `RichTextEditor` · `Label` · `Checkbox` · `RadioGroup` · `Switch` · `Select` · `Slider` · `Calendar` · `InputOTP` · `FileUpload` · `Search`

### Actions & Data

`Button` · `Toggle` · `ToggleGroup` · `Rating` · `Table` · `Badge` · `Avatar` · `Progress` · `StatsCard` · `Timeline` · `Stepper` · `TreeView` · `NotificationBadge` · `Chart`

### Overlays & Feedback

`Dialog` · `AlertDialog` · `Sheet` · `Drawer` · `Popover` · `HoverCard` · `Tooltip` · `Alert` · `Sonner (Toast)` · `Command`

### Composed Blocks (with matching skeleton variants)

| Card                             | Skeleton                   |
| -------------------------------- | -------------------------- |
| `FeatureCard`                    | `FeatureCardSkeleton`      |
| `ActivityCard`                   | `ActivityCardSkeleton`     |
| `ProfileCard`                    | `ProfileCardSkeleton`      |
| `ProjectCard`                    | `ProjectCardSkeleton`      |
| `QuickActionCard`                | `QuickActionCardSkeleton`  |
| `NotificationCard`               | `NotificationCardSkeleton` |
| `StatsCard` (in `xertica-ui/ui`) | `StatsCardSkeleton`        |

Each skeleton mirrors its card's visual layout with pulsing placeholders for loading states:

```tsx
{
  isLoading ? <ActivityCardSkeleton rows={5} /> : <ActivityCard items={items} />;
}
```

---

## 🌟 Specialized Modules

### 🤖 AI Assistant

Integrated AI chat panel with workspace support. Use `demoMode={true}` for mock responses without an API key; pass `demoMode={false}` and a `geminiApiKey` (via `<XerticaProvider apiKey="...">`) for real Gemini integration.

- `XerticaAssistant` · `MarkdownMessage` · `CodeBlock` · `AssistantChart` · `ModernChatInput` · `FormattedDocument`

### 🗺️ Maps & Geolocation

First-class Google Maps integration.

- `Map` · `RouteMap` · `SimpleMap` · `GoogleMapsLoader`

### 🎙️ Media

- `AudioPlayer` · `VideoPlayer` · `FloatingMediaWrapper`

### 📄 Pages

- `LoginPage` · `HomePage` · `TemplatePage` · `AssistantPage` · `ForgotPasswordPage` · `ResetPasswordPage` · `VerifyEmailPage`

### 🧱 Blocks

High-level dashboard and product patterns exported from `xertica-ui/blocks` (also re-exported from the root barrel). Every card ships with a matching `*Skeleton` loading-state companion — see the table in **Composed Blocks** above.

The CLI template includes a small fixed version badge so generated projects can visually identify which `xertica-ui` package version they are using.

---

## 📚 Storybook Documentation

Storybook Docs pages use each component's real story variations instead of repeating a single usage example. UI component MDX files now render the story list directly, so docs stay aligned with the component's public stories.

Map stories use a wider responsive preview frame, making `Map`, `RouteMap`, and related map examples readable in the Docs canvas.

---

## 🎨 Design Tokens & Theming

Xertica UI uses semantic CSS tokens. **Never use raw colors or generic Tailwind color classes**.

### Color Themes

Nine built-in themes — each sets the primary color, sidebar, chart palette, and dark-mode surface hue. Select at `init` time or change later with `npx xertica-ui update → Theme only`.

| Theme | ID | Primary | Sidebar | Dark bg |
|---|---|---|---|---|
| ![#2C275B](https://img.shields.io/badge/-%232C275B-2C275B?style=flat-square) Xertica | `xertica-original` | `#2C275B` | `#2C275B` | `#05050d` |
| ![#18181B](https://img.shields.io/badge/-%2318181B-18181B?style=flat-square) Zinc | `zinc` | `#18181B` | `#18181B` | `#05050d` |
| ![#0F172A](https://img.shields.io/badge/-%230F172A-0F172A?style=flat-square) Slate | `slate` | `#0F172A` | `#0F172A` | `#05050d` |
| ![#2563EB](https://img.shields.io/badge/-%232563EB-2563EB?style=flat-square) Blue | `blue` | `#2563EB` | `#1E3A8A` | `#03050f` |
| ![#7C3AED](https://img.shields.io/badge/-%237C3AED-7C3AED?style=flat-square) Violet | `violet` | `#7C3AED` | `#4C1D95` | `#07040f` |
| ![#BE123C](https://img.shields.io/badge/-%23BE123C-BE123C?style=flat-square) Rose | `rose` | `#BE123C` | `#881337` | `#0f0305` |
| ![#047857](https://img.shields.io/badge/-%23047857-047857?style=flat-square) Emerald | `emerald` | `#047857` | `#064E3B` | `#030f08` |
| ![#B45309](https://img.shields.io/badge/-%23B45309-B45309?style=flat-square) Amber | `amber` | `#B45309` | `#78350F` | `#0f0a03` |
| ![#C2410C](https://img.shields.io/badge/-%23C2410C-C2410C?style=flat-square) Orange | `orange` | `#C2410C` | `#7C2D12` | `#0f0703` |

> Each badge renders the **exact primary color** of that theme as a filled swatch. Generated by the CLI and stored in `src/styles/xertica/tokens.css`.

**CLI — Select at project creation:**

```bash
npx xertica-ui@latest init my-app
# → "Select the default color theme" prompt appears during init
```

**CLI — Change theme in an existing project:**

```bash
npx xertica-ui update
# → choose "Theme only"
# → select any of the 9 themes
# → src/styles/xertica/tokens.css is fully regenerated
# → .xertica.json is updated with the new themeId for future updates
```

**Code — Select theme in `XerticaProvider`:**

```tsx
// Full preset — sets primary, sidebar, charts AND hue-tinted dark surfaces
<XerticaProvider defaultColorTheme="blue">
<XerticaProvider defaultColorTheme="rose">
<XerticaProvider defaultColorTheme="emerald">
<XerticaProvider defaultColorTheme="violet">
<XerticaProvider defaultColorTheme="amber">
<XerticaProvider defaultColorTheme="orange">
<XerticaProvider defaultColorTheme="xertica-original"> {/* default */}

// Custom hex — sets primary only; dark surfaces use the neutral default
<XerticaProvider primaryColor="#7C3AED">
```

**What each theme changes:**

| Token category       | Controlled by theme |
| -------------------- | ------------------- |
| `--primary`          | ✅ Light + dark variant |
| `--sidebar`          | ✅ Light + dark variant |
| `--chart-1..5`       | ✅ Brand-matched palette |
| `--gradient-diagonal`| ✅ Brand-matched gradient |
| `--background`       | ✅ Dark mode only (hue-tinted) |
| `--card`, `--popover`| ✅ Dark mode only (hue-tinted) |
| `--muted`, `--accent`| ✅ Dark mode only (hue-tinted) |
| `--border`, `--input`| ✅ Dark mode only (hue-tinted) |
| Light mode surfaces  | ❌ Always white/zinc (unchanged) |

### Mobile Content Padding

The CSS token `--mobile-content-padding` (default `1.25rem`) controls the horizontal padding of content areas on small screens (`< 768px`). To adjust it globally, override it in your project's `src/styles/xertica/tokens.css`:

```css
:root {
  --mobile-content-padding: 1.5rem; /* increase */
}
```

```
Background:     bg-background          text-foreground
Card surface:   bg-card                text-card-foreground
Muted area:     bg-muted               text-muted-foreground
Primary action: bg-primary             text-primary-foreground
Destructive:    bg-destructive         text-destructive-foreground
Border:         border-border
```

---

## 🌍 Localization

Xertica UI is fully internationalized via **`i18next`** + **`react-i18next`**.

- **UI Components**: Translated out-of-the-box in **Portuguese (pt-BR)**, **English**, and **Español**. Every component uses `useTranslation()` — no hardcoded strings.
- **Runtime extensibility**: Add custom locales (e.g. `fr`, `ja`, `de`) at runtime via `<XerticaProvider availableLanguages={[...]}>` — no source-file edits required.
- **Monolingual mode**: Configure a single language to make the `LanguageSelector` auto-hide.
- **Language-aware React Query**: Hooks include the active language in their `queryKey` so mock/API responses translated via `i18n.t()` refetch automatically when the user switches language. No page reload required.
- **Documentation/Code**: Strictly maintained in **English** for AI Agent compatibility and global developer standard.

See [`docs/i18n.md`](./docs/i18n.md) for setup, runtime configuration, and adding custom locales.

---

## 💻 Tech Stack

| Technology   | Version |
| ------------ | ------- |
| React        | 18.3    |
| TypeScript   | 5.7     |
| Tailwind CSS | 4.0     |
| Vite         | 6.0     |
| Radix UI     | Latest  |
| Lucide React | 0.469+  |
| Vitest       | 4.1     |

---

## 📜 Scripts

| Command              | Description                            |
| -------------------- | -------------------------------------- |
| `npm run dev`        | Start development server               |
| `npm run build`      | Production bundle                      |
| `npm run storybook`  | Launch component library documentation |
| `npm run test`       | Run unit tests via Vitest              |
| `npm run type-check` | TypeScript validation                  |

---

## ⚖️ License

Proprietary — Xertica.ai Team.
