# AGENTS.md

## Project Overview

@mirai/core is a React component library and provider system for hotel booking interfaces. It provides a complete suite of components for finding, booking, and managing hotel reservations including rates display, checkout flows, user sessions, and promotional deals. The library uses React hooks, CSS modules, and a centralized event system for component communication.

## Architecture

```
Core Provider → Event Manager → Components → Services → External APIs
```

- Core provider wraps the application with shared context and configuration
- Event-driven architecture for component communication via EventManager
- Automatic performance monitoring and error tracking
- CSS modules for scoped styling with theming support
- PropTypes for runtime type checking

## Build and Test Commands

### Quick Start
```bash
# Install dependencies
yarn install

# Start development environment
yarn start

# Run unit tests (Jest)
yarn test

# Run E2E tests (Playwright)
yarn test:e2e

# Build for production
yarn build:npm
```

### Development Commands

#### Testing
```bash
yarn test                    # All unit tests with Jest
yarn test:watch             # Watch mode for unit tests
yarn test:e2e               # Playwright E2E tests with UI
yarn pipeline               # Lint + test (CI pipeline)
```

#### Linting & Validation
```bash
yarn lint                   # ESLint check (MUST pass before commit)
yarn lint:fix              # Auto-fix linting issues
```

## Code Style Guidelines

### CRITICAL: No Comments Policy
**ABSOLUTE RULE**: This codebase uses @mirai/eslint which FORBIDS all comments. Write self-documenting code only.

```javascript
// ❌ FORBIDDEN - Will fail ESLint
// This component renders booking rates

// ✅ REQUIRED - Self-documenting code
const BookingRatesDisplay = ({ rates, onRateSelect }) => {
  return renderRateOptions({ rates, onRateSelect });
};
```

### Import Order
1. External packages (npm dependencies)
2. @mirai scoped packages
3. Relative imports (../components, ../helpers)
4. Local imports (./utils, ./constants)

Each group separated by newline and alphabetically sorted:

```javascript
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';

import { Event } from '@mirai/event-manager';

import { fetchConfig } from '../helpers';

import { BOOKING_STATES } from './booking.constants';
```

### Component Standards
- **Functional Components**: Always use React hooks over class components
- **PropTypes**: Required for all props with detailed shape definitions
- **CSS Modules**: Use `.module.css` files for component-specific styles
- **Event Communication**: Use Event.publish/subscribe for component communication
- **Error Boundaries**: Wrap components that might fail in Core.Error
- **Performance**: Use React.memo for expensive components

### File Naming Conventions
- Components: PascalCase directories with index files (`Finder/index.jsx`)
- Styles: `{Component}.module.css`
- Constants: `{component}.constants.js`
- Tests: `{Component}.test.jsx` (unit), `{component}.spec.js` (E2E)
- Workflows: `{action}.workflow.js` (Playwright helpers)

### Formatting
- Prettier: 2 spaces, single quotes, trailing commas, 120 char width
- Destructure props and imports
- Early returns for validation
- Template literals over string concatenation

## Testing Instructions

### Unit Tests (Jest + React Testing Library)
- **Location**: `src/**/__tests__/*.test.jsx`
- **Dependencies**: Mock external services and APIs
- **Run**: `yarn test`
- **Coverage**: Maintain 80%+ coverage
- **Environment**: Uses test-specific mocks in `__mocks__/`

### E2E Tests (Playwright)
- **Location**: `__tests__/*.spec.js`
- **Dependencies**: Full browser automation with real interactions
- **Run**: `yarn test:e2e`
- **Screenshots**: Automatic screenshot comparison in `__screenshots__/`
- **Workflows**: Reusable test helpers in `workflows/` directories

### Test File Structure
```
{Component}.test.jsx        # Unit tests with RTL
{feature}.spec.js          # E2E tests with Playwright
{feature}.workflow.js      # Reusable E2E workflows
```

## Component Architecture

### Core Provider System
The Core component wraps the entire application and provides:
- Global error handling via Core.Error
- Event management via EventManager context
- Performance monitoring via PerformanceManager
- Notification system via Core.Notifications
- Theme and locale configuration

