# Cultivate UI Library - Implementation Plan & Architecture

## 1. Library Overview

The Cultivate UI Library is a complete, production-ready React component library specifically designed for fintech investor forms. It provides a regulation-agnostic core that supports multiple securities regulations (RegA+, RegD, RegCF) through configuration-driven architecture.

### 1.1 Current Implementation Status

✅ **Completed Features:**
- Complete 12-step investor form wizard
- Multi-investor type support (Individual, Joint, Company, Trust, IRA)
- Regulation-specific configurations (RegA+, RegD, RegCF)
- Production-ready UI components based on shadcn/ui
- TypeScript-first with comprehensive type safety
- Form persistence with localStorage
- Custom step handlers for API integration
- Comprehensive validation with Zod schemas
- Mobile-responsive design

### 1.2 Architecture Principles

- **Configuration-Driven**: Differences between regulations handled through configuration objects
- **Zero-Configuration Default**: Works out of the box with sensible defaults
- **API-Agnostic**: Library provides hooks interface, consumers provide API implementation
- **Type-Safe**: Full TypeScript support with strict typing throughout
- **Accessible**: WCAG 2.1 AA compliance built-in
- **Performance-Optimized**: Efficient rendering and data management

---

## 2. Core API & Consumer Usage

### 2.1 Basic Usage Pattern

```tsx
import {
  createDefaultSteps,
  InvestorFormData,
  InvestorFormWizard,
} from "@rajkrajpj/cultivate-ui-library"

// Zero configuration - complete investor form in ~25 lines
const BasicInvestorForm = () => {
  const offeringParams = {
    offeringId: "offering-123",
    companyName: "My Company",
    sharePrice: 10,
    minInvestment: 100,
    maxInvestment: 10000,
    deadline: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
    regulation: "regA",
  }

  const steps = createDefaultSteps({
    regulation: offeringParams.regulation,
  })

  const handleComplete = async (formData: Partial<InvestorFormData>) => {
    await fetch("/api/investments", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(formData),
    })
  }

  return (
    <InvestorFormWizard<InvestorFormData>
      steps={steps}
      regulation={offeringParams.regulation}
      offeringParams={offeringParams}
      onComplete={handleComplete}
    />
  )
}
```

### 2.2 Advanced Usage with Custom Step Handlers

```tsx
import { StepHandlers } from "@rajkrajpj/cultivate-ui-library"

const stepHandlers: StepHandlers = {
  onGetStartedSubmit: async (data) => {
    // Save lead information immediately
    await fetch("/api/leads", {
      method: "POST",
      body: JSON.stringify({
        email: data.email,
        firstName: data.firstName,
        lastName: data.lastName,
      }),
    })
  },
  onInvestmentAmountSubmit: async (data) => {
    // Validate investment against offering limits
    await fetch("/api/validate-investment", {
      method: "POST",
      body: JSON.stringify({
        amount: data.investmentAmount,
        investorType: data.investorType,
      }),
    })
  },
  onIdentityInfoSubmit: async (data) => {
    // Submit KYC/AML verification
    await fetch("/api/kyc-verification", {
      method: "POST",
      body: JSON.stringify({
        ssn: data.ssn,
        birthDate: data.birthDate,
        address: {
          address1: data.address1,
          city: data.city,
          state: data.state,
          zip: data.zip,
        },
      }),
    })
  },
  onPaymentsSubmit: async (data) => {
    // Process final investment
    await fetch("/api/investments/submit", {
      method: "POST",
      body: JSON.stringify(data),
    })
  },
}

const steps = createDefaultSteps({
  regulation: "regCF",
  enableDebugLogs: process.env.NODE_ENV === "development",
  stepHandlers,
  customSuccessHandler: () => {
    window.location.href = "/investment-success"
  },
})
```

---

## 3. Component Architecture

### 3.1 Core Components

#### **InvestorFormWizard**
Main orchestrator component that manages the multi-step form flow.

