template:
  id: frontend-architecture-template-v3-enhanced
  name: VC-SYS Enhanced Frontend Architecture Document
  version: 3.0
  output:
    format: markdown
    filename: docs/frontend-architecture.md
    title: "{{project_name}} Frontend Architecture Document"

# VC-SYS Enhancement: Agent permissions and evidence requirements
permissions:
  owner: frontend-specialist
  editors: [ux-expert, developer, qa]
  viewers: [scrum-master, product-owner, technical-architect]
  evidence-required: true
  anti-hallucination: enabled
  accessibility-compliance: mandatory
  performance-tracking: enabled

workflow:
  mode: interactive
  elicitation: advanced-elicitation
  facilitation: laboratory-agent
  validation: frontend-checklist
  accessibility-review: required
  
# VC-SYS Enhancement: Integration with specialized agents
agent-coordination:
  primary: frontend-specialist
  secondary: 
    - ux-expert # For user experience validation
    - laboratory # For creative UI exploration
    - qa # For testing strategy
  validation: qa
  approval: product-owner
  accessibility-audit: accessibility-specialist

sections:
  - id: template-framework-selection
    title: Template and Framework Selection
    instruction: |
      Review provided documents including PRD, UX-UI Specification, and main Architecture Document. Focus on extracting technical implementation details needed for AI frontend tools and developer agents. Ask the user for any of these documents if you are unable to locate and were not provided.
      
      VC-SYS Enhancement: Also consider performance requirements, accessibility standards, and progressive enhancement needs.
      
      Before proceeding with frontend architecture design, check if the project is using a frontend starter template or existing codebase:
      
      1. Review the PRD, main architecture document, and brainstorming brief for mentions of:
         - Frontend starter templates (e.g., Create React App, Next.js, Vite, Vue CLI, Angular CLI, etc.)
         - UI kit or component library starters
         - Existing frontend projects being used as a foundation
         - Admin dashboard templates or other specialized starters
         - Design system implementations
         - Accessibility-focused starters
         - Performance-optimized templates
      
      2. If a frontend starter template or existing project is mentioned:
         - Ask the user to provide access via one of these methods:
           - Link to the starter template documentation
           - Upload/attach the project files (for small projects)
           - Share a link to the project repository
         - Analyze the starter/existing project to understand:
           - Pre-installed dependencies and versions
           - Folder structure and file organization
           - Built-in components and utilities
           - Styling approach (CSS modules, styled-components, Tailwind, etc.)
           - State management setup (if any)
           - Routing configuration
           - Testing setup and patterns
           - Build and development scripts
           - Accessibility features
           - Performance optimizations
         - Use this analysis to ensure your frontend architecture aligns with the starter's patterns
      
      3. If no frontend starter is mentioned but this is a new UI, ensure we know what the UI language and framework is:
         - Based on the framework choice, suggest appropriate starters:
           - React: Create React App, Next.js, Vite + React, T3 Stack
           - Vue: Vue CLI, Nuxt.js, Vite + Vue
           - Angular: Angular CLI
           - Svelte: SvelteKit
           - Or suggest popular UI templates if applicable
         - Explain benefits specific to frontend development
         - Consider performance implications and bundle size
      
      4. If the user confirms no starter template will be used:
         - Note that all tooling, bundling, and configuration will need manual setup
         - Proceed with frontend architecture from scratch
         - Emphasize importance of accessibility and performance from start
      
      Document the starter template decision and any constraints it imposes before proceeding.
    elicit: true
    evidence-required: true
    sections:
      - id: framework-analysis
        title: Framework Analysis
        template: |
          **Selected Framework:** {{selected_framework}}
          **Version:** {{framework_version}}
          **Starter Template:** {{starter_template}}
          **Bundle Size Impact:** {{bundle_size_analysis}}
          **Performance Characteristics:** {{performance_analysis}}
          **Accessibility Support:** {{a11y_support}}
          **Learning Curve:** {{learning_curve}}/10
          **Community Support:** {{community_score}}/10
          
      - id: changelog
        title: Change Log
        type: table
        columns: [Date, Version, Description, Author, Performance Impact]
        instruction: Track document versions, changes, and performance implications

  - id: performance-requirements
    title: Performance Requirements
    instruction: |
      VC-SYS Enhancement: Define specific performance targets and optimization strategies.
      
      Establish performance requirements based on user needs and business goals:
      1. Core Web Vitals targets
      2. Bundle size constraints
      3. Loading performance requirements
      4. Runtime performance expectations
      5. Mobile performance considerations
    elicit: true
    evidence-required: true
    sections:
      - id: performance-targets
        title: Performance Targets
        template: |
          **Core Web Vitals:**
          - LCP (Largest Contentful Paint): {{lcp_target}}s
          - FID (First Input Delay): {{fid_target}}ms
          - CLS (Cumulative Layout Shift): {{cls_target}}
          
          **Bundle Size Targets:**
          - Initial Bundle: {{initial_bundle}}KB
          - Total Bundle: {{total_bundle}}KB
          - Lazy Load Chunks: {{lazy_chunk_size}}KB max
          
          **Loading Performance:**
          - Time to Interactive: {{tti_target}}s
          - First Contentful Paint: {{fcp_target}}s
          - Speed Index: {{speed_index}}
          
          **Runtime Performance:**
          - Frame Rate: {{fps_target}} FPS
          - Memory Usage: {{memory_limit}}MB max
          - CPU Usage: {{cpu_limit}}% max
          
      - id: optimization-strategy
        title: Optimization Strategy
        template: |
          **Code Splitting:**
          - Route-based: {{route_splitting}}
          - Component-based: {{component_splitting}}
          - Third-party: {{vendor_splitting}}
          
          **Asset Optimization:**
          - Image Optimization: {{image_strategy}}
          - Font Loading: {{font_strategy}}
          - CSS Strategy: {{css_strategy}}
          
          **Caching Strategy:**
          - Browser Cache: {{browser_cache}}
          - Service Worker: {{sw_strategy}}
          - CDN Strategy: {{cdn_strategy}}

  - id: accessibility-requirements
    title: Accessibility Requirements
    instruction: |
      VC-SYS Enhancement: Comprehensive accessibility standards and testing.
      
      Define accessibility requirements and implementation strategy:
      1. WCAG compliance level
      2. Screen reader support
      3. Keyboard navigation
      4. Color contrast requirements
      5. Focus management
      6. ARIA implementation
    elicit: true
    evidence-required: true
    sections:
      - id: accessibility-standards
        title: Accessibility Standards
        template: |
          **WCAG Compliance:** {{wcag_level}} ({{wcag_version}})
          **Screen Reader Support:** {{screen_readers}}
          **Keyboard Navigation:** {{keyboard_support}}
          **Color Contrast Ratio:** {{contrast_ratio}}
          **Focus Management:** {{focus_strategy}}
          **ARIA Implementation:** {{aria_strategy}}
          
      - id: accessibility-testing
        title: Accessibility Testing
        template: |
          **Automated Testing:**
          - Tool: {{a11y_testing_tool}}
          - Coverage: {{a11y_coverage}}%
          - CI Integration: {{a11y_ci}}
          
          **Manual Testing:**
          - Screen Reader Testing: {{sr_testing}}
          - Keyboard Navigation: {{kb_testing}}
          - Color Vision Testing: {{color_testing}}
          
          **User Testing:**
          - Assistive Technology Users: {{user_testing}}
          - Feedback Collection: {{feedback_process}}

  - id: frontend-tech-stack
    title: Frontend Tech Stack
    instruction: |
      Extract from main architecture's Technology Stack Table. This section MUST remain synchronized with the main architecture document.
      
      VC-SYS Enhancement: Include accessibility, performance, and security considerations for each choice.
    elicit: true
    evidence-required: true
    sections:
      - id: tech-stack-table
        title: Technology Stack Table
        type: table
        columns: [Category, Technology, Version, Purpose, Rationale, A11y Impact, Perf Impact]
        instruction: Fill in appropriate technology choices based on the selected framework and project requirements.
        rows:
          - ["Framework", "{{framework}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["UI Library", "{{ui_library}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["State Management", "{{state_management}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Routing", "{{routing_library}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Build Tool", "{{build_tool}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Styling", "{{styling_solution}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Testing", "{{test_framework}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Component Library", "{{component_lib}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Form Handling", "{{form_library}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Animation", "{{animation_lib}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["A11y Tools", "{{a11y_tools}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Performance Tools", "{{perf_tools}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Security Tools", "{{security_tools}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]
          - ["Dev Tools", "{{dev_tools}}", "{{version}}", "{{purpose}}", "{{why_chosen}}", "{{a11y_impact}}", "{{perf_impact}}"]

  - id: design-system-integration
    title: Design System Integration
    instruction: |
      VC-SYS Enhancement: Comprehensive design system with accessibility and performance considerations.
      
      Define design system architecture:
      1. Design tokens
      2. Component hierarchy
      3. Theme management
      4. Accessibility patterns
      5. Performance considerations
    elicit: true
    sections:
      - id: design-tokens
        title: Design System Tokens
        template: |
          **Color System:**
          - Primary Palette: {{primary_colors}}
          - Semantic Colors: {{semantic_colors}}
          - Accessibility Compliance: {{color_accessibility}}
          
          **Typography Scale:**
          - Font Families: {{font_families}}
          - Size Scale: {{font_sizes}}
          - Line Heights: {{line_heights}}
          - Accessibility: {{type_accessibility}}
          
          **Spacing System:**
          - Base Unit: {{spacing_base}}
          - Scale: {{spacing_scale}}
          - Grid System: {{grid_system}}
          
          **Elevation/Shadows:**
          - Shadow Scale: {{shadow_scale}}
          - Z-index Scale: {{z_index_scale}}
          
      - id: component-architecture
        title: Component Architecture
        template: |
          **Atomic Design Levels:**
          - Atoms: {{atom_components}}
          - Molecules: {{molecule_components}}
          - Organisms: {{organism_components}}
          - Templates: {{template_components}}
          - Pages: {{page_components}}
          
          **Accessibility Patterns:**
          - Focus Management: {{focus_patterns}}
          - ARIA Patterns: {{aria_patterns}}
          - Keyboard Navigation: {{keyboard_patterns}}

  - id: project-structure
    title: Project Structure
    instruction: |
      Define exact directory structure for AI tools based on the chosen framework. Be specific about where each type of file goes. Generate a structure that follows the framework's best practices and conventions.
      
      VC-SYS Enhancement: Include accessibility, performance, and security considerations in structure.
    elicit: true
    type: code
    language: plaintext
    template: |
      {{project_name}}/
      ├── src/
      │   ├── components/          # Component library
      │   │   ├── atoms/           # Basic UI elements
      │   │   │   ├── Button/
      │   │   │   │   ├── Button.tsx
      │   │   │   │   ├── Button.test.tsx
      │   │   │   │   ├── Button.stories.tsx
      │   │   │   │   └── Button.module.css
      │   │   ├── molecules/       # Compound components
      │   │   ├── organisms/       # Complex components
      │   │   └── templates/       # Layout templates
      │   ├── pages/               # Page components
      │   ├── hooks/               # Custom React hooks
      │   │   ├── useAccessibility.ts
      │   │   ├── usePerformance.ts
      │   │   └── useSecurity.ts
      │   ├── services/            # API and external services
      │   │   ├── api/
      │   │   ├── auth/
      │   │   └── analytics/
      │   ├── stores/              # State management
      │   │   ├── auth/
      │   │   ├── ui/
      │   │   └── user/
      │   ├── styles/              # Global styles and themes
      │   │   ├── globals.css
      │   │   ├── variables.css
      │   │   ├── accessibility.css
      │   │   └── themes/
      │   ├── utils/               # Utility functions
      │   │   ├── accessibility.ts
      │   │   ├── performance.ts
      │   │   ├── security.ts
      │   │   └── validation.ts
      │   ├── types/               # TypeScript type definitions
      │   │   ├── api.ts
      │   │   ├── ui.ts
      │   │   └── accessibility.ts
      │   ├── assets/              # Static assets
      │   │   ├── images/
      │   │   ├── icons/
      │   │   └── fonts/
      │   └── config/              # Configuration files
      │       ├── constants.ts
      │       ├── environment.ts
      │       └── feature-flags.ts
      ├── public/                  # Public static files
      ├── tests/                   # Test utilities and configs
      │   ├── __mocks__/
      │   ├── fixtures/
      │   ├── utils/
      │   ├── accessibility/       # A11y test helpers
      │   └── performance/         # Performance test helpers
      ├── docs/                    # Documentation
      │   ├── components/          # Component documentation
      │   ├── accessibility/       # A11y guidelines
      │   └── performance/         # Performance guidelines
      └── {{framework_specific_files}}

  - id: component-standards
    title: Component Standards
    instruction: |
      Define exact patterns for component creation based on the chosen framework.
      
      VC-SYS Enhancement: Include accessibility, performance, and security patterns.
    elicit: true
    sections:
      - id: component-template
        title: Component Template
        instruction: |
          Generate a comprehensive component template following the framework's best practices. Include TypeScript types, accessibility features, performance considerations, and security measures.
        type: code
        language: typescript
        template: |
          import React, { memo, forwardRef } from 'react';
          import classNames from 'classnames';
          import { useAccessibility } from '@/hooks/useAccessibility';
          import { usePerformance } from '@/hooks/usePerformance';
          import styles from './{{ComponentName}}.module.css';

          interface {{ComponentName}}Props {
            children?: React.ReactNode;
            className?: string;
            disabled?: boolean;
            loading?: boolean;
            ariaLabel?: string;
            ariaDescribedBy?: string;
            onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
            // Performance tracking
            trackingId?: string;
            // Security
            sanitizeContent?: boolean;
          }

          export const {{ComponentName}} = memo(forwardRef<
            HTMLButtonElement,
            {{ComponentName}}Props
          >(({
            children,
            className,
            disabled = false,
            loading = false,
            ariaLabel,
            ariaDescribedBy,
            onClick,
            trackingId,
            sanitizeContent = true,
            ...props
          }, ref) => {
            const { announceToScreenReader } = useAccessibility();
            const { trackInteraction } = usePerformance();

            const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
              if (disabled || loading) return;
              
              // Performance tracking
              if (trackingId) {
                trackInteraction(trackingId, 'click');
              }
              
              // Accessibility announcement
              if (loading) {
                announceToScreenReader('Loading...');
              }
              
              onClick?.(event);
            };

            const componentClasses = classNames(
              styles.component,
              {
                [styles.disabled]: disabled,
                [styles.loading]: loading,
              },
              className
            );

            return (
              <button
                ref={ref}
                className={componentClasses}
                disabled={disabled || loading}
                aria-label={ariaLabel}
                aria-describedby={ariaDescribedBy}
                aria-busy={loading}
                onClick={handleClick}
                {...props}
              >
                {loading && (
                  <span 
                    className={styles.spinner} 
                    aria-hidden="true"
                    role="status"
                  />
                )}
                <span className={loading ? styles.hiddenContent : undefined}>
                  {sanitizeContent && typeof children === 'string' 
                    ? sanitizeHtml(children) 
                    : children}
                </span>
              </button>
            );
          }));

          {{ComponentName}}.displayName = '{{ComponentName}}';

      - id: naming-conventions
        title: Naming Conventions
        instruction: |
          Provide naming conventions specific to the chosen framework for components, files, services, state management, and other architectural elements.
          
          VC-SYS Enhancement: Include accessibility and performance naming patterns.
        template: |
          **Components:**
          - Component Files: PascalCase (e.g., `UserProfile.tsx`)
          - Component Props: camelCase interfaces (e.g., `UserProfileProps`)
          - CSS Modules: kebab-case (e.g., `user-profile.module.css`)
          
          **Accessibility:**
          - ARIA IDs: kebab-case with prefix (e.g., `user-profile-dialog`)
          - Test IDs: kebab-case (e.g., `data-testid="user-profile-button"`)
          - Screen Reader Text: camelCase (e.g., `screenReaderText`)
          
          **Performance:**
          - Metrics: camelCase (e.g., `loadTime`, `renderDuration`)
          - Tracking IDs: kebab-case (e.g., `user-profile-load`)
          
          **State Management:**
          - Store Names: camelCase (e.g., `userStore`, `authStore`)
          - Actions: camelCase verbs (e.g., `setUser`, `updateProfile`)
          - Selectors: camelCase with 'get' prefix (e.g., `getUserProfile`)
          
          **Files and Directories:**
          - Directories: kebab-case (e.g., `user-profile/`)
          - Utilities: camelCase (e.g., `formatCurrency.ts`)
          - Constants: UPPER_SNAKE_CASE (e.g., `API_ENDPOINTS`)

  - id: state-management
    title: State Management
    instruction: |
      Define state management patterns based on the chosen framework.
      
      VC-SYS Enhancement: Include accessibility state, performance optimization, and security considerations.
    elicit: true
    sections:
      - id: store-architecture
        title: Store Architecture
        template: |
          **Global State:**
          - User Authentication: {{auth_state}}
          - UI State: {{ui_state}}
          - Application Data: {{app_data}}
          - Accessibility Preferences: {{a11y_state}}
          
          **Local State:**
          - Component State: {{component_state}}
          - Form State: {{form_state}}
          - Temporary UI State: {{temp_state}}
          
          **Performance Considerations:**
          - State Normalization: {{normalization_approach}}
          - Memoization: {{memo_strategy}}
          - State Slicing: {{slicing_approach}}
          
      - id: store-structure
        title: Store Structure
        instruction: Generate the state management directory structure appropriate for the chosen framework and selected state management solution.
        type: code
        language: plaintext
        template: |
          src/stores/
          ├── index.ts                 # Store configuration
          ├── auth/
          │   ├── authStore.ts        # Authentication state
          │   ├── authActions.ts      # Auth actions
          │   └── authSelectors.ts    # Auth selectors
          ├── ui/
          │   ├── uiStore.ts          # UI state
          │   ├── accessibilityStore.ts # A11y preferences
          │   └── performanceStore.ts # Performance metrics
          ├── user/
          │   ├── userStore.ts        # User data
          │   └── userPreferences.ts  # User preferences
          └── middleware/
              ├── logger.ts           # Development logging
              ├── analytics.ts        # Usage analytics
              └── performance.ts      # Performance tracking
              
      - id: state-template
        title: State Management Template
        instruction: |
          Provide a comprehensive state management template/example following the framework's recommended patterns. Include TypeScript types, accessibility considerations, and performance optimizations.
        type: code
        language: typescript
        template: |
          import { create } from 'zustand';
          import { devtools, subscribeWithSelector } from 'zustand/middleware';
          import { immer } from 'zustand/middleware/immer';

          interface UserState {
            user: User | null;
            preferences: UserPreferences;
            accessibilitySettings: AccessibilitySettings;
            isLoading: boolean;
            error: string | null;
            
            // Actions
            setUser: (user: User) => void;
            updatePreferences: (preferences: Partial<UserPreferences>) => void;
            updateAccessibility: (settings: Partial<AccessibilitySettings>) => void;
            setLoading: (loading: boolean) => void;
            setError: (error: string | null) => void;
            reset: () => void;
          }

          interface AccessibilitySettings {
            reducedMotion: boolean;
            highContrast: boolean;
            screenReaderEnabled: boolean;
            fontSize: 'small' | 'medium' | 'large';
            focusVisible: boolean;
          }

          const initialState = {
            user: null,
            preferences: {
              theme: 'light' as const,
              language: 'en',
              notifications: true,
            },
            accessibilitySettings: {
              reducedMotion: false,
              highContrast: false,
              screenReaderEnabled: false,
              fontSize: 'medium' as const,
              focusVisible: true,
            },
            isLoading: false,
            error: null,
          };

          export const useUserStore = create<UserState>()(
            devtools(
              subscribeWithSelector(
                immer((set, get) => ({
                  ...initialState,

                  setUser: (user) =>
                    set((state) => {
                      state.user = user;
                      state.error = null;
                    }),

                  updatePreferences: (preferences) =>
                    set((state) => {
                      state.preferences = { ...state.preferences, ...preferences };
                    }),

                  updateAccessibility: (settings) =>
                    set((state) => {
                      state.accessibilitySettings = { 
                        ...state.accessibilitySettings, 
                        ...settings 
                      };
                      // Apply accessibility settings to DOM
                      applyAccessibilitySettings(state.accessibilitySettings);
                    }),

                  setLoading: (loading) =>
                    set((state) => {
                      state.isLoading = loading;
                    }),

                  setError: (error) =>
                    set((state) => {
                      state.error = error;
                      state.isLoading = false;
                    }),

                  reset: () => set(initialState),
                }))
              ),
              { name: 'user-store' }
            )
          );

          // Performance optimization: Memoized selectors
          export const selectUser = (state: UserState) => state.user;
          export const selectAccessibilitySettings = (state: UserState) => 
            state.accessibilitySettings;

  - id: api-integration
    title: API Integration
    instruction: |
      Define API service patterns based on the chosen framework.
      
      VC-SYS Enhancement: Include security headers, performance monitoring, and error handling.
    elicit: true
    sections:
      - id: service-template
        title: Service Template
        instruction: |
          Provide a comprehensive API service template that follows the framework's conventions. Include proper TypeScript types, security measures, performance tracking, and error handling.
        type: code
        language: typescript
        template: |
          import { z } from 'zod';
          import { ApiError, handleApiError } from '@/utils/errorHandling';
          import { trackApiCall } from '@/utils/performance';
          import { sanitizeInput } from '@/utils/security';

          // API Response Schema
          const UserSchema = z.object({
            id: z.string(),
            email: z.string().email(),
            name: z.string(),
            preferences: z.object({
              theme: z.enum(['light', 'dark']),
              language: z.string(),
            }),
          });

          type User = z.infer<typeof UserSchema>;

          interface ApiConfig {
            baseUrl: string;
            timeout: number;
            retries: number;
            headers: Record<string, string>;
          }

          class ApiClient {
            private config: ApiConfig;
            private abortController: AbortController;

            constructor(config: ApiConfig) {
              this.config = config;
              this.abortController = new AbortController();
            }

            private async request<T>(
              endpoint: string,
              options: RequestInit = {},
              schema?: z.ZodSchema<T>
            ): Promise<T> {
              const startTime = performance.now();
              const trackingId = `api-${endpoint.replace(/[^a-zA-Z0-9]/g, '-')}`;

              try {
                const url = `${this.config.baseUrl}${endpoint}`;
                
                const response = await fetch(url, {
                  ...options,
                  signal: this.abortController.signal,
                  headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-Token': this.getCsrfToken(),
                    ...this.config.headers,
                    ...options.headers,
                  },
                });

                if (!response.ok) {
                  throw new ApiError(
                    `HTTP ${response.status}: ${response.statusText}`,
                    response.status,
                    endpoint
                  );
                }

                const data = await response.json();
                
                // Validate response if schema provided
                if (schema) {
                  const validationResult = schema.safeParse(data);
                  if (!validationResult.success) {
                    throw new ApiError(
                      'Invalid response format',
                      500,
                      endpoint,
                      validationResult.error
                    );
                  }
                  return validationResult.data;
                }

                return data;
              } catch (error) {
                const duration = performance.now() - startTime;
                trackApiCall(trackingId, duration, false);
                throw handleApiError(error, endpoint);
              } finally {
                const duration = performance.now() - startTime;
                trackApiCall(trackingId, duration, true);
              }
            }

            private getCsrfToken(): string {
              return document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content || '';
            }

            // User service methods
            async getUser(id: string): Promise<User> {
              const sanitizedId = sanitizeInput(id);
              return this.request(`/users/${sanitizedId}`, {}, UserSchema);
            }

            async updateUser(id: string, userData: Partial<User>): Promise<User> {
              const sanitizedId = sanitizeInput(id);
              const sanitizedData = sanitizeInput(userData);
              
              return this.request(
                `/users/${sanitizedId}`,
                {
                  method: 'PATCH',
                  body: JSON.stringify(sanitizedData),
                },
                UserSchema
              );
            }

            // Cleanup
            destroy() {
              this.abortController.abort();
            }
          }

          // Service instance
          export const apiClient = new ApiClient({
            baseUrl: process.env.NEXT_PUBLIC_API_URL || '/api',
            timeout: 10000,
            retries: 3,
            headers: {
              'X-Client-Version': process.env.NEXT_PUBLIC_APP_VERSION || '1.0.0',
            },
          });

      - id: api-client-config
        title: API Client Configuration
        instruction: |
          Show how to configure the HTTP client for the chosen framework, including authentication interceptors/middleware, security headers, and error handling.
        type: code
        language: typescript
        template: |
          import { apiClient } from './apiClient';
          import { useAuthStore } from '@/stores/auth/authStore';
          import { toast } from '@/components/ui/Toast';

          // Authentication interceptor
          export const setupAuthInterceptor = () => {
            const originalRequest = apiClient.request.bind(apiClient);
            
            apiClient.request = async (endpoint, options = {}) => {
              const authStore = useAuthStore.getState();
              const token = authStore.token;
              
              if (token) {
                options.headers = {
                  ...options.headers,
                  Authorization: `Bearer ${token}`,
                };
              }
              
              try {
                return await originalRequest(endpoint, options);
              } catch (error) {
                // Handle auth errors
                if (error.status === 401) {
                  authStore.logout();
                  toast.error('Session expired. Please log in again.');
                  window.location.href = '/login';
                }
                
                // Handle rate limiting
                if (error.status === 429) {
                  toast.error('Too many requests. Please try again later.');
                }
                
                throw error;
              }
            };
          };

          // Performance monitoring
          export const setupPerformanceMonitoring = () => {
            // Track API performance metrics
            window.addEventListener('beforeunload', () => {
              // Send performance data before page unload
              const metrics = getApiMetrics();
              navigator.sendBeacon('/api/metrics', JSON.stringify(metrics));
            });
          };

          // Security headers
          export const securityHeaders = {
            'X-Content-Type-Options': 'nosniff',
            'X-Frame-Options': 'DENY',
            'X-XSS-Protection': '1; mode=block',
            'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
          };

  - id: routing
    title: Routing
    instruction: |
      Define routing structure and patterns based on the chosen framework.
      
      VC-SYS Enhancement: Include accessibility considerations, performance optimization, and security measures.
    elicit: true
    sections:
      - id: route-configuration
        title: Route Configuration
        instruction: |
          Provide comprehensive routing configuration appropriate for the chosen framework. Include protected routes, lazy loading, accessibility features, and security measures.
        type: code
        language: typescript
        template: |
          import { lazy, Suspense } from 'react';
          import { 
            createBrowserRouter, 
            RouterProvider, 
            Navigate,
            Outlet
          } from 'react-router-dom';
          import { useAuthStore } from '@/stores/auth/authStore';
          import { useAccessibilityStore } from '@/stores/ui/accessibilityStore';
          import { ErrorBoundary } from '@/components/ErrorBoundary';
          import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
          import { SkipLink } from '@/components/a11y/SkipLink';
          import { announceRouteChange } from '@/utils/accessibility';

          // Lazy-loaded components for code splitting
          const HomePage = lazy(() => import('@/pages/HomePage'));
          const ProfilePage = lazy(() => import('@/pages/ProfilePage'));
          const SettingsPage = lazy(() => import('@/pages/SettingsPage'));
          const AdminDashboard = lazy(() => import('@/pages/AdminDashboard'));

          // Route guard components
          const ProtectedRoute = ({ children }: { children: React.ReactNode }) => {
            const { user, isAuthenticated } = useAuthStore();
            
            if (!isAuthenticated) {
              return <Navigate to="/login" replace />;
            }
            
            return <>{children}</>;
          };

          const AdminRoute = ({ children }: { children: React.ReactNode }) => {
            const { user, isAuthenticated } = useAuthStore();
            
            if (!isAuthenticated || user?.role !== 'admin') {
              return <Navigate to="/unauthorized" replace />;
            }
            
            return <>{children}</>;
          };

          // Layout wrapper with accessibility features
          const LayoutWrapper = () => {
            const { screenReaderEnabled } = useAccessibilityStore();
            
            return (
              <>
                {screenReaderEnabled && <SkipLink href="#main-content" />}
                <div className="app-layout">
                  <nav aria-label="Main navigation">
                    {/* Navigation component */}
                  </nav>
                  <main id="main-content" tabIndex={-1}>
                    <Suspense 
                      fallback={
                        <LoadingSpinner 
                          ariaLabel="Loading page content" 
                          size="large" 
                        />
                      }
                    >
                      <ErrorBoundary>
                        <Outlet />
                      </ErrorBoundary>
                    </Suspense>
                  </main>
                </div>
              </>
            );
          };

          // Route configuration with accessibility and performance features
          export const router = createBrowserRouter([
            {
              path: '/',
              element: <LayoutWrapper />,
              errorElement: <ErrorPage />,
              children: [
                {
                  index: true,
                  element: <HomePage />,
                  loader: async () => {
                    // Preload critical data
                    return defer({
                      criticalData: getCriticalData(),
                    });
                  },
                },
                {
                  path: 'profile',
                  element: (
                    <ProtectedRoute>
                      <ProfilePage />
                    </ProtectedRoute>
                  ),
                },
                {
                  path: 'settings',
                  element: (
                    <ProtectedRoute>
                      <SettingsPage />
                    </ProtectedRoute>
                  ),
                },
                {
                  path: 'admin',
                  element: (
                    <AdminRoute>
                      <AdminDashboard />
                    </AdminRoute>
                  ),
                },
              ],
            },
          ]);

          // Route change announcer for screen readers
          router.subscribe((state) => {
            const currentLocation = state.location;
            if (currentLocation) {
              announceRouteChange(currentLocation.pathname);
            }
          });

  - id: styling-guidelines
    title: Styling Guidelines
    instruction: |
      Define styling approach based on the chosen framework.
      
      VC-SYS Enhancement: Include accessibility, dark mode, and performance considerations.
    elicit: true
    sections:
      - id: styling-approach
        title: Styling Approach
        instruction: |
          Describe the styling methodology appropriate for the chosen framework with accessibility and performance considerations.
        template: |
          **Primary Styling Method:** {{styling_method}}
          **CSS Architecture:** {{css_architecture}}
          **Responsive Strategy:** {{responsive_approach}}
          **Dark Mode Support:** {{dark_mode_implementation}}
          **Accessibility Features:** {{a11y_styling_features}}
          
          **Performance Considerations:**
          - Critical CSS: {{critical_css_approach}}
          - CSS Purging: {{css_purging}}
          - CSS Minification: {{css_optimization}}
          - Font Loading: {{font_loading_strategy}}
          
          **Accessibility Guidelines:**
          - Color Contrast: {{contrast_requirements}}
          - Focus Indicators: {{focus_styling}}
          - Motion Preferences: {{motion_handling}}
          - High Contrast Mode: {{high_contrast_support}}
          
      - id: global-theme
        title: Global Theme Variables
        instruction: |
          Provide a comprehensive CSS custom properties (CSS variables) theme system that works across all frameworks. Include colors, spacing, typography, shadows, accessibility features, and dark mode support.
        type: code
        language: css
        template: |
          :root {
            /* Color System */
            --color-primary-50: #f0f9ff;
            --color-primary-500: #3b82f6;
            --color-primary-900: #1e3a8a;
            
            --color-gray-50: #f9fafb;
            --color-gray-500: #6b7280;
            --color-gray-900: #111827;
            
            /* Semantic Colors */
            --color-success: #10b981;
            --color-warning: #f59e0b;
            --color-error: #ef4444;
            --color-info: #3b82f6;
            
            /* Typography */
            --font-family-sans: 'Inter', system-ui, sans-serif;
            --font-family-mono: 'JetBrains Mono', monospace;
            
            --font-size-xs: 0.75rem;    /* 12px */
            --font-size-sm: 0.875rem;   /* 14px */
            --font-size-base: 1rem;     /* 16px */
            --font-size-lg: 1.125rem;   /* 18px */
            --font-size-xl: 1.25rem;    /* 20px */
            --font-size-2xl: 1.5rem;    /* 24px */
            --font-size-3xl: 1.875rem;  /* 30px */
            
            --line-height-tight: 1.25;
            --line-height-normal: 1.5;
            --line-height-relaxed: 1.75;
            
            /* Spacing */
            --spacing-0: 0;
            --spacing-1: 0.25rem;  /* 4px */
            --spacing-2: 0.5rem;   /* 8px */
            --spacing-3: 0.75rem;  /* 12px */
            --spacing-4: 1rem;     /* 16px */
            --spacing-6: 1.5rem;   /* 24px */
            --spacing-8: 2rem;     /* 32px */
            --spacing-12: 3rem;    /* 48px */
            
            /* Shadows */
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
            --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
            --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
            
            /* Border Radius */
            --radius-sm: 0.25rem;
            --radius-md: 0.375rem;
            --radius-lg: 0.5rem;
            --radius-full: 9999px;
            
            /* Z-index */
            --z-dropdown: 1000;
            --z-sticky: 1020;
            --z-modal: 1030;
            --z-popover: 1040;
            --z-tooltip: 1050;
            
            /* Accessibility */
            --focus-ring: 0 0 0 2px var(--color-primary-500);
            --focus-ring-offset: 2px;
            
            /* Animation */
            --transition-fast: 150ms ease-in-out;
            --transition-normal: 250ms ease-in-out;
            --transition-slow: 350ms ease-in-out;
          }
          
          /* Dark Mode */
          [data-theme="dark"] {
            --color-gray-50: #111827;
            --color-gray-500: #9ca3af;
            --color-gray-900: #f9fafb;
            
            /* Dark mode specific adjustments */
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.3);
            --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.4);
            --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.5);
          }
          
          /* High Contrast Mode */
          @media (prefers-contrast: high) {
            :root {
              --color-primary-500: #0066cc;
              --focus-ring: 0 0 0 3px #ffff00;
            }
          }
          
          /* Reduced Motion */
          @media (prefers-reduced-motion: reduce) {
            :root {
              --transition-fast: 0ms;
              --transition-normal: 0ms;
              --transition-slow: 0ms;
            }
            
            * {
              animation-duration: 0.01ms !important;
              animation-iteration-count: 1 !important;
              transition-duration: 0.01ms !important;
            }
          }
          
          /* Focus Management */
          .focus-visible {
            outline: var(--focus-ring);
            outline-offset: var(--focus-ring-offset);
          }
          
          /* Screen Reader Only */
          .sr-only {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0, 0, 0, 0);
            white-space: nowrap;
            border: 0;
          }
          
          .sr-only-focusable:focus {
            position: static;
            width: auto;
            height: auto;
            padding: inherit;
            margin: inherit;
            overflow: visible;
            clip: auto;
            white-space: normal;
          }

  - id: testing-requirements
    title: Testing Requirements
    instruction: |
      Define comprehensive testing requirements based on the chosen framework.
      
      VC-SYS Enhancement: Include accessibility testing, performance testing, and security testing.
    elicit: true
    sections:
      - id: testing-strategy
        title: Testing Strategy
        template: |
          **Testing Pyramid:**
          - Unit Tests: {{unit_test_percentage}}%
          - Integration Tests: {{integration_test_percentage}}%
          - E2E Tests: {{e2e_test_percentage}}%
          - Accessibility Tests: {{a11y_test_coverage}}%
          - Performance Tests: {{perf_test_coverage}}%
          - Security Tests: {{security_test_coverage}}%
          
          **Coverage Targets:**
          - Overall Coverage: {{overall_coverage}}%
          - Critical Path Coverage: {{critical_coverage}}%
          - Component Coverage: {{component_coverage}}%
          
      - id: component-test-template
        title: Component Test Template
        instruction: |
          Provide a comprehensive component test template using the framework's recommended testing library. Include examples of rendering tests, user interaction tests, accessibility tests, and mocking.
        type: code
        language: typescript
        template: |
          import { render, screen, fireEvent, waitFor } from '@testing-library/react';
          import userEvent from '@testing-library/user-event';
          import { axe, toHaveNoViolations } from 'jest-axe';
          import { vi } from 'vitest';
          import { Button } from './Button';
          import { TestWrapper } from '@/tests/utils/TestWrapper';

          // Extend Jest matchers
          expect.extend(toHaveNoViolations);

          const mockProps = {
            children: 'Test Button',
            onClick: vi.fn(),
            ariaLabel: 'Test button for unit testing',
          };

          describe('Button Component', () => {
            beforeEach(() => {
              vi.clearAllMocks();
            });

            describe('Rendering', () => {
              it('renders with correct text', () => {
                render(
                  <TestWrapper>
                    <Button {...mockProps} />
                  </TestWrapper>
                );
                
                expect(screen.getByRole('button', { name: /test button/i })).toBeInTheDocument();
              });

              it('applies custom className', () => {
                render(
                  <TestWrapper>
                    <Button {...mockProps} className="custom-class" />
                  </TestWrapper>
                );
                
                const button = screen.getByRole('button');
                expect(button).toHaveClass('custom-class');
              });
            });

            describe('Interactions', () => {
              it('calls onClick when clicked', async () => {
                const user = userEvent.setup();
                
                render(
                  <TestWrapper>
                    <Button {...mockProps} />
                  </TestWrapper>
                );
                
                const button = screen.getByRole('button');
                await user.click(button);
                
                expect(mockProps.onClick).toHaveBeenCalledTimes(1);
              });

              it('does not call onClick when disabled', async () => {
                const user = userEvent.setup();
                
                render(
                  <TestWrapper>
                    <Button {...mockProps} disabled />
                  </TestWrapper>
                );
                
                const button = screen.getByRole('button');
                await user.click(button);
                
                expect(mockProps.onClick).not.toHaveBeenCalled();
              });
            });

            describe('Loading State', () => {
              it('shows loading spinner when loading', () => {
                render(
                  <TestWrapper>
                    <Button {...mockProps} loading />
                  </TestWrapper>
                );
                
                expect(screen.getByRole('status')).toBeInTheDocument();
                expect(screen.getByText('Test Button')).toHaveClass('hiddenContent');
              });

              it('announces loading state to screen readers', () => {
                render(
                  <TestWrapper>
                    <Button {...mockProps} loading />
                  </TestWrapper>
                );
                
                const button = screen.getByRole('button');
                expect(button).toHaveAttribute('aria-busy', 'true');
              });
            });

            describe('Accessibility', () => {
              it('has no accessibility violations', async () => {
                const { container } = render(
                  <TestWrapper>
                    <Button {...mockProps} />
                  </TestWrapper>
                );
                
                const results = await axe(container);
                expect(results).toHaveNoViolations();
              });

              it('supports keyboard navigation', async () => {
                const user = userEvent.setup();
                
                render(
                  <TestWrapper>
                    <Button {...mockProps} />
                  </TestWrapper>
                );
                
                const button = screen.getByRole('button');
                
                // Tab to focus
                await user.tab();
                expect(button).toHaveFocus();
                
                // Enter to activate
                await user.keyboard('{Enter}');
                expect(mockProps.onClick).toHaveBeenCalledTimes(1);
              });

              it('has proper ARIA attributes', () => {
                render(
                  <TestWrapper>
                    <Button 
                      {...mockProps} 
                      ariaDescribedBy="button-description"
                    />
                  </TestWrapper>
                );
                
                const button = screen.getByRole('button');
                expect(button).toHaveAttribute('aria-label', mockProps.ariaLabel);
                expect(button).toHaveAttribute('aria-describedby', 'button-description');
              });
            });

            describe('Performance', () => {
              it('does not re-render unnecessarily', () => {
                const renderSpy = vi.fn();
                const TestButton = vi.fn().mockImplementation((props) => {
                  renderSpy();
                  return <Button {...props} />;
                });

                const { rerender } = render(
                  <TestWrapper>
                    <TestButton {...mockProps} />
                  </TestWrapper>
                );

                expect(renderSpy).toHaveBeenCalledTimes(1);

                // Re-render with same props
                rerender(
                  <TestWrapper>
                    <TestButton {...mockProps} />
                  </TestWrapper>
                );

                // Should not re-render due to memoization
                expect(renderSpy).toHaveBeenCalledTimes(1);
              });
            });

            describe('Security', () => {
              it('sanitizes dangerous content', () => {
                const maliciousContent = '<script>alert("xss")</script>Safe Content';
                
                render(
                  <TestWrapper>
                    <Button onClick={mockProps.onClick}>
                      {maliciousContent}
                    </Button>
                  </TestWrapper>
                );
                
                const button = screen.getByRole('button');
                expect(button.innerHTML).not.toContain('<script>');
                expect(button).toHaveTextContent('Safe Content');
              });
            });
          });

      - id: testing-best-practices
        title: Testing Best Practices
        type: numbered-list
        items:
          - "**Unit Tests**: Test individual components in isolation with mocks"
          - "**Integration Tests**: Test component interactions and data flow"
          - "**E2E Tests**: Test critical user flows using Cypress/Playwright"
          - "**Accessibility Tests**: Use jest-axe and manual testing with assistive tech"
          - "**Performance Tests**: Monitor bundle size, render times, and memory usage"
          - "**Security Tests**: Test XSS prevention, CSRF protection, and input sanitization"
          - "**Coverage Goals**: Aim for 90% code coverage with quality tests"
          - "**Test Structure**: Follow Arrange-Act-Assert pattern consistently"
          - "**Mock Strategy**: Mock external dependencies, APIs, and third-party libraries"
          - "**Snapshot Testing**: Use sparingly for stable UI components only"

  - id: environment-configuration
    title: Environment Configuration
    instruction: |
      List required environment variables based on the chosen framework. Show the appropriate format and naming conventions for the framework.
      
      VC-SYS Enhancement: Include security, accessibility, and performance configuration.
    elicit: true
    type: code
    language: bash
    template: |
      # Application Configuration
      NEXT_PUBLIC_APP_NAME="{{app_name}}"
      NEXT_PUBLIC_APP_VERSION="1.0.0"
      NEXT_PUBLIC_ENVIRONMENT="development"
      
      # API Configuration
      NEXT_PUBLIC_API_URL="http://localhost:3001/api"
      API_SECRET_KEY="your-secret-key-here"
      
      # Authentication
      NEXT_PUBLIC_AUTH_PROVIDER="auth0"
      AUTH0_DOMAIN="your-domain.auth0.com"
      AUTH0_CLIENT_ID="your-client-id"
      AUTH0_CLIENT_SECRET="your-client-secret"
      
      # Performance Monitoring
      NEXT_PUBLIC_ANALYTICS_ID="your-analytics-id"
      NEXT_PUBLIC_PERFORMANCE_MONITORING="true"
      NEXT_PUBLIC_ERROR_TRACKING="true"
      
      # Accessibility Configuration
      NEXT_PUBLIC_A11Y_ANNOUNCEMENTS="true"
      NEXT_PUBLIC_A11Y_HIGH_CONTRAST="false"
      NEXT_PUBLIC_A11Y_REDUCED_MOTION="false"
      
      # Security Configuration
      NEXT_PUBLIC_CSP_NONCE="generate-nonce-here"
      SECURITY_HEADERS="true"
      XSS_PROTECTION="true"
      
      # Feature Flags
      NEXT_PUBLIC_FEATURE_DARK_MODE="true"
      NEXT_PUBLIC_FEATURE_ANALYTICS="true"
      NEXT_PUBLIC_FEATURE_A11Y_TOOLBAR="false"
      
      # Development
      NODE_ENV="development"
      NEXT_PUBLIC_DEBUG_MODE="true"
      NEXT_PUBLIC_SHOW_DEV_TOOLS="true"

  - id: frontend-developer-standards
    title: Frontend Developer Standards
    sections:
      - id: critical-coding-rules
        title: Critical Coding Rules
        instruction: |
          List essential rules that prevent common AI mistakes, including both universal rules and framework-specific ones.
          
          VC-SYS Enhancement: Include accessibility, performance, and security rules.
        elicit: true
        repeatable: true
        template: "- **{{rule_name}}:** {{rule_description}} - _Impact:_ {{impact_level}}"
        examples:
          - "**Accessibility First**: Every interactive element must have proper ARIA labels and keyboard navigation - _Impact:_ Critical"
          - "**Performance Budget**: Components must not exceed 50KB bundle size - _Impact:_ High"
          - "**Security Validation**: Always sanitize user input and use CSP headers - _Impact:_ Critical"
          - "**Semantic HTML**: Use proper HTML elements before adding ARIA attributes - _Impact:_ High"
          - "**Focus Management**: Manage focus states in modals, routes, and dynamic content - _Impact:_ Critical"
          - "**Error Boundaries**: Wrap all major features in error boundaries - _Impact:_ High"
          - "**TypeScript Strict**: Never use 'any' type, always define proper interfaces - _Impact:_ Medium"
          - "**Component Memoization**: Use React.memo for expensive components - _Impact:_ Medium"
          - "**Image Optimization**: Always use next/image or optimized alternatives - _Impact:_ High"
          - "**CSS-in-JS Performance**: Avoid dynamic styles, use CSS variables instead - _Impact:_ Medium"
          
      - id: quick-reference
        title: Quick Reference
        instruction: |
          Create a framework-specific cheat sheet with:
          - Common commands (dev server, build, test)
          - Key import patterns
          - File naming conventions
          - Project-specific patterns and utilities
          
          VC-SYS Enhancement: Include accessibility and performance quick commands.
        template: |
          **Development Commands:**
          ```bash
          npm run dev              # Start development server
          npm run build           # Production build
          npm run test            # Run all tests
          npm run test:a11y       # Accessibility tests
          npm run test:perf       # Performance tests
          npm run lint            # Code linting
          npm run type-check      # TypeScript checking
          npm run analyze         # Bundle analysis
          ```
          
          **Common Import Patterns:**
          ```typescript
          // Components
          import { Button } from '@/components/ui/Button';
          import { useAuth } from '@/hooks/useAuth';
          import { apiClient } from '@/services/api';
          
          // Accessibility
          import { useAccessibility } from '@/hooks/useAccessibility';
          import { announceToScreenReader } from '@/utils/accessibility';
          
          // Performance
          import { trackInteraction } from '@/utils/performance';
          import { lazy, Suspense } from 'react';
          ```
          
          **File Naming Conventions:**
          - Components: `Button.tsx`, `UserProfile.tsx`
          - Hooks: `useAuth.ts`, `useAccessibility.ts`
          - Utils: `formatCurrency.ts`, `sanitizeInput.ts`
          - Tests: `Button.test.tsx`, `useAuth.test.ts`
          - Stories: `Button.stories.tsx`
          
          **Accessibility Shortcuts:**
          ```typescript
          // Quick ARIA setup
          const buttonProps = {
            'aria-label': 'descriptive label',
            'aria-describedby': 'help-text-id',
            'aria-expanded': isOpen,
          };
          
          // Focus management
          const focusRef = useRef<HTMLElement>(null);
          focusRef.current?.focus();
          
          // Screen reader announcement
          announceToScreenReader('Action completed');
          ```
          
          **Performance Patterns:**
          ```typescript
          // Component memoization
          const MyComponent = memo(({ prop1, prop2 }) => {
            // Component logic
          });
          
          // Lazy loading
          const LazyComponent = lazy(() => import('./Component'));
          
          // Performance tracking
          trackInteraction('button-click', 'user-action');
          ```