# Shared Component Library

This directory contains reusable UI components, layouts, and templates that can be shared across multiple frontend applications in the IGNY8 platform.

## Overview

The shared component library provides:
- **Blocks**: Reusable content blocks (hero sections, feature grids, stats panels)
- **Layouts**: Page layout wrappers (default, minimal)
- **Templates**: Complete page templates (marketing, landing pages)

These components are designed to be framework-agnostic where possible, but currently implemented in React/TypeScript.

## Directory Structure

```
shared/
├── blocks/          # Content blocks (12 total)
│   ├── HeroBlock.tsx
│   ├── FeatureGridBlock.tsx
│   ├── StatsPanel.tsx
│   ├── ServicesBlock.tsx
│   ├── ProductsBlock.tsx
│   ├── TestimonialsBlock.tsx
│   ├── ContactFormBlock.tsx
│   ├── CTABlock.tsx
│   ├── ImageGalleryBlock.tsx
│   ├── VideoBlock.tsx
│   ├── TextBlock.tsx
│   ├── QuoteBlock.tsx
│   ├── blocks.css
│   └── index.ts
├── layouts/         # Page layouts (7 total)
│   ├── DefaultLayout.tsx
│   ├── MinimalLayout.tsx
│   ├── MagazineLayout.tsx
│   ├── EcommerceLayout.tsx
│   ├── PortfolioLayout.tsx
│   ├── BlogLayout.tsx
│   ├── CorporateLayout.tsx
│   ├── layouts.css
│   └── index.ts
├── templates/       # Full page templates (6 total)
│   ├── MarketingTemplate.tsx
│   ├── LandingTemplate.tsx
│   ├── BlogTemplate.tsx
│   ├── BusinessTemplate.tsx
│   ├── PortfolioTemplate.tsx
│   ├── EcommerceTemplate.tsx
│   └── index.ts
├── index.ts         # Barrel exports
└── README.md        # This file
```

## Usage

### In Site Builder (`site-builder/`)

The Site Builder application imports shared components via the `@shared` alias configured in `vite.config.ts`:

```typescript
import { HeroBlock, MarketingTemplate } from '@shared';
```

### In Main Frontend (`frontend/`)

Import directly from the shared directory:

```typescript
import { HeroBlock } from '@/components/shared/blocks';
import { DefaultLayout } from '@/components/shared/layouts';
```

## Components

### Blocks

#### `HeroBlock`
Hero section component for landing pages and marketing sites.

**Props:**
- `heading: string` - Main headline
- `subheading?: string` - Supporting text
- `ctaText?: string` - Call-to-action button text
- `ctaLink?: string` - Call-to-action link URL
- `imageUrl?: string` - Hero image URL
- `variant?: 'default' | 'centered' | 'split'` - Layout variant

**Example:**
```tsx
<HeroBlock
  heading="Build Your Site with AI"
  subheading="Create professional marketing sites in minutes"
  ctaText="Get Started"
  ctaLink="/signup"
/>
```

#### `FeatureGridBlock`
Grid layout for displaying features or benefits.

**Props:**
- `title?: string` - Section title
- `features: Array<{ title: string; description: string; icon?: ReactNode }>` - Feature items
- `columns?: 2 | 3 | 4` - Number of columns

**Example:**
```tsx
<FeatureGridBlock
  title="Key Features"
  features={[
    { title: 'AI-Powered', description: 'Generate content automatically' },
    { title: 'Fast Setup', description: 'Launch in minutes' },
  ]}
  columns={3}
/>
```

#### `StatsPanel`
Statistics display component.

**Props:**
- `stats: Array<{ label: string; value: string | number }>` - Statistics to display
- `variant?: 'default' | 'compact'` - Display variant

**Example:**
```tsx
<StatsPanel
  stats={[
    { label: 'Sites Created', value: '1,234' },
    { label: 'Active Users', value: '567' },
  ]}
/>
```

#### `ServicesBlock`
Display services or offerings in a grid layout.