```tsx
interface InvestorFormWizardProps<T> {
  steps: StepConfig<T>[]                          // Step configurations
  regulation: string                              // "regA" | "regD" | "regCF" | "custom"
  theme?: any                                     // Theme configuration
  offeringParams?: OfferingParams                 // Offering-specific parameters
  onStepChange?: (step: number, data: Partial<T>) => void
  onComplete?: (data: Partial<T>) => Promise<void>
  onError?: (error: Error, step: string) => void
  persistenceKey?: string                         // LocalStorage key for persistence
  initialData?: Partial<T>                        // Pre-populate form data
  className?: string                              // Custom CSS classes
}
```

#### **Page Components**
Pre-built step components that handle specific form sections:

- `GetStarted` - Email, name collection, optional agreement (RegCF)
- `SelectInvestorType` - Individual, Joint, Company, Trust/IRA selection
- `PersonalInfo` - Personal details based on investor type
- `AddressInfo` - Address information collection
- `InvestmentAmount` - Investment amount with validation
- `PaymentSelection` - Payment method selection

### 3.2 UI Component Library

The library includes a complete set of UI components based on shadcn/ui patterns:

```tsx
// Available UI components
import { 
  Button, 
  Card, 
  Checkbox, 
  Dialog, 
  Input, 
  Label, 
  Select, 
  Tabs 
} from "@rajkrajpj/cultivate-ui-library"
```

**Key Features:**
- Radix UI primitives for accessibility
- CVA (Class Variance Authority) for variant management
- Tailwind CSS for styling
- forwardRef pattern for all form components
- Consistent design tokens

---

## 4. Data Management & State

### 4.1 Form Data Structure

The library uses a comprehensive `InvestorFormData` interface that handles all investor types:

```tsx
interface InvestorFormData {
  // Basic Information
  email: string
  firstName: string
  lastName: string
  investorType: "individual" | "joint" | "company" | "trust" | "ira"

  // Investment Data
  investmentAmount: number
  totalShares: number
  isAccredited: boolean

  // Identity Information
  birthDate: string
  ssn: string
  tin?: string

  // Address Information
  address1: string
  city: string
  state: string
  zip: string
  country: string

  // Conditional Fields Based on Investor Type
  // Joint Account Fields
  joint_firstName?: string
  joint_lastName?: string
  joint_birthDate?: string
  joint_ssn?: string

  // Company Fields
  company_name?: string
  company_title?: string
  company_entityType?: string
  company_stateOfFormation?: string

  // Trust Fields
  trust_name?: string
  trust_title?: string
  trust_dateOfFormation?: string
  trust_stateOfFormation?: string

  // IRA Fields
  ira_accountType?: string
  ira_custodianName?: string
  ira_accountNumber?: string

  // Payment Information
  paymentMethod?: string
  paymentUrl?: string

  // Additional Fields
  phone?: string
  isUSCitizen?: boolean
}
```

### 4.2 State Management Strategy

- **React Hook Form**: Primary form state management with Zod validation
- **Step-Level State**: Each step maintains its own form state
- **Cross-Step Persistence**: Automatic localStorage persistence with debounced saving
- **Data Merging**: Sophisticated merging logic via `mergeInvestorFormData` utility

### 4.3 Validation Architecture

- **Zod-Based Schemas**: Type-safe validation with custom refinements
- **Step-Level Validation**: Each step has its own validation schema
- **Regulation-Specific Rules**: Conditional validation based on regulation type
- **Real-Time Validation**: Immediate feedback on form interactions

---

## 5. Regulation Support

### 5.1 Supported Regulations

#### **Regulation A+ (RegA)**
```tsx
const steps = createDefaultSteps({
  regulation: "regA",
  // Features:
  // - Supports both accredited and unaccredited investors
  // - Investment limits for unaccredited investors
  // - No agreement checkbox requirement
})
```

#### **Regulation Crowdfunding (RegCF)**
```tsx
const steps = createDefaultSteps({
  regulation: "regCF",
  // Features:
  // - Shows agreement checkbox on first step for guest flows
  // - Annual investment limits based on income/net worth
  // - Simplified KYC requirements
})
```

