# Components Directory - React Component Library

This directory contains 80+ React components used throughout the Mawidi application.

## 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.3

## Component Inventory

### Total: 80+ Components

- **Server Components**: 60+ (default)
- **Client Components**: 20+ (interactive)
- **Shared Components**: 15+ (used everywhere)

## Directory Structure

```
components/
├── Nav.tsx                        # Main navigation
├── Footer.tsx                     # Site footer
├── Hero.tsx                       # Homepage hero
├── LangSwitcher.tsx               # Language toggle
├── CookieConsent.tsx              # Cookie banner
├── FeatureShowcase.tsx            # Feature displays
├── SectorsShowcase.tsx            # Industry sectors
├── AIAgentsShowcase.tsx           # AI capabilities
├── DemoScheduler/                 # Complex booking component
│   ├── DemoScheduler.tsx          # Main component
│   ├── components/                # 15+ sub-components
│   ├── hooks/                     # Custom hooks (3)
│   ├── utils/                     # Utilities
│   ├── types/                     # TypeScript types
│   └── config/                    # Configuration
├── signup/                        # Signup flow components
│   ├── PackageSelection.tsx       # Package selector
│   └── [other signup components]
├── contact/                       # Contact forms
├── messages/                      # Messaging UI
├── blog/                          # Blog components
│   ├── PostList.tsx               # Post listing
│   └── Pagination.tsx             # Pagination
└── [50+ other components]
```

## Component Categories

### 1. Layout Components

Provide page structure:

- `Nav.tsx` - Main navigation with dropdowns
- `Footer.tsx` - Site footer with links
- `Hero.tsx` - Hero sections

### 2. Navigation Components

Handle routing and language:

- `LangSwitcher.tsx` - Language toggle (AR/EN)
- `Breadcrumbs.tsx` - Breadcrumb navigation
- Mobile menu components

### 3. Feature Components

Display features and capabilities:

- `FeatureShowcase.tsx` - Feature grid/carousel
- `SectorsShowcase.tsx` - Industry verticals
- `AIAgentsShowcase.tsx` - AI capabilities

### 4. Form Components

Handle user input:

- Signup components (`signup/`)
- Contact forms (`contact/`)
- Login forms
- Search components

### 5. Content Components

Display content:

- Blog components (`blog/`)
- Resource cards
- Testimonials
- Pricing cards

### 6. Interactive Components

Client-side interactivity:

- `DemoScheduler/` - Complex booking widget
- `CookieConsent.tsx` - Cookie banner
- Modals and dialogs
- Interactive demos

## Component Patterns

### Server Component (Default)

```typescript
// components/ServerComponent.tsx
export default function ServerComponent({ data }: Props) {
  return <UI>{data}</UI>;
}
```

Benefits:

- No client-side JavaScript
- Direct data fetching
- SEO-friendly
- Fast initial load

### Client Component

```typescript
// components/ClientComponent.tsx
'use client'

import { useState } from 'react';

export default function ClientComponent() {
  const [state, setState] = useState();

  return <InteractiveUI onChange={setState} />;
}
```

Use when:

- Need useState, useEffect, or other hooks
- Event handlers (onClick, onChange)
- Browser APIs (localStorage, window)
- Third-party client libraries

### Shared Component Pattern

Components used by both server and client:

```typescript
// components/SharedComponent.tsx
// No 'use client' directive

interface Props {
  // Props from both server and client contexts
}

export default function SharedComponent(props: Props) {
  // Pure presentational logic
  return <UI {...props} />;
}
```

### Composite Component Pattern

Complex components with sub-components:

```typescript
// components/ComplexComponent/index.tsx
export { default as ComplexComponent } from './ComplexComponent';
export * from './components';  // Export sub-components

// components/ComplexComponent/ComplexComponent.tsx
import { SubComponentA } from './components/SubComponentA';
import { SubComponentB } from './components/SubComponentB';

export default function ComplexComponent() {
  return (
    <div>
      <SubComponentA />
      <SubComponentB />
    </div>
  );
}
```

## Key Components

### Nav.tsx

Main navigation with:

- Dropdown menus
- Language switcher
- Mobile responsive
- Active link highlighting
- Translation support

### DemoScheduler/

Complex booking component:

- Date/time selection
- Timezone handling
- Form validation
- Multi-step flow
- OTP verification

**See**: [DemoScheduler/.claude.md](./DemoScheduler/.claude.md) (if it exists)

### LangSwitcher.tsx

Language toggle:

- Arabic ↔ English
- Preserves current route
- Updates URL with language prefix
- Client component (uses router)

### Blog Components

Blog post display:

- `PostList.tsx` - Grid/list of posts
- `Pagination.tsx` - Page navigation
- Post cards with metadata

## Styling Approach

### Tailwind CSS

All components use Tailwind utility classes:

```typescript
<div className="flex items-center justify-between p-4 bg-brand-green text-white">
  <h1 className="text-2xl font-bold">Title</h1>
</div>
```

### RTL/LTR Support

Use directional classes:

```typescript
<div className="rtl:text-right ltr:text-left">
  <span className="rtl:mr-4 ltr:ml-4">Content</span>
</div>
```

### Brand Colors

- `brand-green`: #10B981 (primary CTA)
- `brand-ink`: #1E293B (dark text)
- `brand-sand`: #F5F5F5 (light accents)