### Event-Driven Communication
```javascript
// Publishing events
Event.publish('booking:rateSelected', { rateId, price });

// Subscribing to events
useEffect(() => {
  const unsubscribe = Event.subscribe('booking:rateSelected', handleRateSelection);
  return unsubscribe;
}, []);
```

### CSS Module Patterns
```css
/* Component.module.css */
.container {
  /* Base styles */
}

.container--loading {
  /* Modifier styles using BEM-like naming */
}

.button {
  /* Component-specific button styles */
}
```

## Security Considerations

- **Input Sanitization**: All user inputs sanitized before API calls
- **XSS Prevention**: Use dangerouslySetInnerHTML sparingly with sanitization
- **API Security**: Never expose API keys in client code
- **Session Management**: Secure cookie handling for user sessions
- **HTTPS Only**: All external API calls over HTTPS
- **Content Security Policy**: Strict CSP headers in production

## Environment Configuration

### Required Environment Variables

```bash
NODE_ENV=development|production|test
REACT_APP_API_BASE_URL=https://api.example.com
```

### Optional Configuration

```bash
REACT_APP_PERFORMANCE_MONITORING=true   # Enable performance tracking
REACT_APP_DEBUG_EVENTS=true            # Log event communications
```

Never commit `.env` files to repository.

## Performance Guidelines

- **Bundle Size**: Keep individual components under 50KB
- **Lazy Loading**: Use React.lazy for route-level components
- **Memoization**: Implement React.memo for expensive renders
- **Event Cleanup**: Always unsubscribe from events in useEffect cleanup
- **Image Optimization**: Use appropriate formats and lazy loading
- **CSS**: Minimize unused styles, prefer CSS modules over global styles

## Debugging

### Common Issues

**Component Not Rendering:**
```bash
# Check event subscriptions
REACT_APP_DEBUG_EVENTS=true yarn start

# Verify CSS modules import
import styles from './Component.module.css';
```

**E2E Tests Failing:**
```bash
# Run with UI for debugging
yarn test:e2e --ui

# Generate new screenshots
yarn test:e2e --update-snapshots
```

**Build Issues:**
```bash
# Clear cache and reinstall
rm -rf node_modules yarn.lock
yarn install

# Check for circular dependencies
yarn build:npm --verbose
```

## Project Structure

```
src/
├── Core.jsx                    # Main provider component
├── Core.provider.jsx           # Context providers
├── Core.Error.jsx              # Error boundary
├── Core.Notifications.jsx      # Global notifications
├── components/                 # All React components
│   ├── __shared__/            # Shared utilities and components
│   ├── Booking/               # Booking flow components
│   ├── Checkout/              # Payment and confirmation
│   ├── Finder/                # Search and filtering
│   ├── Rates/                 # Rate display and selection
│   └── Session/               # User authentication
├── contexts/                  # React contexts
│   ├── EventManager/          # Event system
│   └── PerformanceManager/    # Performance monitoring
├── helpers/                   # Utility functions
└── services/                  # External API services

__tests__/                     # E2E test suites
├── workflows/                 # Reusable test workflows
├── __screenshots__/           # Visual regression tests
└── *.spec.js                 # Test specifications

public/                        # Static demo pages
├── e2e/                      # E2E test fixtures
└── routes/                   # Demo application routes
```

## Contributing

1. **ESLint Compliance**: All code must pass `yarn lint` with zero warnings
2. **Test Coverage**: Maintain 80%+ unit test coverage
3. **Visual Testing**: Update E2E screenshots when UI changes
4. **Performance**: Monitor bundle size impact
5. **Documentation**: Update component PropTypes and this AGENTS.md
6. **Conventional Commits**: Use semantic commit messages

### Pull Request Flow
```bash
# Before commit
yarn lint              # Must pass
yarn test              # Must pass
yarn pipeline          # Full validation

# PR title format
[core] Feature: Add new booking component
[core] Fix: Resolve checkout validation error
[core] Docs: Update component documentation
```

### Release Process
- Semantic versioning (semver)
- Automated builds on tag creation
- NPM package distribution
- Changelog generation from commits