# Frontend JS (static/js/)

## OVERVIEW
Vanilla JavaScript modules loaded via `<script>` tags in HTML templates. No ES module imports in app code — uses global variables (`API_BASE`, `getToken()`) for cross-module communication. Tests use Vitest with ES module syntax.

## STRUCTURE
```
static/js/
├── main.js              # Entry point — DOMContentLoaded, orchestrates tab navigation
├── api.js               # API_BASE config, providers info, search caching
├── auth.js              # Cookie-based token management (getToken, setToken)
├── auth-utils.js        # safeJsonParse, displayError, displaySuccess
├── auth-api.js          # login, register, logout, getMe API calls
├── auth-ui.js           # handleLogin, handleRegister, handleLogout UI handlers
├── anime.js             # loadAnimeReleases (partially HTMX, legacy)
├── anime-details.js     # searchAnimeDetails, episode management (555 lines)
├── series-search.js     # handleSeriesSearch for FS7 provider
├── watchlist.js         # Watchlist CRUD API calls (461 lines)
├── watchlist-ui.js      # displayWatchlist (legacy, redirects to HTMX)
├── tabs.js              # renderSeriesRecommendationCard, tab switching
├── downloads.js         # loadDownloads (legacy, redirects to HTMX)
├── recommendations.js   # loadRecommendations
├── utils.js             # formatBytes utility
└── __tests__/           # Vitest test files
    ├── smoke.test.js
    ├── auth-api.test.js
    └── auth-utils.test.js
```

## WHERE TO LOOK

| Need | File | Notes |
|------|------|-------|
| API base URL / config | `api.js` | Defines `API_BASE` global |
| Auth token access | `auth.js` | `getToken()` used by most API-calling modules |
| Add API endpoint call | Module calling the API | Use `fetch(API_BASE + '/api/...')` + `getToken()` header |
| Add UI component | `auth-ui.js`, `tabs.js` | Alpine.js used for state, HTMX for server interactions |
| Run JS tests | `__tests__/` | `npm test` (Vitest) |

## CONVENTIONS

**Module communication**: Global variables, not ES imports. `api.js` defines `API_BASE`. `auth.js` defines `getToken()`. Other modules consume these globals.

**Loading order matters**: Scripts loaded via `<script>` tags in `base.html` — order defines availability of globals.

**Auth subsystem chain**: `auth.js` (token storage) → `auth-utils.js` (utilities) → `auth-api.js` (API calls) → `auth-ui.js` (UI handlers).

**HTMX + Alpine.js**: Most interactions now use HTMX (server-driven). Alpine.js handles client-side state (modals, toggles, tabs). Legacy JS modules (downloads.js, watchlist-ui.js) redirect to HTMX equivalents.

**Tests**: Vitest with jsdom environment. Test files define skeleton functions matching source — not importing actual source files.

## ANTI-PATTERNS

- Do NOT add ES module `import`/`export` syntax to app JS files — they use global scope
- Do NOT depend on script load order without checking — add null guards
- Do NOT duplicate API call patterns — centralize in `api.js`
