# App Directory - Next.js 14 App Router

This directory contains the Next.js 14 App Router application structure with language-prefixed routes and API endpoints.

## Quick Reference

- **Parent**: [../.claude.md](../.claude.md)
- **Root Project**: [../../CLAUDE.md](../../CLAUDE.md)
- **Comprehensive Analysis**: See [../../COMPREHENSIVE_CODEBASE_ANALYSIS.md](../../COMPREHENSIVE_CODEBASE_ANALYSIS.md) Section 1.1 & 1.2

## Directory Structure

```
app/
├── layout.tsx                    # Root layout (fonts, providers)
├── [lang]/                       # Language-prefixed routes
│   ├── page.tsx                  # Home page
│   ├── layout.tsx                # Language layout
│   ├── pricing/                  # Pricing page
│   ├── dashboard/                # Protected dashboard
│   ├── signup/                   # Multi-step signup
│   ├── login/                    # Login with OTP
│   ├── blog/                     # Blog with pagination
│   ├── demo/                     # Demo scheduler
│   ├── [location]/[service]/     # Dynamic service pages
│   ├── industries/               # Industry pages
│   ├── features/                 # Feature pages
│   └── resources/                # Resources library
└── api/                          # API routes
    ├── auth/                     # Authentication
    ├── signup/                   # Signup workflow
    ├── stripe/                   # Stripe integration
    ├── subscriptions/            # Subscription management
    ├── dashboard/                # Dashboard APIs
    └── health/                   # Health check
```

## Key Statistics

- **60+ page routes** (Arabic + English)
- **32 API routes** with validation
- **Multiple layout levels** (root → lang → feature)
- **Dynamic routes**: Service × Location combinations

## Route Types

### Static Routes

Pages that are pre-rendered:

- Homepage (`/ar`, `/en`)
- About, Contact, Resources
- Industry pages
- Blog posts (with ISR)

### Dynamic Routes

Generated at build time:

- **`[location]/[service]`**: Service pages for each GCC city
- Examples: `/ar/dubai/dental-clinic`, `/en/riyadh/beauty-salon`

### Server-Rendered Routes

Fresh on every request:

- Dashboard (requires auth)
- User-specific pages

## Layouts

### Root Layout (`layout.tsx`)

- Loads fonts (Google Fonts)
- Sets up providers
- Configures metadata
- Wraps entire app

### Language Layout (`[lang]/layout.tsx`)

- Validates language parameter
- Sets HTML direction (RTL/LTR)
- Provides language context
- Wraps all language-specific pages

### Feature Layouts

- Dashboard layout (auth wrapper)
- Signup layout (stepper UI)
- Blog layout (sidebar, pagination)

## Page Components

### Server Components (Default)

Most pages are server components:

```typescript
// app/[lang]/page.tsx
export default async function HomePage({ params }: { params: { lang: 'ar' | 'en' } }) {
  const data = await fetchData();  // Direct data fetching
  return <UI data={data} />;
}
```

Benefits:

- No client-side JavaScript
- SEO-friendly
- Fast initial load
- Direct database access

### Client Components

Pages with interactivity:

```typescript
'use client'

export default function InteractivePage() {
  const [state, setState] = useState();
  return <InteractiveUI />;
}
```

Used for:

- Forms (signup, login)
- Interactive demos
- Client-side state management

## API Routes

Located in `app/api/`:

### Authentication (`api/auth/`)

- **POST /api/auth/login** - Initiate login with credentials
- **POST /api/auth/verify-login-otp** - Verify OTP and create session
- **POST /api/auth/forgot-password** - Password reset request
- **POST /api/auth/verify-reset-otp** - Verify password reset OTP

### Signup (`api/signup/`)

- **POST /api/signup** - Create account
- **POST /api/signup/verify** - Verify OTP
- **POST /api/signup/complete** - Complete profile

### Stripe (`api/stripe/`)

- **POST /api/stripe/create-checkout-session** - Create payment session
- **POST /api/stripe/webhook** - Handle Stripe webhooks
- **GET /api/stripe/subscription** - Get subscription status

### Dashboard (`api/dashboard/`)

- **GET /api/dashboard/stats** - Get dashboard statistics
- **GET /api/dashboard/appointments** - List appointments
- **POST /api/dashboard/appointments** - Create appointment

### Utility

- **GET /api/health** - Health check endpoint

## API Route Pattern

Standard structure for API routes:

```typescript
// app/api/your-endpoint/route.ts
import { NextRequest, NextResponse } from "next/server";
import { rateLimiter } from "@/lib/rate-limiter";
import { withCSRF } from "@/lib/csrf";
import { validateInput } from "@/lib/input-validation";
import { prisma } from "@/lib/db";

export async function POST(request: NextRequest) {
  // 1. Rate limiting
  await rateLimiter.check(request);

  // 2. CSRF protection (for state-changing operations)
  await withCSRF(request);

  // 3. Parse and validate input
  const body = await request.json();
  const validated = validateInput(body);

  // 4. Business logic
  const result = await prisma.model.create({ data: validated });

  // 5. Return response
  return NextResponse.json(result);
}
```

## Common Page Patterns

### Static Page with ISR

```typescript
// 1-hour revalidation
export const revalidate = 3600;

export default async function Page() {
  const data = await fetchStaticData();
  return <Content data={data} />;
}
```