### Responsive Design

Mobile-first with breakpoints:

```typescript
<div className="flex flex-col md:flex-row lg:gap-8">
  {/* Stacks on mobile, horizontal on tablet+ */}
</div>
```

## Internationalization

Components receive translations via props or context:

```typescript
import { UI } from '@/lib/config';

interface Props {
  lang: 'ar' | 'en';
}

export default function Component({ lang }: Props) {
  const t = UI[lang].t;  // Get translations

  return (
    <div dir={lang === 'ar' ? 'rtl' : 'ltr'}>
      <h1>{t.title}</h1>
      <p>{t.description}</p>
    </div>
  );
}
```

## TypeScript Patterns

### Component Props

Always define explicit props:

```typescript
interface ComponentProps {
  title: string;
  description?: string;  // Optional
  items: Array<Item>;
  onAction: (id: string) => void;
  children?: React.ReactNode;
}

export default function Component({
  title,
  description,
  items,
  onAction,
  children
}: ComponentProps) {
  return <UI />;
}
```

### Generic Components

```typescript
interface ListProps<T> {
  items: T[];
  render: (item: T) => React.ReactNode;
}

export default function List<T>({ items, render }: ListProps<T>) {
  return <ul>{items.map(render)}</ul>;
}
```

## Common Patterns

### Conditional Rendering

```typescript
{condition && <Component />}
{condition ? <ComponentA /> : <ComponentB />}
```

### List Rendering

```typescript
{items.map(item => (
  <Item key={item.id} {...item} />
))}
```

### Loading States

```typescript
if (loading) return <Skeleton />;
if (error) return <ErrorMessage error={error} />;
return <Content data={data} />;
```

### Error Boundaries

Wrap components with error boundaries:

```typescript
<ErrorBoundary fallback={<ErrorUI />}>
  <Component />
</ErrorBoundary>
```

## Testing

### Component Tests

```bash
# Test specific component
npm run test:unit -- components/ComponentName

# Test all components
npm run test:unit -- components/
```

### Test Pattern

```typescript
import { render, screen } from '@testing-library/react';
import Component from './Component';

describe('Component', () => {
  it('renders correctly', () => {
    render(<Component title="Test" />);
    expect(screen.getByText('Test')).toBeInTheDocument();
  });

  it('handles interaction', () => {
    const onAction = jest.fn();
    render(<Component onAction={onAction} />);
    // Simulate interaction
    expect(onAction).toHaveBeenCalled();
  });
});
```

## Performance

### Memoization

Use React.memo for expensive components:

```typescript
import { memo } from 'react';

const ExpensiveComponent = memo(function ExpensiveComponent(props) {
  // Expensive rendering logic
  return <UI />;
});
```

### Dynamic Imports

Lazy load heavy components:

```typescript
import dynamic from 'next/dynamic';

const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
  loading: () => <Skeleton />,
  ssr: false  // Disable SSR if needed
});
```

### Image Optimization

Always use next/image:

```typescript
import Image from 'next/image';

<Image
  src="/path/to/image.jpg"
  alt="Description"
  width={800}
  height={600}
  priority  // For above-fold images
/>
```

## Common Tasks

### Create a New Component

1. Create file in `components/ComponentName.tsx`
2. Define props interface
3. Implement component
4. Export from `components/index.ts` (if needed)
5. Add tests in `__tests__/components/`

### Add Client Interactivity

1. Add `'use client'` directive at top
2. Import React hooks
3. Add state and effects
4. Handle events

### Add Translations

1. Pass `lang` prop
2. Get translations: `UI[lang].t`
3. Use in JSX
4. Support RTL/LTR

### Make Component Reusable

1. Extract hardcoded values to props
2. Add generic props (children, className)
3. Document prop types
4. Add examples/storybook (if applicable)

## Accessibility

### Semantic HTML

```typescript
<nav>
  <ul>
    <li><a href="/link">Link</a></li>
  </ul>
</nav>
```

### ARIA Labels

```typescript
<button aria-label="Close menu">
  <Icon />
</button>

<input aria-describedby="help-text" />
<span id="help-text">Helper text</span>
```

### Keyboard Navigation

```typescript
<button
  onKeyDown={(e) => {
    if (e.key === 'Enter' || e.key === ' ') {
      handleAction();
    }
  }}
>
  Action
</button>
```

## Critical Reminders

- ⚠️ **Server Components First** - Default to server components
- ⚠️ **'use client' Only When Needed** - For interactivity only
- ⚠️ **RTL/LTR Support** - Use directional Tailwind classes
- ⚠️ **TypeScript Props** - Always define explicit interfaces
- ⚠️ **Translations** - All text from translation files
- ⚠️ **Accessibility** - Semantic HTML + ARIA labels
- ⚠️ **next/image** - Use for all images
- ⚠️ **Performance** - Memoize expensive components

## Documentation

- **Comprehensive**: [../../COMPREHENSIVE_CODEBASE_ANALYSIS.md](../../COMPREHENSIVE_CODEBASE_ANALYSIS.md) Section 1.3
- **Quick Reference**: [../../QUICK_REFERENCE.md](../../QUICK_REFERENCE.md)
- **App Router**: [../app/.claude.md](../app/.claude.md)
- **Utilities**: [../lib/.claude.md](../lib/.claude.md)
