# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Build Commands

```bash
# Install dependencies
yarn                        # JavaScript/TypeScript dependencies
composer install            # PHP dependencies (for linting)

# Development
yarn start                  # Watch mode - compiles assets on change

# Build
yarn build                  # Full build (typecheck + compile)
yarn typecheck              # TypeScript type checking only
yarn bundle                 # Build + create plugin ZIP

# Linting
./vendor/bin/phpcs          # PHP CodeSniffer (WordPress standards)
./vendor/bin/phpcs -n -p    # PHP linting (no warnings, progress)
```

## Architecture Overview

This is a WordPress plugin that integrates AI-powered publishing tools. It uses a hybrid architecture:

**Backend (PHP):** Object-oriented PHP with WordPress hooks system
**Frontend (TypeScript/React):** Modern React with @wordpress/scripts bundling

### Plugin Initialization Flow

```
nota-wordpress-plugin.php (entry point)
    ↓ plugins_loaded hook
Nota::instance() (singleton in includes/class-nota.php)
    ↓ Creates all services via dependency injection
    ├── Nota_Settings - Plugin configuration
    ├── Nota_Api - External API client
    ├── Nota_WP_Rest - AJAX request router
    ├── Nota_Post_Tools - Post editor integration
    ├── Nota_Script - DRAFT article tool
    ├── Nota_News - News recommendations
    └── Nota_Dashboard - Admin dashboard
```

### React Entry Points

Four separate bundles compiled to `/dist/app/`:

| Entry         | File                         | Purpose                        |
| ------------- | ---------------------------- | ------------------------------ |
| postTools     | `assets/js/postTools.ts`     | Post editor meta box & sidebar |
| notaScript    | `assets/js/notaScript.ts`    | DRAFT article generation tool  |
| notaNews      | `assets/js/notaNews.ts`      | News recommendations UI        |
| dashboardPage | `assets/js/dashboardPage.ts` | Main admin dashboard           |

### Frontend-Backend Communication

All AJAX routes through a single endpoint:

```
Frontend (React) → POST wp-admin/admin-ajax.php?action=nota_action
    ↓
Nota_WP_Rest::handle_action() → Routes to service methods → JSON response
```

Frontend services are in `assets/js/services/notaService/` - each function makes requests via the shared fetch utility.

#### Data transport gotchas (learned the hard way)

- **`$_REQUEST` arrives magic-quoted.** WP core runs `wp_magic_quotes()`
  (addslashes) on every request. Always `wp_unslash()` before using or
  `json_decode`-ing request data, or embedded quotes/apostrophes get corrupted
  (`We can't` → `We can\'t`). `topic`, `postHTML`, etc. already take this hit —
  don't add more.
- **Byte-exact passthrough payloads MUST travel as JSON, never form-encoded.**
  Both legs corrupt arrays: `qs.stringify` (JS → admin-ajax) *and*
  `http_build_query` (PHP → nota-api via a WP_Http array body) drop empty arrays
  (`people: []` vanishes) and, past qs's `arrayLimit` of 20, turn long arrays
  into objects keyed `'0','1',…`. Send such a payload as a JSON *string* on the
  JS leg (survives both form encoders intact), `json_decode(wp_unslash(...))` it
  in the handler, and forward with `'headers' => array( 'Content-Type' =>
  'application/json' )` + `wp_json_encode( $body )` (the `nota_json` mechanism in
  `class-nota-wp-rest.php` is the precedent).

### State Management

- **WordPress Data Store** (`assets/js/data/`): Redux store for post metadata, grades, brands, tones
- **React Query**: Server state caching via `@tanstack/react-query`

#### Effect + derived-state patterns

- **Never put state an effect *sets* into its own dep array** — it self-cancels
  and hangs. Drive re-runs off identity + an explicit reload token.
- **Latch *intent*, not transient UI state, for expensive on-demand fetches.**
  Key a fetch effect on a "requested" latch that flips once (per identity, never
  back), not on something incidental like the active tab — otherwise unrelated
  UI changes cancel and re-trigger in-flight work (e.g. a ~15s LLM generation).
- **Invalidate derived state when its inputs change.** A value computed from
  specific inputs (e.g. a precomputed extraction from one asset) must be cleared
  when those inputs change (source add/edit/remove), or it silently grounds
  later work in stale data.

### Styling

Tailwind CSS with `ntw-` prefix to avoid WordPress conflicts. All utilities scoped under `.nota` class for specificity.

## Key Directories

```
includes/           # PHP classes (Nota_* naming convention)
assets/js/
  ├── components/   # React components
  ├── hooks/        # Custom React hooks
  ├── services/     # API service layer
  ├── utils/        # Shared utilities
  └── data/         # WordPress Redux store
templates/admin/    # PHP admin templates
dist/               # Compiled output (not committed)
```

## PHP Class Naming

All PHP classes follow `Nota_*` convention with files named `class-nota-*.php`. Key classes:

- `Nota` - Main singleton orchestrator
- `Nota_Api` - HTTP client for external Nota API
- `Nota_WP_Rest` - Central AJAX handler
- `Nota_Settings` - Options API wrapper
- `Nota_Post_Tools` - Post editor meta box
- `Nota_Migrations` - Database schema versioning

## Code Standards

**PHP:** WordPress Coding Standards via PHPCS (WordPress-Extra, WordPress-VIP-Go)
**TypeScript:** ESLint with @wordpress/eslint-plugin, Prettier
**Pre-commit:** Husky runs lint-staged on staged files
**Validate behavior end-to-end, not just `tsc`/build.** Drive the real app
(e.g. Playwright against a real WordPress) and assert observable behavior. The
data-transport corruption and the tab-flip double-fetch above both pass `tsc`
and only surface at runtime.

## Local Development

Configure `wp-config.php`:

```php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_NOTA_API_URL', 'http://localhost:3010/');
```

Plugin settings at WordPress admin → Settings → Nota Tools (API key, URL, timeout).