**Props:**
- `title?: string` - Section title
- `subtitle?: string` - Section subtitle
- `services: Array<{ title: string; description: string; icon?: ReactNode; imageUrl?: string }>` - Service items
- `columns?: 2 | 3 | 4` - Number of columns
- `variant?: 'default' | 'card' | 'minimal'` - Display variant

#### `ProductsBlock`
Display products in a grid or list layout.

**Props:**
- `title?: string` - Section title
- `subtitle?: string` - Section subtitle
- `products: Array<{ name: string; description?: string; price?: string; imageUrl?: string; ctaLabel?: string }>` - Product items
- `columns?: 2 | 3 | 4` - Number of columns
- `variant?: 'grid' | 'list' | 'carousel'` - Display variant

#### `TestimonialsBlock`
Display customer testimonials with ratings and author info.

**Props:**
- `title?: string` - Section title
- `subtitle?: string` - Section subtitle
- `testimonials: Array<{ quote: string; author: string; role?: string; company?: string; avatarUrl?: string; rating?: number }>` - Testimonial items
- `columns?: 1 | 2 | 3` - Number of columns
- `variant?: 'default' | 'card' | 'minimal'` - Display variant

#### `ContactFormBlock`
Contact form with customizable fields.

**Props:**
- `title?: string` - Form title
- `subtitle?: string` - Form subtitle
- `fields?: Array<{ name: string; label: string; type: 'text' | 'email' | 'tel' | 'textarea'; required?: boolean; placeholder?: string }>` - Form fields
- `submitLabel?: string` - Submit button label
- `onSubmit?: (data: Record<string, string>) => void` - Submit handler

#### `CTABlock`
Call-to-action section with primary and secondary actions.

**Props:**
- `title: string` - CTA title
- `subtitle?: string` - CTA subtitle
- `primaryCtaLabel?: string` - Primary button label
- `primaryCtaLink?: string` - Primary button link
- `onPrimaryCtaClick?: () => void` - Primary button click handler
- `secondaryCtaLabel?: string` - Secondary button label
- `secondaryCtaLink?: string` - Secondary button link
- `onSecondaryCtaClick?: () => void` - Secondary button click handler
- `backgroundImage?: string` - Background image URL
- `variant?: 'default' | 'centered' | 'split'` - Layout variant

#### `ImageGalleryBlock`
Image gallery with grid, masonry, or carousel layout.

**Props:**
- `title?: string` - Gallery title
- `subtitle?: string` - Gallery subtitle
- `images: Array<{ url: string; alt?: string; caption?: string; thumbnailUrl?: string }>` - Image items
- `columns?: 2 | 3 | 4` - Number of columns
- `variant?: 'grid' | 'masonry' | 'carousel'` - Display variant
- `lightbox?: boolean` - Enable lightbox on click

#### `VideoBlock`
Video player component supporting both video URLs and embed codes.

**Props:**
- `title?: string` - Video title
- `subtitle?: string` - Video subtitle
- `videoUrl?: string` - Video file URL
- `embedCode?: string` - HTML embed code (e.g., YouTube iframe)
- `thumbnailUrl?: string` - Video thumbnail/poster
- `autoplay?: boolean` - Autoplay video
- `controls?: boolean` - Show video controls
- `loop?: boolean` - Loop video
- `muted?: boolean` - Mute video
- `variant?: 'default' | 'fullwidth' | 'centered'` - Layout variant

#### `TextBlock`
Simple text content block with customizable alignment and width.

**Props:**
- `title?: string` - Block title
- `content: string | ReactNode` - Text content (HTML string or React nodes)
- `align?: 'left' | 'center' | 'right' | 'justify'` - Text alignment
- `variant?: 'default' | 'narrow' | 'wide' | 'fullwidth'` - Width variant

#### `QuoteBlock`
Quote/testimonial block with author information.