### Dynamic Route with SSG

```typescript
export async function generateStaticParams() {
  const services = await getServices();
  const locations = await getLocations();

  return services.flatMap(service =>
    locations.map(location => ({
      service: service.slug,
      location: location.slug
    }))
  );
}

export default async function ServicePage({ params }: { params: { service: string; location: string } }) {
  const data = await getServiceData(params);
  return <ServiceUI data={data} />;
}
```

### Protected Page with Auth

```typescript
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { redirect } from 'next/navigation';

export default async function ProtectedPage() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect('/ar/login');
  }

  return <ProtectedContent user={session.user} />;
}
```

## Data Fetching Strategies

### Server Component Pattern (Preferred)

```typescript
async function Page() {
  const data = await prisma.model.findMany();
  return <Component data={data} />;
}
```

### API Route + Client Component

```typescript
'use client'
function ClientPage() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(setData);
  }, []);

  return <Component data={data} />;
}
```

### Server Action (Mutations)

```typescript
async function updateProfile(formData: FormData) {
  "use server";

  const data = {
    name: formData.get("name"),
    email: formData.get("email"),
  };

  await prisma.user.update({ where: { id }, data });
  revalidatePath("/dashboard");
}
```

## Metadata & SEO

Every page should export metadata:

```typescript
import type { Metadata } from 'next';

export const metadata: Metadata = {
  title: 'Page Title - Mawidi',
  description: 'Page description for SEO',
  openGraph: {
    title: 'OG Title',
    description: 'OG Description',
    images: ['/og-image.jpg']
  }
};

export default function Page() {
  return <Content />;
}
```

## Internationalization

All pages under `[lang]/` receive the language parameter:

```typescript
type Params = { params: { lang: 'ar' | 'en' } };

export default function Page({ params }: Params) {
  const UI = getUI(params.lang);  // Get translations
  const dir = params.lang === 'ar' ? 'rtl' : 'ltr';

  return (
    <div dir={dir}>
      <h1>{UI.t.title}</h1>
    </div>
  );
}
```

## Error Handling

### Error Boundary

```typescript
// app/[lang]/error.tsx
'use client'

export default function Error({
  error,
  reset
}: {
  error: Error;
  reset: () => void;
}) {
  return (
    <div>
      <h2>Something went wrong!</h2>
      <button onClick={reset}>Try again</button>
    </div>
  );
}
```

### Not Found

```typescript
// app/[lang]/not-found.tsx
export default function NotFound() {
  return (
    <div>
      <h2>404 - Page Not Found</h2>
      <Link href="/ar">Go Home</Link>
    </div>
  );
}
```

## Loading States

```typescript
// app/[lang]/loading.tsx
export default function Loading() {
  return <Skeleton />;
}
```

## Common Tasks

### Add a New Page

1. Create `app/[lang]/your-page/page.tsx`
2. Add metadata for SEO
3. Fetch data (if needed)
4. Add translations
5. Update navigation

### Add an API Route

1. Create `app/api/your-route/route.ts`
2. Export HTTP method functions (`GET`, `POST`, etc.)
3. Add rate limiting
4. Add input validation
5. Add CSRF protection (for mutations)
6. Return NextResponse

### Add Middleware Logic

Edit `middleware.ts` (in root, not in app/)

## Testing

### Page Tests

```bash
# E2E tests for pages
npm run test:e2e -- --grep "page-name"
```

### API Tests

```bash
# API integration tests
npm run test:e2e -- --grep "api"
```

## Security

### Authentication

- All dashboard routes require auth
- Session validation via NextAuth
- JWT tokens with 2-hour expiry

### API Security

- Rate limiting on all endpoints
- CSRF protection on mutations
- Input validation (Zod)
- SQL injection prevention (Prisma)

### CORS

Configured in `middleware.ts`

## Performance

### Page Load

- ISR for static content (1-hour cache)
- Server components reduce bundle size
- Image optimization with `next/image`
- Font optimization with `next/font`

### API Performance

- Database query optimization
- Response caching where appropriate
- Efficient data serialization

## Debugging

### Server Components

```typescript
// Add console.log (visible in terminal)
console.log("Server component data:", data);
```

### Client Components

```typescript
// Add console.log (visible in browser)
console.log("Client component state:", state);
```

### API Routes

```typescript
// Log requests
console.log("API request:", await request.json());
```

## Critical Reminders

- ⚠️ **Default to Server Components** - Use 'use client' only when necessary
- ⚠️ **Port 9000** - Test on http://localhost:9000
- ⚠️ **Language Prefix** - All pages under `/[lang]/`
- ⚠️ **Metadata** - Always export metadata for SEO
- ⚠️ **Rate Limiting** - Apply to all API routes
- ⚠️ **CSRF** - Protect all state-changing operations
- ⚠️ **Validation** - Validate all inputs server-side

## Documentation

- **Comprehensive**: [../../COMPREHENSIVE_CODEBASE_ANALYSIS.md](../../COMPREHENSIVE_CODEBASE_ANALYSIS.md) Section 1.1 & 1.2
- **Quick Reference**: [../../QUICK_REFERENCE.md](../../QUICK_REFERENCE.md)
- **Components**: [../components/.claude.md](../components/.claude.md)
- **Utilities**: [../lib/.claude.md](../lib/.claude.md)