#### **Regulation D (RegD)**
```tsx
const steps = createDefaultSteps({
  regulation: "regD",
  // Features:
  // - Requires accreditation verification
  // - No investment limits for accredited investors
  // - Enhanced KYC requirements
})
```

### 5.2 Regulation-Specific Features

**Conditional Field Rendering:**
- Agreement checkbox for RegCF guest flows
- Enhanced accreditation verification for RegD
- Investment limit calculations for RegA+/RegCF

**Step Flow Variations:**
- RegD may skip unaccredited investor steps
- RegCF includes additional disclosure steps
- Custom steps can be added per regulation

---

## 6. API Integration Architecture

### 6.1 Step Handler Pattern

The library uses a step handler pattern that allows consumers to inject custom API calls at specific points in the form flow:

```tsx
interface StepHandlers {
  onGetStartedSubmit?: (data: InvestorFormData) => Promise<void>
  onInvestorTypeSubmit?: (data: InvestorFormData) => Promise<void>
  onPersonalInfoSubmit?: (data: InvestorFormData) => Promise<void>
  onAddressInfoSubmit?: (data: InvestorFormData) => Promise<void>
  onIdentityInfoSubmit?: (data: InvestorFormData) => Promise<void>
  onInvestmentAmountSubmit?: (data: InvestorFormData) => Promise<void>
  onSelfAccreditationSubmit?: (data: InvestorFormData) => Promise<void>
  onUnaccreditedInvestorSubmit?: (data: InvestorFormData) => Promise<void>
  onAcknowledgementSubmit?: (data: InvestorFormData) => Promise<void>
  onPaymentSelectionSubmit?: (data: InvestorFormData) => Promise<void>
  onPaymentsSubmit?: (data: InvestorFormData) => Promise<void>
}
```

### 6.2 API-Agnostic Design

The library doesn't make any API calls directly. Instead, it provides:

1. **Hook Points**: Clear points where consumers can inject API calls
2. **Data Contracts**: Well-defined data structures for API integration
3. **Error Handling**: Consistent error handling patterns
4. **Loading States**: Built-in loading state management

---

## 7. Default Form Flow

### 7.1 12-Step Default Flow

The `createDefaultSteps` function creates a comprehensive 12-step investor form:

1. **Get Started** - Email, name collection, optional agreement
2. **Select Investor Type** - Individual, Joint, Company, Trust/IRA
3. **Personal Information** - Personal details based on investor type
4. **Address Information** - Address fields with validation
5. **Identity Information** - SSN, DOB, identity verification
6. **Investment Amount** - Investment amount selection with calculations
7. **Self Accreditation** - Accreditation verification (if required)
8. **Unaccredited Investor** - Income/net worth disclosure (conditional)
9. **Acknowledgement** - Agreements and certifications
10. **Payment Selection** - Payment method selection
11. **Payments** - Payment processing and external URL generation
12. **Success Investment** - Success confirmation page

### 7.2 Step Configuration Options

```tsx
interface CreateDefaultStepsOptions {
  regulation: "regA" | "regD" | "regCF" | "custom"
  enableDebugLogs?: boolean
  stepHandlers?: StepHandlers
  customSuccessHandler?: () => void
}
```

---

## 8. Offering Configuration

### 8.1 OfferingParams Interface

```tsx
interface OfferingParams {
  offeringId: string                    // Unique offering identifier
  companyName: string                   // Company name for display
  sharePrice: number                    // Price per share
  minInvestment: number                 // Minimum investment amount
  maxInvestment: number                 // Maximum investment amount
  deadline: Date                        // Offering deadline
  regulation: "regA" | "regD" | "regCF" // Regulation type
  customContent?: {
    welcomeMessage?: string             // Custom welcome text
    riskDisclosure?: string             // Risk disclosure text
    investmentTerms?: string            // Investment terms
    legalFooter?: string                // Legal footer text
    disclaimers?: string[]              // Array of disclaimers
  }
  features?: {
    allowInternational?: boolean        // Allow international investors
    requireAccreditation?: boolean      // Require accreditation check
    enableCrypto?: boolean              // Accept cryptocurrency
  }
}
```