**Props:**
- `quote: string` - Quote text
- `author?: string` - Author name
- `role?: string` - Author role
- `company?: string` - Author company
- `avatarUrl?: string` - Author avatar image
- `variant?: 'default' | 'large' | 'minimal' | 'card'` - Display variant
- `align?: 'left' | 'center' | 'right'` - Text alignment

### Layouts

#### `DefaultLayout`
Standard page layout with header, main content area, and footer.

**Props:**
- `children: ReactNode` - Page content
- `header?: ReactNode` - Custom header component
- `footer?: ReactNode` - Custom footer component
- `sidebar?: ReactNode` - Optional sidebar

**Example:**
```tsx
<DefaultLayout>
  <YourPageContent />
</DefaultLayout>
```

#### `MinimalLayout`
Minimal layout for focused content pages.

**Props:**
- `children: ReactNode` - Page content
- `background?: 'light' | 'dark'` - Background color

**Example:**
```tsx
<MinimalLayout background="light">
  <ArticleContent />
</MinimalLayout>
```

#### `MagazineLayout`
Magazine-style layout with featured section and sidebar.

**Props:**
- `header?: ReactNode` - Page header
- `featured?: ReactNode` - Featured content section
- `sidebar?: ReactNode` - Sidebar content
- `mainContent: ReactNode` - Main content area
- `footer?: ReactNode` - Page footer

#### `EcommerceLayout`
E-commerce layout with navigation and product sidebar.

**Props:**
- `header?: ReactNode` - Page header
- `navigation?: ReactNode` - Navigation menu
- `sidebar?: ReactNode` - Sidebar (filters, categories)
- `mainContent: ReactNode` - Main content (products)
- `footer?: ReactNode` - Page footer

#### `PortfolioLayout`
Portfolio layout optimized for showcasing work.

**Props:**
- `header?: ReactNode` - Page header
- `mainContent: ReactNode` - Main content (gallery, projects)
- `footer?: ReactNode` - Page footer
- `fullWidth?: boolean` - Full-width layout option

#### `BlogLayout`
Blog layout with optional sidebar (left or right).

**Props:**
- `header?: ReactNode` - Page header
- `sidebar?: ReactNode` - Sidebar content
- `mainContent: ReactNode` - Main content (blog posts)
- `footer?: ReactNode` - Page footer
- `sidebarPosition?: 'left' | 'right'` - Sidebar position

#### `CorporateLayout`
Corporate/business layout with navigation and structured sections.

**Props:**
- `header?: ReactNode` - Page header
- `navigation?: ReactNode` - Navigation menu
- `mainContent: ReactNode` - Main content
- `footer?: ReactNode` - Page footer
- `sidebar?: ReactNode` - Optional sidebar

### Templates

#### `MarketingTemplate`
Complete marketing page template with hero, features, and CTA sections.

**Props:**
- `hero: HeroBlockProps` - Hero section configuration
- `features?: FeatureGridBlockProps` - Features section
- `stats?: StatsPanelProps` - Statistics section
- `cta?: { text: string; link: string }` - Call-to-action

**Example:**
```tsx
<MarketingTemplate
  hero={{
    heading: "Welcome to IGNY8",
    subheading: "AI-powered content generation",
    ctaText: "Start Free Trial",
    ctaLink: "/signup"
  }}
  features={{
    features: [
      { title: 'AI Writer', description: 'Generate content automatically' },
      { title: 'Site Builder', description: 'Create sites in minutes' },
    ]
  }}
/>
```

#### `LandingTemplate`
Landing page template optimized for conversions.

**Props:**
- Similar to `MarketingTemplate` with additional conversion-focused sections

#### `BlogTemplate`
Blog page template with posts and sidebar.

**Props:**
- `header?: ReactNode` - Page header
- `sidebar?: ReactNode` - Sidebar content
- `posts: ReactNode` - Blog posts content
- `footer?: ReactNode` - Page footer
- `sidebarPosition?: 'left' | 'right'` - Sidebar position

#### `BusinessTemplate`
Business/corporate page template.