### 8.2 Dynamic Validation

The library automatically validates investment amounts against offering parameters:

- Minimum/maximum investment validation
- Share price calculations
- Deadline enforcement
- Regulation-specific limits

---

## 9. Utilities & Helpers

### 9.1 Core Utilities

```tsx
// Step configuration helper
import { createStepConfig } from "@rajkrajpj/cultivate-ui-library"

const customSteps = createStepConfig([
  {
    id: "custom-step",
    component: MyCustomStep,
    title: "Custom Step",
    validationSchema: myValidationSchema,
  }
])

// Data merging utility
import { mergeInvestorFormData } from "@rajkrajpj/cultivate-ui-library"

const mergedData = mergeInvestorFormData(existingData, newStepData)
```

### 9.2 Default Step Creation

```tsx
import { createDefaultSteps } from "@rajkrajpj/cultivate-ui-library"

// Zero configuration
const basicSteps = createDefaultSteps({
  regulation: "regA"
})

// With custom handlers
const advancedSteps = createDefaultSteps({
  regulation: "regCF",
  enableDebugLogs: true,
  stepHandlers: myStepHandlers,
  customSuccessHandler: () => window.location.href = "/success"
})
```

---

## 10. Styling & Theming

### 10.1 Tailwind CSS Integration

The library is built with Tailwind CSS and requires consumers to include Tailwind in their projects:

```js
// tailwind.config.js
module.exports = {
  content: [
    "./src/**/*.{js,ts,jsx,tsx}",
    "./node_modules/@rajkrajpj/cultivate-ui-library/**/*.{js,ts,jsx,tsx}",
  ],
  // ...rest of config
}
```

### 10.2 CSS Custom Properties

The library uses CSS custom properties for theming, allowing runtime theme customization:

```css
:root {
  --primary: #e11d48;
  --primary-foreground: #fff;
  --background: #f9fafb;
  /* ...other theme variables */
}
```

### 10.3 Component Variants

All components use CVA (Class Variance Authority) for consistent variant management:

```tsx
// Example button variants
const buttonVariants = cva(
  "inline-flex items-center justify-center rounded-md text-sm font-medium",
  {
    variants: {
      variant: {
        default: "bg-primary text-primary-foreground hover:bg-primary/90",
        outline: "border border-input bg-background hover:bg-accent",
      },
      size: {
        default: "h-10 px-4 py-2",
        sm: "h-9 rounded-md px-3",
        lg: "h-11 rounded-md px-8",
      },
    },
  }
)
```

---

## 11. Error Handling & Persistence

### 11.1 Error Handling Strategy

```tsx
<InvestorFormWizard
  steps={steps}
  regulation="regA"
  offeringParams={offeringParams}
  onError={(error, stepId) => {
    console.error(`Error in step ${stepId}:`, error)
    // Custom error handling logic
  }}
  onComplete={handleComplete}
/>
```

### 11.2 Form Persistence

Automatic localStorage persistence with configurable keys:

```tsx
<InvestorFormWizard
  steps={steps}
  regulation="regA"
  offeringParams={offeringParams}
  persistenceKey="investor-form-draft"  // Auto-saves to localStorage
  initialData={savedFormData}           // Pre-populate with saved data
  onComplete={handleComplete}
/>
```

**Persistence Features:**
- Debounced saving (500ms delay)
- Automatic data restoration on page reload
- Clear cache on successful submission
- Step tracking for resume capability

---

## 12. Package Distribution & Installation

### 12.1 NPM Package

```bash
npm install @rajkrajpj/cultivate-ui-library
```

### 12.2 Required Setup

```tsx
// 1. Import styles in your app entry point
import "@rajkrajpj/cultivate-ui-library/styles"

// 2. Add to Tailwind config
module.exports = {
  content: [
    "./src/**/*.{js,ts,jsx,tsx}",
    "./node_modules/@rajkrajpj/cultivate-ui-library/**/*.{js,ts,jsx,tsx}",
  ],
}

// 3. Use in your components
import { InvestorFormWizard } from "@rajkrajpj/cultivate-ui-library"
```

### 12.3 Bundle Output

- **ESM and CJS bundles** for broad compatibility
- **TypeScript declaration files** for full type support
- **CSS styles** with Tailwind integration
- **Tree-shaking support** for optimal bundle sizes

---

## 13. Migration Benefits

### 13.1 Before/After Comparison

**Before (Legacy Implementation):**
- ~500+ lines of boilerplate code
- Custom step management logic
- Manual validation implementation
- Custom persistence logic
- Regulation-specific hard-coding
- Limited reusability

**After (Library Usage):**
- ~25-50 lines of business logic
- Zero configuration option
- Built-in validation and persistence
- Regulation-agnostic architecture
- Full reusability across projects
- Production-ready components

### 13.2 Key Migration Benefits

1. **Massive Code Reduction**: 90%+ reduction in boilerplate code
2. **Improved Maintainability**: Centralized logic in the library
3. **Enhanced Compliance**: Built-in regulation support
4. **Better UX**: Consistent, tested user experience
5. **Faster Development**: New forms can be built in minutes
6. **Type Safety**: Full TypeScript support throughout

---

## 14. Production Readiness

### 14.1 Current Status

✅ **Production Features Implemented:**
- Complete 12-step investor form flow
- Multi-investor type support (Individual, Joint, Company, Trust, IRA)
- Regulation-specific logic (RegA+, RegD, RegCF)
- Comprehensive validation with Zod
- Form persistence and recovery
- Error handling and loading states
- Mobile-responsive design
- Accessibility compliance (WCAG 2.1 AA)
- TypeScript support with strict typing
- Bundle optimization and tree-shaking

### 14.2 API Stability

The current API is stable and production-ready:

- **Semantic Versioning**: Following semver for all releases
- **Backward Compatibility**: Non-breaking changes in minor versions
- **TypeScript Support**: Full type safety with IntelliSense
- **Documentation**: Comprehensive docs and examples

### 14.3 Performance Characteristics

- **Bundle Size**: Optimized for tree-shaking, minimal footprint
- **Runtime Performance**: Efficient React patterns, optimized re-renders
- **Memory Usage**: Proper cleanup and memory management
- **Load Times**: Code-splitting and lazy loading support

---

## 15. Future Enhancements

### 15.1 Planned Features

**Phase 1 (Next Release):**
- Enhanced theming system with design tokens
- Additional regulation support (Reg S, custom regulations)
- Advanced validation rules engine
- Multi-language support

**Phase 2 (Future):**
- Visual form builder for custom steps
- Advanced analytics integration
- Enhanced mobile optimization
- Real-time collaboration features

### 15.2 Community & Extensibility

The library is designed for extensibility:

- **Custom Step Components**: Easy to add custom steps
- **Custom Validation**: Pluggable validation system
- **Theme Customization**: Full control over styling
- **API Integration**: Flexible hooks for any backend

---

## 16. Success Metrics

### 16.1 Development Efficiency

- **Code Reduction**: 90%+ reduction in implementation code
- **Development Time**: New investor forms in 15-30 minutes
- **Maintenance Overhead**: Centralized in library, minimal per-project maintenance

### 16.2 User Experience

- **Form Completion Rates**: Optimized flow for maximum completion
- **Mobile Experience**: Responsive design with touch optimization
- **Accessibility**: WCAG 2.1 AA compliance out of the box
- **Performance**: Fast load times and smooth interactions

### 16.3 Business Impact

- **Faster Time to Market**: Rapid deployment of new offerings
- **Reduced Development Costs**: Minimal custom development required
- **Improved Compliance**: Built-in regulation support
- **Enhanced Scalability**: Consistent patterns across all forms

This implementation plan reflects the current state of the Cultivate UI Library as a production-ready, comprehensive solution for fintech investor forms that significantly reduces development complexity while providing enterprise-grade features and compliance support.