**Props:**
- `header?: ReactNode` - Page header
- `navigation?: ReactNode` - Navigation menu
- `hero?: ReactNode` - Hero section
- `features?: ReactNode` - Features section
- `services?: ReactNode` - Services section
- `testimonials?: ReactNode` - Testimonials section
- `cta?: ReactNode` - Call-to-action section
- `footer?: ReactNode` - Page footer

#### `PortfolioTemplate`
Portfolio showcase template.

**Props:**
- `header?: ReactNode` - Page header
- `gallery?: ReactNode` - Portfolio gallery
- `about?: ReactNode` - About section
- `contact?: ReactNode` - Contact section
- `footer?: ReactNode` - Page footer
- `fullWidth?: boolean` - Full-width layout

#### `EcommerceTemplate`
E-commerce store template.

**Props:**
- `header?: ReactNode` - Page header
- `navigation?: ReactNode` - Navigation menu
- `sidebar?: ReactNode` - Sidebar (filters)
- `products?: ReactNode` - Products grid
- `featured?: ReactNode` - Featured products
- `footer?: ReactNode` - Page footer

## Styling

Components use CSS modules and shared CSS files:
- `blocks/blocks.css` - Block component styles
- `layouts/layouts.css` - Layout component styles

Styles are scoped to prevent conflicts. When using in different applications, ensure CSS is imported:

```typescript
import '@shared/blocks/blocks.css';
import '@shared/layouts/layouts.css';
```

## TypeScript Types

All components are fully typed. Import types from the component files:

```typescript
import type { HeroBlockProps } from '@shared/blocks/HeroBlock';
```

## Best Practices

1. **Composition over Configuration**: Prefer composing blocks into templates rather than creating monolithic components.

2. **Props Validation**: All components validate required props. Use TypeScript for compile-time safety.

3. **Accessibility**: Components follow WCAG 2.1 AA guidelines. Include ARIA labels, proper heading hierarchy, and keyboard navigation support.

4. **Responsive Design**: All components are mobile-first and responsive. Use CSS Grid and Flexbox for layouts.

5. **Performance**: 
   - Use React.memo for expensive components
   - Lazy load templates when possible
   - Optimize images with lazy loading
   - Minimize re-renders with proper state management

6. **Type Safety**: All props are fully typed. Avoid `any` types. Use union types for variants.

7. **Error Handling**: Components should gracefully handle missing or invalid props.

8. **Documentation**: Include JSDoc comments for complex components and props.

## API Reference

### Blocks

All block components follow a consistent API pattern:
- Accept `className` for custom styling
- Support optional props with sensible defaults
- Return semantic HTML elements
- Use CSS classes from `blocks.css`

### Layouts

Layout components:
- Accept `children` as main content
- Support optional `header`, `footer`, `sidebar` props
- Use CSS Grid or Flexbox for structure
- Are fully responsive

### Templates

Template components:
- Compose multiple blocks and layouts
- Accept configuration objects for sections
- Support custom content injection
- Handle empty states gracefully

## Migration Guide

### From Phase 6 to Phase 7

If you're upgrading from Phase 6 components:

1. **New Props**: Some components now accept additional props for Phase 7 features
2. **Theme System**: Integrate with CMS Theme System for consistent styling
3. **Type Updates**: TypeScript interfaces may have new optional fields
4. **CSS Changes**: New CSS variables for theme customization

### Breaking Changes

None in Phase 7. All changes are backward compatible.

## Troubleshooting

### Components not rendering
- Ensure CSS files are imported: `import './blocks.css'`
- Check that props match TypeScript interfaces
- Verify React version compatibility (React 19+)

### Styling issues
- Check CSS class names match component structure
- Verify CSS variables are defined in theme
- Ensure Tailwind classes are available (if used)

### Type errors
- Update TypeScript to latest version
- Check prop types match component interfaces
- Verify all required props are provided

## Contributing

When adding new shared components:

1. Create the component in the appropriate directory (`blocks/`, `layouts/`, or `templates/`)
2. Export from the directory's `index.ts`
3. Add to the main `shared/index.ts` barrel export
4. Document props and usage in this README
5. Add TypeScript types
6. Include CSS in the appropriate stylesheet
7. Write tests (if applicable)

## Testing

Shared components include comprehensive test coverage using React Testing Library. Tests are located in `__tests__` directories within each component folder.

### Test Coverage

**Blocks:**
- ✅ `HeroBlock` - Tests for title, subtitle, CTA, and supporting content
- ✅ `FeatureGridBlock` - Tests for features rendering, columns, and icons
- ✅ `StatsPanel` - Tests for stats display and variants

**Layouts:**
- ✅ `DefaultLayout` - Tests for header, footer, sidebar, and children rendering

**Templates:**
- ✅ `MarketingTemplate` - Tests for hero, sections, and sidebar rendering

### Running Tests

Tests use `@testing-library/react` and follow the existing test patterns in the codebase:

```bash
# Run all tests (when test script is configured)
npm test

# Run tests for shared components specifically
npm test -- shared
```

### Writing New Tests

When adding new components, include tests covering:
- Basic rendering
- Props validation
- Conditional rendering
- User interactions (clicks, form submissions)
- Edge cases (empty arrays, null values)

Example test structure:
```typescript
import { render, screen, fireEvent } from '@testing-library/react';
import { YourComponent } from '../YourComponent';

describe('YourComponent', () => {
  it('renders correctly', () => {
    render(<YourComponent prop="value" />);
    expect(screen.getByText('Expected Text')).toBeInTheDocument();
  });
});
```

## CMS Theme System Integration

The shared components work seamlessly with the CMS Theme System (`frontend/src/styles/cms/`):

### Style Presets
Apply predefined style presets:
```typescript
import { applyPreset } from '@/styles/cms/presets';

const preset = applyPreset('modern');
// Use preset colors, typography, and spacing
```

### Color Schemes
Use color schemes for consistent theming:
```typescript
import { getColorScheme, generateCSSVariables } from '@/styles/cms/colors';

const scheme = getColorScheme('blue');
const cssVars = generateCSSVariables(scheme);
```

### Typography
Apply typography presets:
```typescript
import { getTypographyPreset, generateTypographyCSS } from '@/styles/cms/typography';

const typography = getTypographyPreset('modern');
const css = generateTypographyCSS(config, typography);
```

### Component Styles
Customize component styles:
```typescript
import { applyComponentStyles, generateComponentCSS } from '@/styles/cms/components';

const customStyles = applyComponentStyles({
  button: { primary: { background: '#custom-color' } }
});
const css = generateComponentCSS(customStyles);
```

## Phase 7 Enhancements

### New Site Management Components

The following components were added in Phase 7 for advanced site management:

**Layout & Template System:**
- `LayoutSelector` - Browse and select page layouts
- `TemplateLibrary` - Search and filter page templates
- `LayoutPreview` - Preview layouts with sample content
- `TemplateCustomizer` - Customize template settings and styles
- `StyleEditor` - Edit CSS, colors, typography, and spacing

**Site Management:**
- `SitePreview` - Live iframe preview of deployed sites
- Enhanced `SiteSettings` - SEO, Open Graph, and Schema.org configuration
- Enhanced `PageManager` - Drag-drop reorder and bulk actions
- Enhanced `PostEditor` - Full-featured editing with tabs
- `SiteContentManager` - Advanced content management with search and filters

### Integration with Site Builder

Shared components are used in the Site Builder preview canvas:
- `HeroBlock` for hero sections
- `FeatureGridBlock` for feature displays
- `StatsPanel` for statistics
- `MarketingTemplate` for complete page templates

## Future Enhancements

- [x] Design tokens/theming system (Phase 7 - Completed)
- [x] Component tests (Phase 7 - Completed)
- [ ] Storybook integration for component documentation
- [ ] Animation utilities
- [ ] Form components library
- [ ] Icon library integration
- [ ] Accessibility audit and improvements
- [ ] Performance optimization (lazy loading, code splitting)

