# ModusWcAccordion

## Prompt 1
**User Question:** I need to build a dynamic content management interface where users can expand different sections to view related information. Each section should have contextual icons and descriptions to help users understand what content they'll find. How should I approach building this with Modus components, and what's the best way to handle user interactions?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this requirement, I need to consider several factors:
1. **Content Organization**: The user needs collapsible sections, which immediately suggests an accordion pattern
2. **Visual Hierarchy**: Icons and descriptions indicate need for rich header content
3. **Interaction Management**: Dynamic expansion suggests need for event handling
4. **User Experience**: Context clues (icons/descriptions) improve discoverability

**Component Analysis:**
I examined the ModusWcAccordion component architecture and determined it follows a container-child pattern:
- **ModusWcAccordion**: Acts as the structural container with minimal direct configuration
- **ModusWcCollapse**: Provides the actual collapsible functionality with rich customization options

**Why I chose these properties:**
- **`options` object on ModusWcCollapse**: This was crucial because it allows comprehensive configuration of each section's appearance (title, description, icon, iconAriaLabel) in a single, structured format
- **`onExpandedChange` event handler**: Essential for tracking user interactions and enabling dynamic content loading or state management
- **`customClass` prop**: Allows styling customization while maintaining component consistency
- **`slot="content"` attribute**: Ensures proper content placement within the collapse component's DOM structure

```tsx
import React, { useState } from 'react';
import { ModusWcAccordion, ModusWcCollapse } from '@trimble-oss/moduswebcomponents-react';

function AccordionExample() {
  // Define collapse options
  const collapseOptions = [
    {
      description: 'Item one description',
      icon: 'alert',
      iconAriaLabel: 'Alert',
      title: 'Item One',
    },
    {
      description: 'Item two description',
      icon: 'alert',
      iconAriaLabel: 'Alert',
      title: 'Item Two',
    },
    {
      description: 'Item three description',
      icon: 'alert',
      iconAriaLabel: 'Alert',
      title: 'Item Three',
    },
  ];
  const [expandedSection, setExpandedSection] = useState(null);
  
  const handleExpandedChange = (e) => {
    const { expanded, index } = e.detail;
    setExpandedSection(expanded ? index : null);
    
    // You can perform additional actions based on which section was toggled
    if (expanded && index === 1) {
      // Do something special when section 2 is expanded
      console.log('Loading additional content for section 2...');
    }
  };
  
  return (
    <ModusWcAccordion onExpandedChange={handleExpandedChange} customClass="demo-accordion">
      <ModusWcCollapse options={collapseOptions[0]}>
        <div slot="content">This is the content for the first section of the accordion.</div>
      </ModusWcCollapse>
      
      <ModusWcCollapse options={collapseOptions[1]}>
        <div slot="content">
          <p>Content for section 2 goes here.</p>
          <ul>
            <li>List item 1</li>
            <li>List item 2</li>
          </ul>
        </div>
      </ModusWcCollapse>
      
      <ModusWcCollapse options={collapseOptions[2]}>
        <div slot="content">This is the third section content.</div>
      </ModusWcCollapse>
    </ModusWcAccordion>
  );
}
```

**Implementation Decisions & Rationale:**

**Component Architecture**: ModusWcAccordion acts as a container with ModusWcCollapse children providing the actual functionality. Each collapse uses an options object for configuration (title, description, icon).

**Event Handling**: `onExpandedChange` provides `{ expanded, index }` details for tracking interactions and implementing conditional logic per section.

**State Management**: Used `useState` to track active sections, enabling dynamic content loading and section-specific behaviors.

**Key Benefits**: Modus 2.0's collapse-based approach offers better flexibility than 1.0's accordion-item pattern, with centralized configuration and proper accessibility support.

---

# ModusWcAlert

## Prompt 1
**User Question:** I'm building a complex application that needs to provide contextual feedback to users across different scenarios - form validation errors, successful operations, system warnings, and informational messages. The feedback should be accessible, dismissible when appropriate, and visually distinct based on severity. How should I approach implementing a comprehensive alert system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this user feedback requirement, I need to consider several factors:
1. **Semantic Communication**: Different types of messages require different visual treatments and accessibility roles
2. **User Control**: Some alerts should be dismissible, others should persist until resolved
3. **Context Awareness**: Alerts should convey urgency and meaning through visual hierarchy
4. **Accessibility**: Screen readers and keyboard users need proper context

**Component Analysis:**
I examined the ModusWcAlert component architecture and determined it's designed for flexible message delivery:
- **Core messaging**: `alert-title` (required) and `alert-description` (optional) provide structured content
- **Visual semantics**: `variant` property maps to standard UI patterns (error, warning, success, info)
- **Accessibility integration**: `role` property ensures proper screen reader behavior
- **User interaction**: `dismissible` boolean controls user agency over message persistence

**Why I chose these properties:**
- **`variant` property**: Essential for visual and semantic distinction - 'error' for validation failures, 'warning' for cautions, 'success' for confirmations, 'info' for general notices
- **`role` attribute**: Critical for accessibility - 'alert' for urgent messages that interrupt, 'status' for polite notifications that don't interrupt
- **`dismissible` boolean**: Provides user control - essential for non-critical messages but should be false for critical system alerts
- **`alert-title` (required)**: Ensures every alert has a clear, scannable message even when description is lengthy
- **`dismissClick` event handler**: Enables cleanup logic and state management when users dismiss alerts

**TypeScript Example:**
```tsx
import React, { useRef, useEffect } from 'react';
import { ModusWcAlert } from '@trimble-oss/moduswebcomponents-react';

const BasicAlert: React.FC = () => {
  const alertRef = useRef<HTMLModusWcAlertElement>(null);
  
  useEffect(() => {
    const element = alertRef.current;
    if (element) {
      const handleDismiss = (e: CustomEvent) => {
        console.log('Alert dismissed');
      };
      
      element.addEventListener('dismissClick', handleDismiss);
      
      return () => {
        element.removeEventListener('dismissClick', handleDismiss);
      };
    }
  }, []);
  
  return (
    <ModusWcAlert
      ref={alertRef}
      alert-title="New message!"
      alert-description="You have 3 new messages."
      variant="info"
      role="status"
      dismissible={true}
    />
  );
};

export default BasicAlert;
```

**Implementation Decisions & Rationale:**

**State Management Strategy:**
- I used `useRef` and `useEffect` to demonstrate proper event listener management in React
- This pattern ensures cleanup and prevents memory leaks when components unmount

**Accessibility Considerations:**
- **Role Selection**: 'status' for success messages (polite, non-interrupting), 'alert' for errors (assertive, interrupting)
- **Required Title**: Ensures screen readers have clear context even when scanning quickly

**Variant Selection Logic:**
- **'info'**: Default for general notifications and neutral information
- **'success'**: Confirms completed actions, builds user confidence
- **'warning'**: Indicates potential issues without blocking workflow
- **'error'**: Critical issues requiring immediate attention

**Event Handling Pattern:**
- The `dismissClick` event provides a clean separation between UI interaction and business logic
- Enables logging, analytics, or state management when users interact with alerts


## Prompt 2
**User Question:** I need to create actionable alerts that go beyond simple notifications - some should include call-to-action buttons for user workflows, others need rich content with formatted text, links, or complex layouts. How can I extend the alert component to support these advanced use cases while maintaining consistency and accessibility?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this advanced alert requirement, I considered:
1. **Actionable vs. Informational**: Some alerts need to guide users to next steps, not just inform
2. **Content Flexibility**: Complex scenarios require more than simple title/description patterns
3. **Workflow Integration**: Alerts should seamlessly connect to broader application flows
4. **Consistent UX**: Custom content shouldn't break established design patterns

**Component Architecture Analysis:**
The ModusWcAlert component supports two key extension mechanisms:
- **`button` slot**: For adding contextual actions without breaking the alert's visual structure
- **`content` slot**: For completely custom content when title/description aren't sufficient

**Why I chose this slot-based approach:**
- **`button` slot**: Maintains alert's semantic structure while adding interaction - perfect for "View Details", "Retry", or "Navigate" actions
- **`content` slot**: Provides complete flexibility when standard patterns don't fit - useful for rich formatting, multiple actions, or complex layouts
- **Slot system**: Preserves component boundaries and styling while allowing customization
- **Independent event handling**: Button actions and dismiss actions operate independently, enabling complex workflows

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcAlert, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

const AlertWithCustomElements: React.FC = () => {
  const [showAlert, setShowAlert] = useState(true);
  
  const handleDismiss = () => {
    setShowAlert(false);
  };
  
  const handleViewAction = () => {
    console.log('View documents action triggered');
    // Navigation or other action logic
  };
  
  if (!showAlert) return null;
  
  return (
    <>
      {/* Alert with custom button */}
      <ModusWcAlert
        alert-title="Action Required"
        alert-description="Please review the new documents"
        variant="warning"
        role="alert"
        dismissible={true}
        onDismissClick={handleDismiss}
      >
        <ModusWcButton
          slot="button"
          color="secondary"
          variant="outlined"
          aria-label="View documents"
          onClick={handleViewAction}
        >
          View Documents
        </ModusWcButton>
      </ModusWcAlert>
      
      {/* Alert with custom content */}
      <ModusWcAlert
        variant="success"
        role="status"
        dismissible={true}
        onDismissClick={handleDismiss}
        style={{ marginTop: '16px' }}
      >
        <div slot="content">
          <strong>Success!</strong> Your profile has been updated.
        </div>
      </ModusWcAlert>
    </>
  );
};

export default AlertWithCustomElements;
```

**Implementation Decisions & Rationale:**

**Slot Usage Strategy:**
- **`button` slot with standard props**: Preserves alert semantics while adding interaction - title and description still provide context for screen readers
- **`content` slot for rich formatting**: When standard patterns don't suffice, complete control allows for complex layouts while maintaining component structure

**State Management Pattern:**
- Used `useState` to control alert visibility, enabling programmatic control after user actions
- Independent handling of dismiss vs. action buttons allows for different workflows

**Accessibility Decisions:**
- **`aria-label` on buttons**: Provides context when button text alone might be insufficient
- **Content slot accessibility**: Even with custom content, maintain semantic HTML structure
- **Role preservation**: Alert's role and structure remain intact regardless of content customization

**Workflow Integration:**
- Button actions can trigger navigation, API calls, or state changes before/after dismissing
- Separation of concerns: dismiss handling vs. business logic in separate functions
- Pattern supports both immediate actions (like navigation) and complex workflows (like form submission)

---

# ModusWcAutocomplete

## Prompt 1
**User Question:** I'm building an e-commerce product search interface within a modal that needs autocomplete functionality with cart integration. Users should search products, see pricing, select multiple items while preventing duplicates, and view totals before confirming. How do I implement this with proper event handling and duplicate prevention?

## Thought Process:
**My Reasoning Process:**

When analyzing this e-commerce autocomplete requirement, I considered:
1. **Modal-Based Search**: Focused product selection without navigation disruption
2. **E-commerce Patterns**: Product pricing display, duplicate prevention, and cart-like totals
3. **Performance**: Debounced search for large product catalogs
4. **Event Handling**: Robust duplicate prevention and data validation

**Component Analysis:**
ModusWcAutocomplete provides e-commerce search capabilities through:
- **Dynamic Filtering**: `items` array with real-time product filtering and pricing display
- **Performance Controls**: `minChars` and `debounceMs` optimize search for large datasets
- **Event System**: `itemSelect` and `inputChange` events manage selection lifecycle
- **State Management**: Controlled `value` property for search input coordination

**Why I chose these properties:**
- **`items`**: Product array with `label`, `value`, `visibleInMenu`, and `price` for rich display
- **`minChars={2}`**: Prevents unnecessary searches on single characters
- **`debounceMs={300}`**: Optimizes performance while maintaining responsiveness
- **`value`**: Controlled search input for state synchronization
- **Event handling**: Custom duplicate prevention with timestamp tracking

## Implementation Decisions & Rationale:

**Key Properties Used:**
- **`items={autocompleteItems}`**: Dynamic product array with pricing information
- **`minChars={2}`**: Performance optimization for product catalog search
- **`debounceMs={300}`**: Balanced responsiveness vs. performance
- **`value={searchValue}`**: Controlled component pattern for React integration

**Event Handling Strategy:**
- **`inputChange`**: CustomEvent with `e.detail.target.value` for search input
- **`itemSelect`**: CustomEvent with `e.detail` containing selected product data
- **Duplicate Prevention**: Timestamp tracking within 100ms window using `useRef`
- **Data Validation**: Price property validation before adding to cart

**Performance Patterns:**
- **Client-side Filtering**: Efficient product search with `toLowerCase()` matching
- **State Optimization**: Clear search after selection, maintain selected products separately
- **Memory Management**: Proper event listener cleanup in `useEffect` return function

**User Experience Features:**
- **Visual Feedback**: Real-time product cards with pricing and removal buttons
- **Cart Totals**: Running price calculations with formatted display
- **Modal Integration**: Focused search experience with confirmation workflow

**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcModal, ModusWcButton, ModusWcAutocomplete } from '@trimble-oss/moduswebcomponents-react';

interface Product {
  label: string;
  value: string;
  visibleInMenu: boolean;
  price: number;
}

const ProductSearchModal: React.FC = () => {
  const modalId = 'product-modal-' + Math.random().toString(36).substring(2, 9);
  const autocompleteRef = useRef<HTMLModusWcAutocompleteElement>(null);
  const lastSelectedRef = useRef<{value: string, timestamp: number} | null>(null);
  
  const [searchValue, setSearchValue] = useState('');
  const [selectedProducts, setSelectedProducts] = useState<Product[]>([]);
  const [autocompleteItems, setAutocompleteItems] = useState<Product[]>([]);

  // Sample products
  const allProducts = [
    { name: 'Laptop Pro', price: 1299 },
    { name: 'Wireless Mouse', price: 49 },
    { name: 'USB-C Hub', price: 79 },
    { name: 'Monitor 4K', price: 399 },
    { name: 'Keyboard', price: 129 },
    { name: 'Webcam HD', price: 89 },
    { name: 'Headphones', price: 199 },
    { name: 'Tablet', price: 449 }
  ];

  // Filter products - restored original logic
  const filterProducts = (searchTerm: string): Product[] => {
    if (searchTerm.length < 2) return [];
    
    return allProducts
      .filter(product => 
        product.name.toLowerCase().includes(searchTerm.toLowerCase())
      )
      .map(product => ({
        label: `${product.name} - $${product.price}`,
        value: product.name,
        visibleInMenu: true,
        price: product.price
      }));
  };

  // Modal controls
  const openModal = () => {
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.showModal();
      setSearchValue('');
      setSelectedProducts([]);
      setAutocompleteItems([]);
      lastSelectedRef.current = null; // Reset tracking
    }
  };

  const closeModal = () => {
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.close();
    }
  };

  // Handle search - restored original logic
  const handleInputChange = (value: string) => {
    setSearchValue(value);
    const filteredItems = filterProducts(value);
    setAutocompleteItems(filteredItems);
  };

  // Add product - fixed to handle double-firing
  const handleItemSelect = (item: any) => {
    console.log("Item selected", item);
    
    // Check for double-firing within 100ms
    const now = Date.now();
    if (lastSelectedRef.current && 
        lastSelectedRef.current.value === item.value && 
        now - lastSelectedRef.current.timestamp < 100) {
      console.log("Duplicate event detected, ignoring");
      return;
    }
    
    // Only process items with complete data (must have price)
    if (!item.price && typeof item.price !== 'number') {
      console.log("Incomplete item data, ignoring:", item);
      return;
    }
    
    // Update tracking
    lastSelectedRef.current = { value: item.value, timestamp: now };
    
    // Check if already selected
    const isAlreadySelected = selectedProducts.some(product => product.value === item.value);
    if (isAlreadySelected) {
      console.log('Product already selected, skipping');
      return;
    }

    // Add the product as-is (it already has correct price from filterProducts)
    console.log("Adding product:", item);
    setSelectedProducts(prev => [...prev, item]);
    
    // Clear search
    setSearchValue('');
    setAutocompleteItems([]);
  };

  // Remove product
  const removeProduct = (productToRemove: Product) => {
    setSelectedProducts(prev => prev.filter(product => product.value !== productToRemove.value));
  };

  // Confirm selection
  const handleConfirm = () => {
    const total = selectedProducts.reduce((sum, product) => sum + product.price, 0);
    const productNames = selectedProducts.map(product => product.value).join(', ');
    
    alert(`🛒 Products Added to Cart!\n\n${selectedProducts.length} items selected:\n${productNames}\n\nTotal: $${total.toFixed(2)}`);
    closeModal();
  };

  // Event listeners - keep minimal fix for duplicates
  useEffect(() => {
    const element = autocompleteRef.current;
    if (!element) return;

    const handleInputChangeEvent = (e: CustomEvent) => {
      const input = e.detail.target as HTMLInputElement;
      handleInputChange(input.value);
    };

    const handleItemSelectEvent = (e: CustomEvent) => {
      // Only prevent default to stop double-firing, but don't over-complicate
      e.preventDefault();
      console.log("Item selected", e.detail);
      handleItemSelect(e.detail);
    };

    element.addEventListener('inputChange', handleInputChangeEvent);
    element.addEventListener('itemSelect', handleItemSelectEvent);

    return () => {
      if (element) {
        element.removeEventListener('inputChange', handleInputChangeEvent);
        element.removeEventListener('itemSelect', handleItemSelectEvent);
      }
    };
  }, []); // Empty dependency array

  return (
    <div style={{ 
      padding: '40px', 
      maxWidth: '600px', 
      margin: '0 auto',
      textAlign: 'center'
    }}>
      <h1 style={{ 
        fontSize: '2rem',
        marginBottom: '16px',
        color: '#0063a3'
      }}>
        🛒 Product Search
      </h1>
      
      <p style={{ fontSize: '1rem', color: '#666', marginBottom: '32px' }}>
        Search and select products to add to your cart
      </p>
      
      <ModusWcButton
        variant="filled"
        color="primary"
        size="lg"
        onClick={openModal}
      >
        🔍 Search Products
      </ModusWcButton>

      {/* Debug info */}
      <div style={{ marginTop: '20px', fontSize: '12px', color: '#888' }}>
        Selected: {selectedProducts.length} items
      </div>

      {/* Modal */}
      <ModusWcModal
        modalId={modalId}
        backdrop="default"
        position="center"
        showClose={true}
      >
        <div slot="header">
          🛒 Search Products
        </div>
        
        <div slot="content" style={{ padding: '20px 0' }}>
          {/* Search Input */}
          <ModusWcAutocomplete
            ref={autocompleteRef}
            label="Product Search"
            placeholder="Type product name (e.g., laptop, mouse)..."
            value={searchValue}
            items={autocompleteItems}
            minChars={2}
            debounceMs={300}
            size="md"
            bordered={true}
          />

          {/* Selected Products */}
          {selectedProducts.length > 0 && (
            <div style={{ marginTop: '24px' }}>
              <h4 style={{ marginBottom: '12px' }}>
                Selected Products ({selectedProducts.length})
              </h4>
              
              {selectedProducts.map((product, index) => (
                <div 
                  key={`${product.value}-${index}`}
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    padding: '12px',
                    margin: '8px 0',
                    background: '#f8f9fa',
                    borderRadius: '6px',
                    border: '1px solid #dee2e6'
                  }}
                >
                  <div style={{ textAlign: 'left' }}>
                    <div style={{ fontWeight: '500' }}>{product.value}</div>
                    <div style={{ fontSize: '14px', color: '#666' }}>
                      ${product.price}
                    </div>
                  </div>
                  
                  <button
                    onClick={() => removeProduct(product)}
                    style={{
                      background: '#dc3545',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      padding: '6px 10px',
                      cursor: 'pointer',
                      fontSize: '12px'
                    }}
                  >
                    Remove
                  </button>
                </div>
              ))}
              
              <div style={{ 
                marginTop: '16px', 
                fontSize: '16px', 
                fontWeight: '600',
                color: '#0063a3'
              }}>
                Total: ${selectedProducts.reduce((sum, product) => sum + product.price, 0)}
              </div>
            </div>
          )}
        </div>
        
        <div slot="footer" style={{ 
          display: 'flex', 
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <div style={{ fontSize: '14px', color: '#666' }}>
            {selectedProducts.length} product{selectedProducts.length !== 1 ? 's' : ''} selected
          </div>
          
          <div style={{ display: 'flex', gap: '8px' }}>
            <ModusWcButton
              variant="outlined"
              color="secondary"
              onClick={closeModal}
            >
              Cancel
            </ModusWcButton>
            <ModusWcButton
              variant="filled"
              color="primary"
              onClick={handleConfirm}
              disabled={selectedProducts.length === 0}
            >
              Add to Cart ({selectedProducts.length})
            </ModusWcButton>
          </div>
        </div>
      </ModusWcModal>
    </div>
  );
};

export default ProductSearchModal;
```

**Implementation Decisions & Rationale:**

**Multi-Context Architecture:**
- **Context-Specific Configuration**: Different search contexts (users, products, teams) have unique placeholder text, minimum characters, and selection patterns
- **Independent State Management**: Separate item arrays and selected states prevent conflicts between different search contexts
- **Dynamic Item Management**: Real-time filtering with `visibleInMenu` property enables efficient search result updates

**Performance Optimization Strategy:**
- **Debounced Search**: Different debounce timings (200-300ms) optimize for responsiveness vs. server load
- **Minimum Character Thresholds**: Prevents unnecessary searches on single characters while maintaining usability
- **Efficient Filtering**: Client-side filtering for demonstration, with patterns that extend to server-side search APIs

**User Experience Patterns:**
- **Multi-Select Workflows**: Chip-based selection for team building and product selection scenarios
- **Single-Select Precision**: Direct value setting for contexts requiring single choice selection
- **Visual Feedback**: Loading states, result counts, and preview grids provide clear search progress indication

---

# ModusWcAvatar

## Prompt 1
**User Question:** I need to implement user identity representation throughout my application with consistent visual hierarchy and accessibility. The avatars should adapt to different contexts, support various content types, and provide clear user recognition patterns. How can I build effective avatar systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing avatar requirements: user identity consistency, visual hierarchy establishment, accessibility compliance, contextual scaling, and recognition pattern clarity.

**Component Analysis:**
ModusWcAvatar provides identity representation through `img-src` property, contextual sizing via `size` options, and flexible presentation through `shape` variants.

**Why I chose these properties:**
- **`img-src` and `alt`**: Essential for user representation and accessibility compliance
- **`size` hierarchy**: Enables contextual scaling from compact lists (xs) to prominent profiles (lg)
- **`shape` options**: 'circle' for personal identity, 'square' for organizational or content representation
- **Consistent sizing**: Standardized dimensions ensure visual harmony across different interface contexts
- **`custom-class`**: Enables brand-specific styling while maintaining component structure

**TypeScript Example:**
```tsx
import React from 'react';
import { ModusWcAvatar } from '@trimble-oss/moduswebcomponents-react';

const ProfileAvatar: React.FC = () => {
  return (
    <ModusWcAvatar
      img-src="https://picsum.photos/200/200?random=1"
      alt="Profile picture of Jane Doe"
      size="md"
      shape="circle"
      aria-label="Avatar"
    />
  );
};

export default ProfileAvatar;
```

**Implementation Decisions & Rationale:**

**Size Hierarchy**: Different sizes support visual importance - 'lg' for main profiles, 'md' for lists, 'sm' for compact contexts, 'xs' for dense layouts.

**Shape Semantics**: 'circle' shapes emphasize personal identity, while 'square' shapes work well for brands, teams, or content representation.

**Accessibility Foundation**: Required `alt` text ensures screen reader compatibility and proper user identification across all contexts.

---

# ModusWcBadge

## Prompt 1

**User Question:** I need to implement dynamic visual indicators that communicate real-time status, counts, and categorization in a compact format. The indicators should support semantic meaning through color, adapt to different contexts, provide clear information hierarchy, and properly handle dynamic content updates. How can I build effective badge indicator systems that respond to changing data?

**Agent Answer:**
**My Reasoning Process:**

Analyzing badge requirements: real-time information communication, semantic color meaning, contextual adaptation, visual hierarchy establishment, compact information delivery, and **critical dynamic content rendering** for web components.

**Component Analysis:**
ModusWcBadge provides semantic communication through `color` variants, flexible presentation via `variant` options, contextual sizing through `size` properties, and **requires special handling for dynamic content updates** due to its web component nature.

**Why I chose these properties:**
- **`color` semantics**: Maps directly to meaning - 'success' for completion, 'warning' for attention, 'danger' for errors
- **`variant` flexibility**: 'filled' for prominence, 'text' for subtlety, 'counter' for numerical indicators
- **`size` adaptation**: Contextual scaling for different interface densities and importance levels
- **Consistent meaning**: Color and variant combinations create predictable information patterns
- **Content flexibility**: Supports text, numbers, and icons for comprehensive information delivery
- **`key` property**: **CRITICAL for Modus 2.0** - Forces component re-render when content changes, ensuring web component updates properly reflect new data

**Critical Implementation Note - Why Key Property is Essential:**
In Modus 2.0 web components, the `key` property serves a crucial role in dynamic content updates. Unlike traditional React components, web components may not automatically re-render when their text content changes. The `key` property forces React to unmount and remount the component, ensuring:

1. **Content Synchronization**: Web component internal state aligns with new content
2. **Visual Consistency**: Prevents stale content display in counter badges
3. **Accessibility Updates**: Screen readers receive updated content announcements
4. **Performance Optimization**: Controlled re-rendering only when necessary

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcBadge, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

type BadgeColor = 'primary' | 'secondary' | 'tertiary' | 'high-contrast' | 'success' | 'warning' | 'danger';

const CounterBadgeExample: React.FC = () => {
  const [count, setCount] = useState(0);
  
  const incrementCount = () => {
    setCount(prev => prev + 1);
  };
  
  const resetCount = () => {
    setCount(0);
  };
  
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
      <ModusWcBadge
        key={`counter-${count}`} // Forces re-render when count changes
        color="primary"
        variant="counter"
        size="md"
      >
        {count}
      </ModusWcBadge>
      <ModusWcButton
        variant="filled"
        color="primary"
        onClick={incrementCount}
      >
        Increment
      </ModusWcButton>
      <ModusWcButton
        variant="outlined"
        color="secondary"
        onClick={resetCount}
      >
        Reset
      </ModusWcButton>
    </div>
  );
};

// Status badge example showing different colors and sizes
const StatusBadgeExample: React.FC = () => {
  const statusItems = [
    { label: 'Active', color: 'success' as BadgeColor, size: 'sm' as const },
    { label: 'Pending', color: 'warning' as BadgeColor, size: 'md' as const },
    { label: 'Error', color: 'danger' as BadgeColor, size: 'lg' as const },
    { label: 'Inactive', color: 'secondary' as BadgeColor, size: 'md' as const },
  ];
  
  return (
    <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', alignItems: 'center' }}>
      {statusItems.map((item, index) => (
        <ModusWcBadge
          key={`status-${index}`}
          color={item.color}
          variant="filled"
          size={item.size}
        >
          {item.label}
        </ModusWcBadge>
      ))}
    </div>
  );
};

// Text badge example showing subtle indicators
const TextBadgeExample: React.FC = () => {
  const textItems = [
    { label: 'New', color: 'primary' as BadgeColor },
    { label: 'Updated', color: 'success' as BadgeColor },
    { label: 'Draft', color: 'tertiary' as BadgeColor },
    { label: 'Urgent', color: 'warning' as BadgeColor },
    { label: 'Archived', color: 'secondary' as BadgeColor },
  ];
  
  return (
    <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap', alignItems: 'center' }}>
      {textItems.map((item, index) => (
        <ModusWcBadge
          key={`text-${index}`}
          color={item.color}
          variant="text"
          size="md"
        >
          {item.label}
        </ModusWcBadge>
      ))}
    </div>
  );
};

const BadgesShowcase: React.FC = () => {
  return (
    <div style={{ padding: '24px', display: 'flex', flexDirection: 'column', gap: '24px' }}>
      <div>
        <h3>Counter Badge (with key prop)</h3>
        <p>Counter updates when button is clicked. Uses key prop to force re-render.</p>
        <CounterBadgeExample />
      </div>
      
      <div>
        <h3>Status Badges (filled variant)</h3>
        <p>Different colors and sizes for status indicators.</p>
        <StatusBadgeExample />
      </div>
      
      <div>
        <h3>Text Badges (text variant)</h3>
        <p>Subtle text-only badges for secondary information.</p>
        <TextBadgeExample />
      </div>
    </div>
  );
};

export default BadgesShowcase;
```

**Implementation Decisions & Rationale:**

**Dynamic Content Strategy**: **Key property implementation is mandatory** for counter badges and any dynamic content scenarios. This ensures web components properly update their internal DOM when React state changes.

**Variant Strategy**: 'filled' for high-priority indicators, 'text' for secondary information, 'counter' for numerical data like notifications or counts.

**Semantic Color Mapping**: Color directly correlates to meaning - maintaining user expectations and accessibility through consistent color-meaning associations.

**Content Flexibility**: Supports text, numbers, and icons enabling comprehensive status communication in compact visual formats.

**Web Component Compatibility**: The `key={`counter-${count}`}` pattern ensures Modus 2.0 web components stay synchronized with React state changes, preventing common issues like stale content display or missed updates.


## Prompt 2

**User Question:** How can I create badges with icons and use them in a notification context?

**Agent Answer:**
References:
- **Content**:
  - Badges can contain any valid HTML content including text and icons
  - When using icons, the component provides proper alignment and spacing

- **Usage Patterns**: 
  - Icon + text badges enhance meaning with visual indicators
  - Counter badges can display notification counts
  - Badges are often used in navigation menus, lists, and near interactive elements

**TypeScript Example:**
```tsx
import React from 'react';
import { ModusWcBadge, ModusWcIcon } from '@trimble-oss/moduswebcomponents-react';

interface NotificationItem {
  id: string;
  label: string;
  badgeType: 'counter' | 'status';
  badgeColor: 'primary' | 'secondary' | 'success' | 'warning' | 'danger';
  badgeContent: string;
  iconName?: string;
  count?: number;
}

const NotificationsExample: React.FC = () => {
  const notifications: NotificationItem[] = [
    {
      id: '1',
      label: 'Messages',
      badgeType: 'counter',
      badgeColor: 'danger',
      badgeContent: '',
      count: 5
    },
    {
      id: '2',
      label: 'Project Status',
      badgeType: 'status',
      badgeColor: 'success',
      badgeContent: 'Complete',
      iconName: 'check'
    },
    {
      id: '3',
      label: 'System Updates',
      badgeType: 'status',
      badgeColor: 'warning',
      badgeContent: 'Required',
      iconName: 'exclamation'
    },
    {
      id: '4',
      label: 'Security Alerts',
      badgeType: 'status',
      badgeColor: 'danger',
      badgeContent: 'Critical',
      iconName: 'shield'
    }
  ];
  
  return (
    <div style={{ 
      display: 'flex', 
      flexDirection: 'column', 
      gap: '16px',
      maxWidth: '400px'
    }}>
      {notifications.map(item => (
        <div key={item.id} style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: '12px',
          borderRadius: '4px',
          backgroundColor: '#f5f5f5'
        }}>
          <span>{item.label}</span>
          
          {item.badgeType === 'counter' ? (
            <ModusWcBadge 
              color={item.badgeColor} 
              variant="counter" 
              size="sm"
            >
              {item.count}
            </ModusWcBadge>
          ) : (
            <ModusWcBadge 
              color={item.badgeColor} 
              variant="filled" 
              size="sm"
            >
              {item.iconName && (
                <ModusWcIcon
                  style={{ marginRight: '4px' }}
                  decorative={true}
                  name={item.iconName}
                  size="xs"
                />
              )}
              {item.badgeContent}
            </ModusWcBadge>
          )}
        </div>
      ))}
    </div>
  );
};

export default NotificationsExample;
```

**Notes:**
- When using icons inside badges, add appropriate spacing (margin or padding)
- Counter badges work best with just numbers and minimal padding
- For accessibility, ensure sufficient color contrast between badge text and background
- Consider the badge size appropriate to its context - smaller badges for menu items, larger badges for general UI elements

---

# ModusWcBreadcrumbs

## Prompt 1
**User Question:** I need to implement hierarchical navigation that helps users understand their current location and provides easy paths back to parent levels. The navigation should integrate with routing systems and support complex application structures. How can I build effective breadcrumb navigation systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing breadcrumb requirements: hierarchical location communication, navigation efficiency, route integration, user orientation, and path visualization clarity.

**Component Analysis:**
ModusWcBreadcrumbs provides structured navigation through `items` array configuration, user interaction via `breadcrumbClick` events, and flexible presentation through sizing options.

**Why I chose these properties:**
- **`items` array structure**: Enables dynamic breadcrumb generation from routing data and application state
- **`url` optional property**: Supports both clickable navigation items and current page indicators
- **`breadcrumbClick` event**: Enables routing system integration and custom navigation logic
- **`size` options**: Contextual scaling for different interface densities and importance levels
- **IBreadcrumb interface**: Structured data model ensures consistent breadcrumb behavior across components

**TypeScript Example:**
```tsx
import React, { useRef, useEffect } from 'react';
import { ModusWcBreadcrumbs } from '@trimble-oss/moduswebcomponents-react';

interface IBreadcrumb {
  label: string;
  url?: string;
}

const BreadcrumbNavigation: React.FC = () => {
  const breadcrumbsRef = useRef<HTMLModusWcBreadcrumbsElement>(null);
  
  // Sample breadcrumbs data
  const breadcrumbItems: IBreadcrumb[] = [
    { label: 'Home', url: '/home' },
    { label: 'Products', url: '/products' },
    { label: 'Category', url: '/products/category' },
    { label: 'Current Item' }
  ];
  
  useEffect(() => {
    const handleBreadcrumbClick = (e: CustomEvent<IBreadcrumb>) => {
      if (e.detail.url) {
        console.log('Navigating to:', e.detail.url);
        // Handle navigation here, e.g., with React Router
        // history.push(e.detail.url);
      }
    };
    
    const breadcrumbsElement = breadcrumbsRef.current;
    if (breadcrumbsElement) {
      breadcrumbsElement.addEventListener('breadcrumbClick', handleBreadcrumbClick as EventListener);
      
      return () => {
        breadcrumbsElement.removeEventListener('breadcrumbClick', handleBreadcrumbClick as EventListener);
      };
    }
  }, []);
  
  return (
    <ModusWcBreadcrumbs
      ref={breadcrumbsRef}
      items={breadcrumbItems}
      size="md"
      aria-label="Page navigation"
    />
  );
};

export default BreadcrumbNavigation;
```

**Implementation Decisions & Rationale:**

**Navigation Pattern**: Last breadcrumb represents current location (no URL) while previous items provide navigation paths to parent levels.

**Event Integration**: `breadcrumbClick` events enable seamless routing system integration for programmatic navigation control.

**Accessibility Foundation**: Proper `aria-label` ensures screen reader users understand navigation structure and current location context.



---

# ModusWcButton

## Prompt 1
**User Question:** I need to create a consistent button system across my application that supports different action hierarchies, semantic meanings, and interaction patterns. How should I approach implementing buttons that communicate purpose and importance while maintaining accessibility?

**Agent Answer:**
**My Reasoning Process:**

Analyzing button requirements: action hierarchy (primary/secondary/tertiary), semantic meaning (success/warning/danger), visual consistency, and accessibility compliance.

**Component Analysis:**
ModusWcButton provides comprehensive styling through `variant` (visual hierarchy), `color` (semantic meaning), `size` (contextual scaling), and `shape` (layout flexibility).

**Why I chose these properties:**
- **`variant`**: 'filled' for primary actions, 'outlined' for secondary, 'borderless' for tertiary
- **`color`**: Maps to semantic meaning - 'danger' for destructive actions, 'warning' for caution
- **`size`**: Contextual scaling based on UI density and importance
- **`buttonClick` event**: Clean separation between UI interaction and business logic

**TypeScript Example:**
```tsx
import React from 'react';
import { ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

type ButtonVariant = 'filled' | 'outlined' | 'borderless';
type ButtonColor = 'primary' | 'secondary' | 'tertiary' | 'warning' | 'danger';

interface ButtonDemoProps {
  variant: ButtonVariant;
  disabled?: boolean;
}

const ButtonDemo: React.FC<ButtonDemoProps> = ({ variant, disabled = false }) => {
  // Array of button colors to display
  const colors: ButtonColor[] = ['primary', 'secondary', 'tertiary', 'warning', 'danger'];
  
  const handleButtonClick = (color: string) => {
    console.log(`${variant} ${color} button clicked`);
  };
  
  return (
    <div style={{ marginBottom: '24px' }}>
      <h3>{variant.charAt(0).toUpperCase() + variant.slice(1)} Buttons</h3>
      <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
        {colors.map(color => (
          <ModusWcButton
            key={`${variant}-${color}`}
            variant={variant}
            color={color}
            disabled={disabled}
            size="md"
            aria-label={`${color} button`}
            onClick={() => handleButtonClick(color)}
          >
            {color.charAt(0).toUpperCase() + color.slice(1)}
          </ModusWcButton>
        ))}
      </div>
    </div>
  );
};

const ButtonVariantsShowcase: React.FC = () => {
  return (
    <div>
      <ButtonDemo variant="filled" />
      <ButtonDemo variant="outlined" />
      <ButtonDemo variant="borderless" />
      
      <h3>Disabled Buttons</h3>
      <ButtonDemo variant="filled" disabled={true} />
    </div>
  );
};

export default ButtonVariantsShowcase;
```

**Implementation Decisions & Rationale:**

**Variant Hierarchy**: 'filled' establishes primary actions, 'outlined' for secondary actions, 'borderless' for tertiary or space-constrained contexts.

**Semantic Color Mapping**: Color directly correlates to action meaning - 'danger' for destructive operations, 'warning' for cautionary actions, maintaining user expectations and accessibility.

## Prompt 2

**User Question:** I need to create buttons that combine text and visual icons for improved user recognition and accessibility. The buttons should handle complex interactions, support different layouts, and integrate with form workflows. How can I build comprehensive icon-button systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing icon-button requirements: visual recognition enhancement, accessibility compliance, layout flexibility, interaction complexity, and form integration patterns.

**Component Analysis:**
ModusWcButton supports icon integration through child components, flexible positioning via content order, and comprehensive event handling for complex interaction workflows.

**Why I chose this approach:**
- **Icon child components**: Provides flexible positioning and styling while maintaining button semantics
- **`shape` property**: 'circle' for icon-only buttons, 'square' for compact layouts, 'rectangle' for text-icon combinations
- **Event handling patterns**: Both `useRef/useEffect` and `onClick` approaches for different complexity levels
- **Accessibility integration**: `aria-label` for icon-only buttons ensures screen reader compatibility
  
**TypeScript Example:**
```tsx
import React, { useRef, useEffect } from 'react';
import { ModusWcButton, ModusWcIcon } from '@trimble-oss/moduswebcomponents-react';

// Example component showing different icon buttons with proper event handling
const IconButtonsExample: React.FC = () => {
  // Example of using refs and event listeners
  const downloadButtonRef = useRef<HTMLModusWcButtonElement>(null);
  
  useEffect(() => {
    const handleButtonClick = (e: Event) => {
      console.log('Download started');
      // Your download logic here
    };
    
    const buttonElement = downloadButtonRef.current;
    if (buttonElement) {
      buttonElement.addEventListener('buttonClick', handleButtonClick);
      
      return () => {
        buttonElement.removeEventListener('buttonClick', handleButtonClick);
      };
    }
  }, []);
  
  // Example of using onClick for simpler cases
  const handleAddClick = () => {
    console.log('Add item clicked');
    // Your add logic here
  };
  
  const handleNextClick = () => {
    console.log('Next clicked');
    // Your navigation logic here
  };
  
  return (
    <div>
      <h3>Icon Buttons</h3>
      
      <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', alignItems: 'center' }}>
        {/* Icon-only button (using shape="circle" for a round button) */}
        <ModusWcButton 
          aria-label="Add item"
          shape="circle"
          onClick={handleAddClick}>
          <ModusWcIcon decorative={true} name="add" />
        </ModusWcButton>
        
        {/* Icon left button with ref */}
        <ModusWcButton 
          ref={downloadButtonRef}
          variant="filled" 
          color="primary">
          <ModusWcIcon decorative={true} name="download" />
          Download
        </ModusWcButton>
        
        {/* Icon right button */}
        <ModusWcButton 
          variant="outlined" 
          color="secondary"
          onClick={handleNextClick}>
          Next
          <ModusWcIcon decorative={true} name="arrow_right" />
        </ModusWcButton>
      </div>
      
      <h3>Icon Buttons with Different Shapes</h3>
      <div style={{ display: 'flex', gap: '8px' }}>
        <ModusWcButton 
          shape="square" 
          aria-label="Settings">
          <ModusWcIcon decorative={true} name="settings" />
        </ModusWcButton>
        
        <ModusWcButton 
          shape="circle" 
          aria-label="Notifications">
          <ModusWcIcon decorative={true} name="notifications" />
        </ModusWcButton>
        
        <ModusWcButton 
          shape="rectangle" 
          variant="outlined" 
          aria-label="Search button">
          <ModusWcIcon decorative={true} name="search" />
          Search
        </ModusWcButton>
      </div>
    </div>
  );
};

// Example component demonstrating form submission with buttons
const FormWithButtons: React.FC = () => {
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    console.log('Form submitted');
  };
  
  const handleReset = () => {
    console.log('Form reset');
  };
  
  return (
    <form onSubmit={handleSubmit} style={{ marginTop: '24px' }}>
      <h3>Form Buttons</h3>
      <div style={{ marginBottom: '16px' }}>
        <input type="text" placeholder="Enter your name" style={{ padding: '8px', marginRight: '8px' }} />
      </div>
      
      <div style={{ display: 'flex', gap: '8px' }}>
        <ModusWcButton 
          type="submit" 
          variant="filled" 
          color="primary">
          <ModusWcIcon decorative={true} name="save" />
          Submit
        </ModusWcButton>
        
        <ModusWcButton 
          type="reset" 
          variant="outlined" 
          color="secondary"
          onClick={handleReset}>
          Reset
        </ModusWcButton>
      </div>
    </form>
  );
};

const ButtonsWithIconsDemo: React.FC = () => {
  return (
    <div>
      <IconButtonsExample />
      <FormWithButtons />
    </div>
  );
};

export default ButtonsWithIconsDemo;
```

**Notes:**
- Always provide `aria-label` for icon-only buttons for accessibility
- Set the `decorative` property to `true` on icons inside buttons
- For form buttons, use the appropriate `type` attribute: 'submit', 'reset', or 'button'
- Choose the appropriate button shape based on your design:
  - `rectangle` (default) for standard text buttons
  - `square` for icon buttons in toolbars or grids
  - `circle` for floating action buttons or icon buttons that should stand out
- In React, you can handle button clicks either by:
  1. Using a ref and the native `buttonClick` event (useful for complex interactions)
  2. Using the React `onClick` prop (simpler for most cases)

---

# ModusWcCard

## Prompt 1

**User Question:** I need to display content in card format with flexible layouts for different content types - some need horizontal layouts for thumbnails and text, others need background images with overlay content. How can I create an adaptive card system that handles various content structures while maintaining visual consistency?

**Agent Answer:**
**My Reasoning Process:**

Analyzing card layout needs: content density, visual hierarchy, image integration, and responsive behavior across different content types.

**Component Analysis:**
ModusWcCard supports flexible layouts through `layout` property and slot-based content organization, with `background-figure` enabling overlay patterns.

**Why I chose these properties:**
- **`layout="horizontal"`**: Optimizes for thumbnail-text pairs and content that benefits from side-by-side arrangement
- **`background-figure="true"`**: Enables hero-style cards with overlay content for visual impact
- **Slot system**: Provides structured content areas (header, title, subtitle, actions) while maintaining semantic clarity
- **`bordered` and `custom-class`**: Enable visual differentiation and hover effects for interactive cards

**TypeScript Example:**
```tsx
import React from 'react';
import { ModusWcCard, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface CardItem {
  id: string;
  title: string;
  subtitle: string;
  content: string;
  imageUrl: string;
  type: 'horizontal' | 'background';
}

const CardGallery: React.FC = () => {
  const cards: CardItem[] = [
    {
      id: '1',
      title: 'Horizontal Layout',
      subtitle: 'Side-by-side content',
      content: 'Perfect for displaying an image alongside text content.',
      imageUrl: 'https://picsum.photos/200/200?random=5',
      type: 'horizontal',
    },
    {
      id: '2',
      title: 'Background Image',
      subtitle: 'Overlay content',
      content: 'Text displayed over a full background image.',
      imageUrl: 'https://picsum.photos/200/200?random=2',
      type: 'background',
    },
    {
      id: '3',
      title: 'News Article',
      subtitle: 'Latest updates',
      content: 'Breaking news and important announcements.',
      imageUrl: 'https://picsum.photos/200/200?random=3',
      type: 'horizontal',
    }
  ];
  
  const cardContainerStyle: React.CSSProperties = {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
    gap: '16px',
    padding: '16px'
  };
  
  const hoverShadowClass = {
    transition: 'box-shadow 0.3s ease',
    '&:hover': {
      boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
    }
  };
  
  const imageStyle: React.CSSProperties = {
    width: '100%',
    height: '100%',
    objectFit: 'cover'
  };
  
  const textOverlayStyle: React.CSSProperties = {
    color: 'white',
    textShadow: '0 1px 3px rgba(0, 0, 0, 0.6)'
  };
  
  const backgroundContentStyle: React.CSSProperties = {
    position: 'relative',
    zIndex: 1,
    padding: '16px',
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'flex-end'
  };
  
  return (
    <div style={cardContainerStyle}>
      {cards.map(card => (
        card.type === 'horizontal' ? (
          <ModusWcCard
            key={card.id}
            aria-label={`${card.title} card`}
            layout="horizontal"
            bordered={true}
            custom-class="hover-shadow">
            <figure slot="header" style={{ width: '150px', height: '100%' }}>
              <img style={imageStyle} src={card.imageUrl} alt={`${card.title} image`} />
            </figure>
            <div>
              <span slot="title">{card.title}</span>
              <span slot="subtitle">{card.subtitle}</span>
              <p>{card.content}</p>
              <div slot="actions">
                <ModusWcButton aria-label="Learn more">Learn More</ModusWcButton>
              </div>
            </div>
          </ModusWcCard>
        ) : (
          <ModusWcCard
            key={card.id}
            aria-label={`${card.title} card`}
            background-figure={true}
            custom-class="hover-shadow">
            <figure slot="header" style={{ height: '200px' }}>
              <img style={imageStyle} src={card.imageUrl} alt={`${card.title} background`} />
            </figure>
            <div style={backgroundContentStyle}>
              <span slot="title" style={textOverlayStyle}>{card.title}</span>
              <span slot="subtitle" style={textOverlayStyle}>{card.subtitle}</span>
              <p style={textOverlayStyle}>{card.content}</p>
              <div slot="actions">
                <ModusWcButton color="secondary" variant="filled">View</ModusWcButton>
              </div>
            </div>
          </ModusWcCard>
        )
      ))}
    </div>
  );
};

export default CardGallery;
```

**Implementation Decisions & Rationale:**

**Layout Strategy**: Horizontal layout optimizes space for thumbnail-content pairs, while background-figure creates impactful hero cards with overlay content.

**Accessibility Considerations**: Text contrast over background images requires careful color choice and text-shadow for readability.

**Responsive Design**: Cards adapt to different content types through slot-based organization, maintaining semantic structure regardless of layout choice.

---

# ModusWcCheckbox

## Prompt 1
**User Question:** I need to implement form controls that allow users to make binary choices or multiple selections from lists. The controls should be accessible, integrate with form validation, and support different interaction patterns like grouped selections. How should I approach building checkbox functionality?

**Agent Answer:**
**My Reasoning Process:**

Analyzing checkbox requirements: binary choice handling, form integration, accessibility compliance, validation support, and group management patterns.

**Component Analysis:**
ModusWcCheckbox provides controlled state through `value` property, comprehensive event handling via `inputChange/Focus/Blur`, and accessibility features including proper labeling and required field support.

**Why I chose these properties:**
- **`value` boolean**: Controlled component pattern for React state management
- **`label` and accessibility**: Ensures screen reader compatibility and user clarity
- **`required` property**: Integrates with form validation and user experience patterns
- **`indeterminate` state**: Essential for parent-child relationship in grouped checkboxes
- **Event handling**: `inputChange` provides clean separation between UI and business logic

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcCheckbox } from '@trimble-oss/moduswebcomponents-react';

const CheckboxExample: React.FC = () => {
  const [isChecked, setIsChecked] = useState(false);
  const checkboxRef = useRef<HTMLModusWcCheckboxElement>(null);
  
  useEffect(() => {
    const checkbox = checkboxRef.current;
    if (checkbox) {
      const handleChange = (e: CustomEvent) => {
        setIsChecked(e.detail.target.checked);
        console.log('Checkbox value changed:', e.detail.target.checked);
      };
      
      checkbox.addEventListener('inputChange', handleChange);
      
      return () => {
        checkbox.removeEventListener('inputChange', handleChange);
      };
    }
  }, []);
  
  return (
    <ModusWcCheckbox
      ref={checkboxRef}
      aria-label="Terms and conditions"
      label="I agree to the terms and conditions"
      value={isChecked}
      required={true}
      size="md"
    />
  );
};

export default CheckboxExample;
```

**Implementation Decisions & Rationale:**

**Controlled Component Pattern**: React state management via `value` prop ensures predictable behavior and enables form validation integration.

**Accessibility Strategy**: Proper labeling through `label` prop or `aria-label` ensures screen reader compatibility and keyboard navigation support.

**Event Management**: Used `useRef` and `useEffect` for proper event listener lifecycle management, preventing memory leaks in React applications.

**Notes:**
- Use the `indeterminate` state for parent checkboxes when some but not all child options are selected
- Maintain a consistent state management approach for all checkboxes in a group
- For better accessibility, use logical grouping with fieldsets and legends for checkbox groups
- Consider providing select all/none functionality for convenience with larger checkbox groups
- When handling form submission, collect checked values by filtering the options array

---

# ModusWcChip

## Prompt 1
**User Question:** I need to build interactive tag and filter systems where users can add, remove, and interact with compact UI elements. These elements should support different states, visual feedback, and integrate with dynamic content management. How should I implement chip-based interactions?

**Agent Answer:**
**My Reasoning Process:**

Analyzing chip requirements: interactive tagging, removable elements, state management, visual feedback, and dynamic list manipulation patterns.

**Component Analysis:**
ModusWcChip provides dual interaction modes through `chipClick` and `chipRemove` events, state visualization via `active/disabled/hasError`, and flexible styling through `variant` and `size` properties.

**Why I chose these properties:**
- **`showRemove` boolean**: Enables user control over chip persistence in dynamic lists
- **`active` state**: Provides visual feedback for selection-based workflows
- **Event separation**: `chipClick` vs. `chipRemove` enables different interaction patterns
- **`variant` styling**: 'filled' for primary elements, 'outline' for secondary or filter chips
- **State management integration**: Events support React state updates and list manipulation

**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcChip } from '@trimble-oss/moduswebcomponents-react';

interface Tag {
  id: string;
  name: string;
}

const ChipExample: React.FC = () => {
  const [tags, setTags] = useState<Tag[]>([
    { id: '1', name: 'React' },
    { id: '2', name: 'TypeScript' },
    { id: '3', name: 'Modus' }
  ]);
  
  const handleChipRemove = (id: string) => {
    setTags(tags.filter(tag => tag.id !== id));
  };
  
  return (
    <div className="chip-container">
      {tags.map(tag => (
        <ChipWithEvents 
          key={tag.id}
          id={tag.id}
          label={tag.name}
          onRemove={handleChipRemove}
        />
      ))}
    </div>
  );
};

interface ChipProps {
  id: string;
  label: string;
  onRemove: (id: string) => void;
}

const ChipWithEvents: React.FC<ChipProps> = ({ id, label, onRemove }) => {
  const chipRef = useRef<HTMLModusWcChipElement>(null);
  
  useEffect(() => {
    const chip = chipRef.current;
    if (chip) {
      const handleRemove = (e: Event) => {
        e.preventDefault();
        onRemove(id);
      };
      
      chip.addEventListener('chipRemove', handleRemove);
      
      return () => {
        chip.removeEventListener('chipRemove', handleRemove);
      };
    }
  }, [id, onRemove]);
  
  return (
    <ModusWcChip
      ref={chipRef}
      label={label}
      showRemove={true}
      variant="filled"
      size="md"
    />
  );
};

export default ChipExample;
```

**Implementation Decisions & Rationale:**

**Event Architecture**: Separated `chipClick` and `chipRemove` events enable complex interaction patterns while maintaining clean component boundaries.

**State Management**: React state integration through array filtering and mapping provides dynamic list management with predictable updates.

**Accessibility**: Proper keyboard support and screen reader compatibility ensure inclusive user interactions across different interface contexts.

## Prompt 2
**User Question:** How can I create chips with custom content like icons or avatars, and use them in a form as a multi-select component?

**Agent Answer:**
References:
- **Properties**: 
  - All properties from Prompt 1
  - The component supports slotted content for customization
- **Events**: 
  - `chipClick`: CustomEvent<KeyboardEvent | MouseEvent>
  - `chipRemove`: CustomEvent<KeyboardEvent | MouseEvent>
- **Usage Patterns**: 
  - Chip components can include slotted content like icons or avatars
  - Multiple chips can be used together for multi-select functionality
  - Can be used with form submissions for selected options


**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcChip, ModusWcIcon, ModusWcAvatar } from '@trimble-oss/moduswebcomponents-react';

interface User {
  id: string;
  name: string;
  avatar: string;
  selected: boolean;
}

const MultiSelectChips: React.FC = () => {
  const [users, setUsers] = useState<User[]>([
    { id: '1', name: 'John Doe', avatar: 'https://randomuser.me/api/portraits/men/1.jpg', selected: false },
    { id: '2', name: 'Jane Smith', avatar: 'https://randomuser.me/api/portraits/women/2.jpg', selected: true },
    { id: '3', name: 'Mike Johnson', avatar: 'https://randomuser.me/api/portraits/men/3.jpg', selected: true }
  ]);
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const selectedUsers = users.filter(user => user.selected);
    console.log('Selected users:', selectedUsers);
    // Process form submission with selected users
  };
  
  const toggleUser = (userId: string) => {
    setUsers(users.map(user => 
      user.id === userId ? { ...user, selected: !user.selected } : user
    ));
  };
  
  const removeUser = (userId: string) => {
    setUsers(users.map(user => 
      user.id === userId ? { ...user, selected: false } : user
    ));
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <h3>Select Team Members:</h3>
      
      <div className="available-users">
        {users.filter(user => !user.selected).map(user => (
          <button 
            key={user.id} 
            type="button"
            onClick={() => toggleUser(user.id)}
            className="user-option">
            <img src={user.avatar} alt={user.name} width="24" height="24" />
            {user.name}
          </button>
        ))}
      </div>
      
      <div className="selected-chips">
        {users.filter(user => user.selected).map(user => (
          <UserChip 
            key={user.id}
            user={user}
            onRemove={() => removeUser(user.id)}
          />
        ))}
      </div>
      
      <button type="submit">Save Team</button>
    </form>
  );
};

interface UserChipProps {
  user: User;
  onRemove: () => void;
}

const UserChip: React.FC<UserChipProps> = ({ user, onRemove }) => {
  const chipRef = useRef<HTMLModusWcChipElement>(null);
  
  useEffect(() => {
    const chip = chipRef.current;
    if (chip) {
      const handleRemove = () => {
        onRemove();
      };
      
      chip.addEventListener('chipRemove', handleRemove);
      
      return () => {
        chip.removeEventListener('chipRemove', handleRemove);
      };
    }
  }, [onRemove]);
  
  return (
    <ModusWcChip
      ref={chipRef}
      label={user.name}
      showRemove={true}
      variant="outline"
      size="md"
    >
      <ModusWcAvatar
        imgSrc={user.avatar}
        alt={user.name}
        size="xs"
      />
    </ModusWcChip>
  );
};

export default MultiSelectChips;
```

**Notes:**
- When using chips with avatars or icons, they should be placed as children of the ModusWcChip component
- For multi-select functionality, maintain the selection state in the parent React component
- The examples show how to use chips both as options selection and as display of selected items
- For form integration, chips represent selected values that can be submitted with the form
- Custom styling can be applied to the chip container to control layout (e.g., flex container for wrapping)
- For better accessibility, ensure the selected state is correctly communicated (e.g., using `active` prop or ARIA attributes)

---

# ModusWcCollapse  

### **User Question:**
I need to create a FAQ section for my application where users can expand and collapse individual questions to find answers. The FAQ should be organized by categories (general, technical, billing) with different icons for each type, and some questions should start expanded by default. How can I implement this using ModusWcCollapse?

### **Agent Answer:**

**My Reasoning Process:**

When analyzing this FAQ requirement, I considered:
1. **Progressive Disclosure**: Users should be able to focus on relevant questions without information overload
2. **Visual Organization**: Different question categories need clear visual differentiation  
3. **State Management**: Individual control over each FAQ item's expanded state
4. **User Experience**: Intuitive interaction patterns with proper feedback

**Component Analysis:**
ModusWcCollapse is perfectly suited for FAQ implementations because it provides:
- **Individual State Control**: Each FAQ can be independently expanded/collapsed
- **Rich Header Configuration**: Title, description, and icons can categorize content clearly
- **Event Integration**: `expandedChange` events enable proper React state synchronization
- **Visual Flexibility**: Border styling and custom classes for category differentiation

**Why I chose these properties:**
- **`expanded` control**: Enables controlled component pattern for reliable state management
- **`options` configuration**: Provides structured headers with category-specific icons and descriptions  
- **`bordered` styling**: Creates clear visual separation between FAQ items
- **`customClass`**: Allows category-based styling (e.g., `faq-technical`, `faq-billing`)
- **Event handling**: Maintains React state synchronization for dynamic interactions

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcCollapse } from '@trimble-oss/moduswebcomponents-react';

interface FAQItem {
  id: string;
  question: string;
  answer: string;
  category: 'general' | 'technical' | 'billing';
  isExpanded: boolean;
}

const FAQSection: React.FC = () => {
  const [faqItems, setFaqItems] = useState<FAQItem[]>([
    {
      id: 'faq-1',
      question: 'How do I create an account?',
      answer: 'To create an account, click the "Sign Up" button in the top right corner...',
      category: 'general',
      isExpanded: false
    },
    {
      id: 'faq-2',
      question: 'What payment methods do you accept?',
      answer: 'We accept all major credit cards (Visa, MasterCard, American Express)...',
      category: 'billing',
      isExpanded: false
    },
    {
      id: 'faq-3',
      question: 'How do I integrate the API?',
      answer: 'Our API uses REST architecture with JSON responses...',
      category: 'technical',
      isExpanded: true // Pre-expanded for important technical info
    }
  ]);

  const handleFAQToggle = (faqId: string, expanded: boolean) => {
    setFaqItems(prev => 
      prev.map(item => 
        item.id === faqId 
          ? { ...item, isExpanded: expanded }
          : item
      )
    );
  };

  return (
    <section style={{ maxWidth: '800px', margin: '0 auto' }}>
      <h2>Frequently Asked Questions</h2>
      
      <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
        {faqItems.map((faq) => (
          <ModusWcCollapse
            key={faq.id}
            collapseId={faq.id}
            bordered={true}
            expanded={faq.isExpanded}
            customClass={`faq-${faq.category}`}
            options={{
              title: faq.question,
              description: `${faq.category.charAt(0).toUpperCase() + faq.category.slice(1)} FAQ`,
              icon: faq.category === 'technical' ? 'code' : 
                    faq.category === 'billing' ? 'credit_card' : 'help'
            }}
            onExpandedChange={(e: CustomEvent<{ expanded: boolean }>) => {
              handleFAQToggle(faq.id, e.detail.expanded);
            }}
          >
            <div slot="content" style={{ padding: '20px', backgroundColor: '#fff' }}>
              <p style={{ margin: 0, lineHeight: '1.6', color: '#444' }}>
                {faq.answer}
              </p>
            </div>
          </ModusWcCollapse>
        ))}
      </div>
    </section>
  );
};
```

### **Implementation Decisions & Rationale:**

**FAQ Organization Strategy:**
- **Category-Based Icons**: Technical questions use 'code' icon, billing uses 'credit_card', general uses 'help' for immediate visual recognition
- **Default State Management**: Critical information (API integration) starts expanded to provide immediate access to important technical details
- **Descriptive Headers**: Each FAQ includes both the question and a category label for clear content organization

**User Experience Patterns:**
- **Individual Control**: Each FAQ operates independently, allowing users to keep multiple sections open for comparison
- **Visual Consistency**: Bordered styling and consistent spacing creates a clean, organized appearance
- **State Persistence**: React state management ensures UI remains consistent with user interactions

**Content Architecture:**
- **Structured Data**: TypeScript interfaces ensure type safety and consistent data structure across FAQ items
- **Controlled Components**: `expanded` state is managed in React, providing reliable state synchronization
- **Semantic HTML**: Proper slot usage (`content`) maintains accessibility and semantic structure

**Scalability Considerations:**
- **Category System**: Easy to add new FAQ categories by extending the union type and icon mapping
- **Dynamic Content**: FAQ items can be loaded from APIs or CMS systems while maintaining the same interaction patterns
- **Performance**: Component-level state management avoids unnecessary re-renders of unrelated FAQ items

This implementation provides a robust, user-friendly FAQ system that scales well and maintains excellent UX patterns for progressive disclosure of information.

---

# ModusWcDate

## Prompt 1
**User Question:** How can I implement a date input field with validation in my React application using the Modus Date component?

**Agent Answer:**
References:
- **Properties**: 
  - `value`: string - The value of the control in ISO 8601 format (yyyy-mm-dd)
  - `label`: string - The text to display within the label
  - `min`: string - Minimum date value
  - `max`: string - Maximum date value
  - `required`: boolean - Whether a value is required (default: false)
  - `disabled`: boolean - Whether the form control is disabled (default: false)
  - `readOnly`: boolean - Whether the value is editable (default: false)
  - `bordered`: boolean - Indicates that the input should have a border (default: true)
  - `size`: "sm" | "md" | "lg" - The size of the input (default: "md")
  - `feedback`: IInputFeedbackProp - Feedback object with level ('error' | 'info' | 'success' | 'warning') and message
- **Events**: 
  - `inputChange`: InputEvent - Emitted when the input value changes
  - `inputBlur`: FocusEvent - Emitted when the input loses focus
  - `inputFocus`: FocusEvent - Emitted when the input gains focus
- **Usage Patterns**: Date fields for forms, date range selection, appointment scheduling


**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcDate } from '@trimble-oss/moduswebcomponents-react';

interface DateFormValues {
  startDate: string;
  endDate: string;
}

interface DateValidationErrors {
  startDate?: string;
  endDate?: string;
}

const DateInputExample: React.FC = () => {
  const [formValues, setFormValues] = useState<DateFormValues>({
    startDate: '',
    endDate: ''
  });
  
  const [errors, setErrors] = useState<DateValidationErrors>({});
  const startDateRef = useRef<HTMLModusWcDateElement>(null);
  const endDateRef = useRef<HTMLModusWcDateElement>(null);
  
  // Get today's date in yyyy-mm-dd format
  const today = new Date().toISOString().split('T')[0];
  
  useEffect(() => {
    const startDateElement = startDateRef.current;
    const endDateElement = endDateRef.current;
    
    if (startDateElement) {
      const handleStartDateChange = () => {
        // Get the value directly from the component
        const newStartDate = startDateElement.value || '';
        
        setFormValues(prev => ({
          ...prev,
          startDate: newStartDate
        }));
        
        // Clear the error if a value is provided
        if (newStartDate !== '') {
          setErrors(prev => ({ ...prev, startDate: undefined }));
          
          // Check if start date is after end date
          if (formValues.endDate && newStartDate > formValues.endDate) {
            setErrors(prev => ({ ...prev, endDate: 'End date must be after start date' }));
          } else if (errors.endDate === 'End date must be after start date') {
            setErrors(prev => ({ ...prev, endDate: undefined }));
          }
        }
      };
      
      startDateElement.addEventListener('inputChange', handleStartDateChange);
      
      return () => {
        startDateElement.removeEventListener('inputChange', handleStartDateChange);
      };
    }
    
    if (endDateElement) {
      const handleEndDateChange = () => {
        // Get the value directly from the component
        const newEndDate = endDateElement.value || '';
        
        setFormValues(prev => ({
          ...prev,
          endDate: newEndDate
        }));
        
        // Clear the error if a value is provided
        if (newEndDate !== '') {
          setErrors(prev => ({ ...prev, endDate: undefined }));
          
          // Check if end date is before start date
          if (formValues.startDate && newEndDate < formValues.startDate) {
            setErrors(prev => ({ ...prev, endDate: 'End date must be after start date' }));
          } else if (errors.endDate === 'End date must be after start date') {
            setErrors(prev => ({ ...prev, endDate: undefined }));
          }
        }
      };
      
      endDateElement.addEventListener('inputChange', handleEndDateChange);
      
      return () => {
        endDateElement.removeEventListener('inputChange', handleEndDateChange);
      };
    }
  }, [formValues.startDate, formValues.endDate, errors.startDate, errors.endDate]);
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validate form before submission
    const newErrors: DateValidationErrors = {};
    
    if (!formValues.startDate) {
      newErrors.startDate = 'Start date is required';
    }
    
    if (!formValues.endDate) {
      newErrors.endDate = 'End date is required';
    } else if (formValues.startDate && formValues.endDate < formValues.startDate) {
      newErrors.endDate = 'End date must be after start date';
    }
    
    setErrors(newErrors);
    
    // If no errors, process form submission
    if (Object.keys(newErrors).length === 0) {
      console.log('Form submitted with values:', formValues);
      // Process form submission
    }
  };
  
  return (
    <form onSubmit={handleSubmit} className="date-range-form">
      <h3>Select Date Range</h3>
      
      <div className="form-group">
        <ModusWcDate
          ref={startDateRef}
          label="Start Date"
          required={true}
          min={today}
          value={formValues.startDate}
          feedback={errors.startDate ? { level: 'error', message: errors.startDate } : undefined}
        />
      </div>
      
      <div className="form-group">
        <ModusWcDate
          ref={endDateRef}
          label="End Date"
          required={true}
          min={formValues.startDate || today}
          value={formValues.endDate}
          feedback={errors.endDate ? { level: 'error', message: errors.endDate } : undefined}
        />
      </div>
      
      <button type="submit">Submit</button>
    </form>
  );
};

export default DateInputExample;
```

**Notes:**
- The Date component uses the ISO 8601 format (`yyyy-mm-dd`) for date values
- Use the `min` and `max` properties to restrict date selection to a valid range
- The component supports form validation with the `feedback` property for displaying error messages
- For proper validation, use event listeners to capture input changes and validate in your React component
- Remember to clean up event listeners in the `useEffect` return function to prevent memory leaks


---

# ModusWcDivider

## Prompt 1
**User Question:** I'm building a complex dashboard interface that combines different data visualizations, user controls, and content sections. The layout needs clear visual separation to maintain user focus and hierarchy - some sections should be strongly divided while others need subtle separation with text indicators. How should I approach implementing a comprehensive visual separation system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this layout separation requirement, I need to consider:
1. **Visual Hierarchy**: Different content sections require different levels of separation intensity
2. **Layout Context**: Horizontal vs vertical layouts demand different divider orientations
3. **Content Labeling**: Some separations benefit from descriptive text to guide user understanding
4. **Responsive Behavior**: Dividers should adapt to container constraints and responsive breakpoints

**Component Analysis:**
I examined the ModusWcDivider component architecture and found it's designed for flexible visual separation:
- **Orientation control**: `orientation` property handles both horizontal and vertical separation needs
- **Visual hierarchy**: `color` property provides semantic intensity levels from subtle tertiary to prominent high-contrast
- **Content integration**: `content` property allows descriptive text within dividers for contextual labeling
- **Flexible positioning**: `position` property controls text alignment within content dividers

**Why I chose these properties:**
- **`orientation` property**: Essential for layout context - 'horizontal' for stacking content vertically, 'vertical' for side-by-side layouts
- **`color` property**: Critical for visual hierarchy - 'tertiary' for subtle separation, 'primary' for prominent divisions, semantic colors for contextual meaning
- **`content` text**: Valuable for user guidance in complex interfaces - helps users understand section relationships and transitions
- **`position` control**: Improves content divider aesthetics and scanning - 'center' for balanced presentation, 'start'/'end' for specific emphasis
- **`responsive` boolean**: Ensures consistent behavior across device sizes and container changes

**TypeScript Example:**
```tsx
import React from 'react';
import { ModusWcDivider } from '@trimble-oss/moduswebcomponents-react';

const DividerExample: React.FC = () => {
  return (
    <div style={{ padding: '20px', maxWidth: '800px' }}>
      <h1>Modus Divider Examples</h1>
      
      {/* Horizontal Dividers */}
      <div style={{ backgroundColor: '#f5f5f5', padding: '20px', marginBottom: '20px' }}>
        <h2>Section 1: User Profile</h2>
        <p>User information and settings go here.</p>
      </div>
      
      <ModusWcDivider 
        orientation="horizontal"
        color="danger"
      />
      
      <div style={{ backgroundColor: '#e8f4f8', padding: '20px', marginTop: '20px', marginBottom: '20px' }}>
        <h2>Section 2: Account Details</h2>
        <p>Account settings and preferences.</p>
      </div>
      
      <ModusWcDivider 
        orientation="horizontal"
        color="success"
        content="PAYMENT INFORMATION"
        position="center"
      />
      
      <div style={{ backgroundColor: '#f0f8f0', padding: '20px', marginTop: '20px', marginBottom: '20px' }}>
        <h2>Section 3: Billing</h2>
        <p>Payment methods and billing history.</p>
      </div>
      
      {/* Vertical Dividers */}
      <h3>Vertical Layout Example</h3>
      <div style={{ display: 'flex', height: '200px', gap: '0', marginTop: '20px' }}>
        <div style={{ flex: 1, backgroundColor: '#fff2e6', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <h4>Left Panel</h4>
          <p>Navigation menu</p>
        </div>
        
        <ModusWcDivider 
          orientation="vertical"
          color="secondary"
        />
        
        <div style={{ flex: 2, backgroundColor: '#e6f3ff', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <h4>Main Content</h4>
          <p>Primary content area</p>
        </div>
        
        <ModusWcDivider 
          orientation="vertical"
          color="warning"
        />
        
        <div style={{ flex: 1, backgroundColor: '#f0e6ff', padding: '20px', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <h4>Right Panel</h4>
          <p>Additional tools</p>
        </div>
      </div>
    </div>
  );
};

export default DividerExample;
```

**Implementation Decisions & Rationale:**

**Visual Hierarchy Strategy:**
- **Primary dividers**: For major section boundaries that require strong visual separation
- **Secondary dividers**: For related but distinct content areas in multi-column layouts
- **Tertiary dividers**: For subtle internal organization without overwhelming the interface

**Layout Pattern Selection:**
- **Horizontal dividers**: Used between vertically stacked sections, common in dashboard main flow
- **Vertical dividers**: Essential for side-by-side content in responsive flex layouts
- **Content dividers**: Provide contextual transitions that help users understand section relationships

**Accessibility Integration:**
- **`aria-label` attributes**: Ensure screen readers understand the purpose of visual separations
- **Semantic meaning**: Divider placement and styling reinforce content hierarchy for all users
- **Responsive behavior**: Maintains separation effectiveness across different viewport sizes

---

# ModusWcIcon

## Prompt 1
**User Question:** I'm developing a complex enterprise application that needs consistent iconography across multiple interface patterns - navigation elements, status indicators, interactive buttons, data visualization markers, and contextual actions. The icons should be accessible, scalable, and semantically meaningful. How should I approach implementing a comprehensive icon system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive iconography requirement, I considered:
1. **Semantic Clarity**: Icons must communicate meaning instantly across different user contexts
2. **Accessibility Standards**: Visual elements need proper screen reader support and keyboard navigation
3. **Visual Hierarchy**: Different icon sizes and treatments for various interface roles
4. **Interaction Patterns**: Distinguishing between decorative icons and actionable elements

**Component Analysis:**
I examined the ModusWcIcon component architecture and found it's designed for flexible semantic iconography:
- **Semantic naming**: `name` property maps to standardized icon library with consistent naming conventions
- **Scale flexibility**: `size` property provides appropriate scaling for different interface contexts
- **Accessibility control**: `decorative` boolean distinguishes between meaningful and ornamental icons
- **Styling integration**: Works with CSS for color and styling while maintaining semantic structure

**Why I chose these properties:**
- **`name` property**: Essential for semantic consistency - using standardized icon names ensures visual language coherence across the application
- **`size` variants**: Critical for visual hierarchy - 'xs' for inline indicators, 'sm' for compact interfaces, 'md' for standard actions, 'lg' for prominent features
- **`decorative` boolean**: Vital for accessibility - 'true' hides purely visual icons from screen readers, 'false' ensures meaningful icons are announced
- **`aria-label` integration**: Provides contextual meaning when icons convey specific information or actions
- **CSS color control**: Enables semantic color coding while maintaining component structure integrity

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcIcon, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface IconSystemProps {
  // Props could be added for theme or context
}

const EnterpriseIconSystem: React.FC<IconSystemProps> = () => {
  const [notificationCount, setNotificationCount] = useState(3);
  const [currentStatus, setCurrentStatus] = useState<'success' | 'warning' | 'error'>('success');
  
  // Status-aware icon configuration
  const getStatusIcon = (status: string) => {
    const statusConfig = {
      success: { name: 'check_circle', color: '#0ca45c', label: 'Operation successful' },
      warning: { name: 'warning', color: '#ffbe00', label: 'Warning condition' },
      error: { name: 'error', color: '#d54309', label: 'Error detected' },
      info: { name: 'info', color: '#0063a3', label: 'Information available' }
    };
    return statusConfig[status] || statusConfig.info;
  };
  
  const statusConfig = getStatusIcon(currentStatus);
  
  const handleActionClick = (action: string) => {
    console.log(`Action triggered: ${action}`);
    // Handle specific action logic
  };
  
  return (
    <div className="enterprise-app-layout">
             {/* Navigation with semantic icons */}
       <nav className="app-navigation" style={{ display: 'flex', gap: '24px', padding: '16px', borderBottom: '1px solid #e0e0e0' }}>
         <ModusWcButton 
           variant="borderless"
           size="md"
           onClick={() => handleActionClick('dashboard')}
           aria-label="Navigate to dashboard"
         >
           <ModusWcIcon name="dashboard" size="sm" decorative={true} />
           <span>Dashboard</span>
         </ModusWcButton>
         
         <ModusWcButton 
           variant="borderless"
           size="md"
           onClick={() => handleActionClick('projects')}
           aria-label="Navigate to projects"
         >
           <ModusWcIcon name="folder" size="sm" decorative={true} />
           <span>Projects</span>
         </ModusWcButton>
         
         <div style={{ position: 'relative' }}>
           <ModusWcButton 
             variant="borderless"
             size="md"
             onClick={() => handleActionClick('notifications')}
             aria-label={`Notifications - ${notificationCount} unread`}
           >
             <ModusWcIcon name="notifications" size="sm" decorative={true} />
             <span>Notifications</span>
           </ModusWcButton>
           {notificationCount > 0 && (
             <span className="notification-badge" style={{ 
               position: 'absolute', 
               top: '-8px', 
               right: '-8px', 
               background: '#d54309', 
               color: 'white', 
               borderRadius: '50%', 
               padding: '2px 6px', 
               fontSize: '12px' 
             }}>
               {notificationCount}
             </span>
           )}
         </div>
         
         <ModusWcButton 
           variant="borderless"
           size="md"
           onClick={() => handleActionClick('settings')}
           aria-label="Open settings"
         >
           <ModusWcIcon name="settings" size="sm" decorative={true} />
           <span>Settings</span>
         </ModusWcButton>
       </nav>
      
      {/* Status indicator section */}
      <section className="status-panel" style={{ padding: '16px', display: 'flex', alignItems: 'center', gap: '12px' }}>
        <ModusWcIcon 
          name={statusConfig.name} 
          size="md" 
          decorative={false}
          aria-label={statusConfig.label}
          style={{ color: statusConfig.color }}
        />
                 <span>System Status: {currentStatus}</span>
         
         <ModusWcButton 
           variant="outlined"
           color="secondary"
           size="sm"
           onClick={() => setCurrentStatus(currentStatus === 'success' ? 'warning' : 'success')}
           style={{ marginLeft: '16px' }}
         >
           Toggle Status
         </ModusWcButton>
      </section>
      
      {/* Action toolbar with size hierarchy */}
      <section className="action-toolbar" style={{ padding: '16px', display: 'flex', gap: '16px', alignItems: 'center' }}>
        <h3>Document Actions</h3>
        
                 {/* Primary actions - larger icons */}
         <div className="primary-actions" style={{ display: 'flex', gap: '12px' }}>
           <ModusWcButton 
             variant="filled"
             color="primary"
             size="lg"
             onClick={() => handleActionClick('create')}
             aria-label="Create new document"
           >
             <ModusWcIcon name="add" size="lg" decorative={true} />
             Create
           </ModusWcButton>
           
           <ModusWcButton 
             variant="filled"
             color="primary"
             size="lg"
             onClick={() => handleActionClick('upload')}
             aria-label="Upload documents"
           >
             <ModusWcIcon name="upload" size="lg" decorative={true} />
             Upload
           </ModusWcButton>
         </div>
        
                 {/* Secondary actions - standard icons */}
         <div className="secondary-actions" style={{ display: 'flex', gap: '8px', marginLeft: '24px' }}>
           <ModusWcButton 
             variant="outlined"
             color="secondary"
             size="md"
             shape="circle"
             onClick={() => handleActionClick('search')}
             aria-label="Search documents"
           >
             <ModusWcIcon name="search" size="md" decorative={true} />
           </ModusWcButton>
           
           <ModusWcButton 
             variant="outlined"
             color="secondary"
             size="md"
             shape="circle"
             onClick={() => handleActionClick('filter')}
             aria-label="Filter results"
           >
             <ModusWcIcon name="filter" size="md" decorative={true} />
           </ModusWcButton>
           
           <ModusWcButton 
             variant="outlined"
             color="secondary"
             size="md"
             shape="circle"
             onClick={() => handleActionClick('sort')}
             aria-label="Sort documents"
           >
             <ModusWcIcon name="sort" size="md" decorative={true} />
           </ModusWcButton>
         </div>
        
        {/* Inline indicators - small icons */}
        <div className="inline-indicators" style={{ marginLeft: 'auto', display: 'flex', gap: '16px', alignItems: 'center' }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <ModusWcIcon name="cloud" size="xs" decorative={false} aria-label="Cloud sync enabled" />
            Synced
          </span>
          
          <span style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <ModusWcIcon name="lock" size="xs" decorative={false} aria-label="Document secured" />
            Secured
          </span>
        </div>
      </section>
    </div>
  );
};

export default EnterpriseIconSystem;
```

**Implementation Decisions & Rationale:**

**Accessibility Strategy:**
- **Decorative vs. Semantic**: Used `decorative={true}` for icons that accompany text labels, `decorative={false}` for standalone meaningful icons
- **Screen Reader Context**: Applied `aria-label` to buttons and meaningful icons to provide clear context for assistive technology
- **Color Independence**: Ensured icons convey meaning through shape and context, not just color

**Visual Hierarchy Implementation:**
- **Size Progression**: 'xs' for inline status indicators, 'sm' for navigation, 'md' for standard actions, 'lg' for primary actions
- **Semantic Color Coding**: Applied consistent color patterns for status types while maintaining accessibility contrast
- **Layout Integration**: Positioned icons to support scanning patterns and visual flow

**Component Usage Patterns:**
- **Navigation Icons**: Decorative alongside text labels for redundant meaning
- **Status Icons**: Semantic with proper ARIA labels for independent communication
- **Action Icons**: Context-dependent - decorative in buttons with text, semantic when standalone

---

# ModusWcInputFeedback

## Prompt 1
**User Question:** How can I display validation feedback messages for form inputs in my React application using the Modus Input Feedback component?

**Agent Answer:**
References:
- **Properties**: 
  - `level`: "error" | "info" | "success" | "warning" - The feedback level that determines the icon and color
  - `message`: string - The feedback message to display
  - `size`: "sm" | "md" | "lg" - The size of the feedback component (default: "md")
  - `icon`: string - Optional custom Modus icon name to override the default icon for the level
  - `customClass`: string - Custom CSS class to apply to the outer div element
- **Events**: None
- **Usage Patterns**: Used to provide feedback for form inputs such as validation errors, helpful information, or success messages

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcInputFeedback, ModusWcTextInput, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

type FeedbackLevel = 'error' | 'info' | 'success' | 'warning';

interface FeedbackState {
  level?: FeedbackLevel;
  message?: string;
}

const FormWithFeedback: React.FC = () => {
  // Form states for different fields
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [emailFeedback, setEmailFeedback] = useState<FeedbackState>({});
  const [passwordFeedback, setPasswordFeedback] = useState<FeedbackState>({
    level: 'info',
    message: 'Password must be at least 8 characters with one uppercase letter and one number'
  });
  
  // Email validation
  const validateEmail = (value: string) => {
    if (!value) {
      setEmailFeedback({
        level: 'error',
        message: 'Email is required'
      });
      return false;
    } else if (!/\S+@\S+\.\S+/.test(value)) {
      setEmailFeedback({
        level: 'error',
        message: 'Please enter a valid email address'
      });
      return false;
    } else {
      setEmailFeedback({
        level: 'success',
        message: 'Email is valid'
      });
      return true;
    }
  };
  
  // Password validation
  const validatePassword = (value: string) => {
    if (!value) {
      setPasswordFeedback({
        level: 'error',
        message: 'Password is required'
      });
      return false;
    } else if (value.length < 8) {
      setPasswordFeedback({
        level: 'error',
        message: 'Password must be at least 8 characters long'
      });
      return false;
    } else if (!/[A-Z]/.test(value) || !/[0-9]/.test(value)) {
      setPasswordFeedback({
        level: 'warning',
        message: 'Password should contain at least one uppercase letter and one number'
      });
      return true; // Warning doesn't invalidate the form
    } else {
      setPasswordFeedback({
        level: 'success',
        message: 'Password meets requirements'
      });
      return true;
    }
  };
  
  const handleEmailChange = (e: CustomEvent) => {
    const newValue = e.detail.target?.value || '';
    setEmail(newValue);
    validateEmail(newValue);
  };
  
  const handlePasswordChange = (e: CustomEvent) => {
    const newValue = e.detail.target?.value || '';
    setPassword(newValue);
    validatePassword(newValue);
  };
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const isEmailValid = validateEmail(email);
    const isPasswordValid = validatePassword(password);
    
    if (isEmailValid && isPasswordValid) {
      console.log('Form submitted:', { email, password });
      // Process form submission
    }
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <h3>Sign Up</h3>
      
      <div style={{ marginBottom: '20px' }}>
        <ModusWcTextInput
          label="Email"
          type="email"
          value={email}
          required={true}
          onInputChange={handleEmailChange}
          onInputBlur={() => validateEmail(email)}
          feedback={emailFeedback.level ? {
            level: emailFeedback.level,
            message: emailFeedback.message
          } : undefined}
        />
      </div>
      
      <div style={{ marginBottom: '20px' }}>
        <ModusWcTextInput
          label="Password"
          type="password"
          value={password}
          required={true}
          onInputChange={handlePasswordChange}
          onInputBlur={() => validatePassword(password)}
        />
        
        {/* Only render feedback if we have a level */}
        {passwordFeedback.level && (
          <ModusWcInputFeedback
            level={passwordFeedback.level}
            message={passwordFeedback.message}
            size="md"
          />
        )}
      </div>
      
             <ModusWcButton 
         type="submit"
         variant="filled"
         color="primary"
         size="lg"
         disabled={
           !email || 
           !password || 
           emailFeedback.level === 'error' || 
           passwordFeedback.level === 'error'
         }
       >
         Sign Up
       </ModusWcButton>
    </form>
  );
};

export default FormWithFeedback;
```

**Notes:**
- Use appropriate feedback levels based on the context:
  - `error`: For invalid inputs that prevent form submission
  - `warning`: For potential issues that don't prevent submission
  - `info`: For helpful instructions or context
  - `success`: For valid inputs or successful actions
- The component automatically selects appropriate icons based on the feedback level
- You can override the default icon using the `icon` property
- For accessibility, ensure error messages are clear and descriptive
- When used with Modus input components, you can pass feedback directly to those components
- Consider showing feedback only after user interaction (e.g., on blur or submit)


---

# ModusWcInputLabel

## Prompt 1
**User Question:** How can I create accessible form labels with required field indicators using the Modus Input Label component in React?

**Agent Answer:**
References:
- **Properties**: 
  - `labelText`: string - The text to display within the label
  - `forId`: string - The `for` attribute of the label, matching the `id` of the associated input
  - `required`: boolean - Whether the label indicates a required field (default: false)
  - `size`: "sm" | "md" | "lg" - The size of the label (default: "md")
  - `subLabelText`: string - Additional text rendered beneath the main label text
  - `customClass`: string - Additional classes for custom styling
- **Events**: None
- **Usage Patterns**: Used to provide accessible labels for form inputs with consistent styling and support for required field indicators

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcTextInput, ModusWcButton, ModusWcModal } from '@trimble-oss/moduswebcomponents-react';

interface FormData {
  username: string;
  email: string;
  password: string;
  confirmPassword: string;
  phoneNumber: string;
}

interface FeedbackState {
  level?: 'error' | 'info' | 'success' | 'warning';
  message?: string;
}

const ComprehensiveModusForm: React.FC = () => {
  // Form state
  const [formData, setFormData] = useState<FormData>({
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    phoneNumber: ''
  });

  // Feedback states for each field
  const [usernameFeedback, setUsernameFeedback] = useState<FeedbackState>({});
  const [emailFeedback, setEmailFeedback] = useState<FeedbackState>({});
  const [passwordFeedback, setPasswordFeedback] = useState<FeedbackState>({});
  const [confirmPasswordFeedback, setConfirmPasswordFeedback] = useState<FeedbackState>({});
  const [phoneFeedback, setPhoneFeedback] = useState<FeedbackState>({});

  // Modal state
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const modalId = 'success-modal';

  // Validation functions
  const validateUsername = (value: string) => {
    if (!value) {
      setUsernameFeedback({ level: 'error', message: 'Username is required' });
      return false;
    } else if (value.length < 3) {
      setUsernameFeedback({ level: 'error', message: 'Username must be at least 3 characters' });
      return false;
    } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
      setUsernameFeedback({ level: 'error', message: 'Username can only contain letters, numbers, and underscores' });
      return false;
    } else {
      setUsernameFeedback({ level: 'success', message: 'Username is available' });
      return true;
    }
  };

  const validateEmail = (value: string) => {
    if (!value) {
      setEmailFeedback({ level: 'error', message: 'Email is required' });
      return false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      setEmailFeedback({ level: 'error', message: 'Please enter a valid email address' });
      return false;
    } else {
      setEmailFeedback({ level: 'success', message: 'Email format is valid' });
      return true;
    }
  };

  const validatePassword = (value: string) => {
    if (!value) {
      setPasswordFeedback({ level: 'error', message: 'Password is required' });
      return false;
    } else if (value.length < 8) {
      setPasswordFeedback({ level: 'error', message: 'Password must be at least 8 characters' });
      return false;
    } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
      setPasswordFeedback({ level: 'warning', message: 'Password should contain uppercase, lowercase, and number' });
      return true;
    } else {
      setPasswordFeedback({ level: 'success', message: 'Strong password' });
      return true;
    }
  };

  const validateConfirmPassword = (value: string) => {
    if (!value) {
      setConfirmPasswordFeedback({ level: 'error', message: 'Please confirm your password' });
      return false;
    } else if (value !== formData.password) {
      setConfirmPasswordFeedback({ level: 'error', message: 'Passwords do not match' });
      return false;
    } else {
      setConfirmPasswordFeedback({ level: 'success', message: 'Passwords match' });
      return true;
    }
  };

  const validatePhone = (value: string) => {
    if (!value) {
      setPhoneFeedback({ level: 'info', message: 'Phone number is optional' });
      return true;
    } else if (!/^\+?[\d\s\-\(\)]+$/.test(value)) {
      setPhoneFeedback({ level: 'error', message: 'Please enter a valid phone number' });
      return false;
    } else {
      setPhoneFeedback({ level: 'success', message: 'Phone number is valid' });
      return true;
    }
  };

  // Input change handlers
  const handleUsernameChange = (e: CustomEvent) => {
    const value = e.detail.target?.value || '';
    setFormData(prev => ({ ...prev, username: value }));
    validateUsername(value);
  };

  const handleEmailChange = (e: CustomEvent) => {
    const value = e.detail.target?.value || '';
    setFormData(prev => ({ ...prev, email: value }));
    validateEmail(value);
  };

  const handlePasswordChange = (e: CustomEvent) => {
    const value = e.detail.target?.value || '';
    setFormData(prev => ({ ...prev, password: value }));
    validatePassword(value);
    // Re-validate confirm password if it exists
    if (formData.confirmPassword) {
      validateConfirmPassword(formData.confirmPassword);
    }
  };

  const handleConfirmPasswordChange = (e: CustomEvent) => {
    const value = e.detail.target?.value || '';
    setFormData(prev => ({ ...prev, confirmPassword: value }));
    validateConfirmPassword(value);
  };

  const handlePhoneChange = (e: CustomEvent) => {
    const value = e.detail.target?.value || '';
    setFormData(prev => ({ ...prev, phoneNumber: value }));
    validatePhone(value);
  };

  // Form submission
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const isUsernameValid = validateUsername(formData.username);
    const isEmailValid = validateEmail(formData.email);
    const isPasswordValid = validatePassword(formData.password);
    const isConfirmPasswordValid = validateConfirmPassword(formData.confirmPassword);
    const isPhoneValid = validatePhone(formData.phoneNumber);

    if (isUsernameValid && isEmailValid && isPasswordValid && isConfirmPasswordValid && isPhoneValid) {
      console.log('Form submitted:', formData);
      openSuccessModal();
    }
  };

  // Modal functions
  const openSuccessModal = () => {
    setShowSuccessModal(true);
    setTimeout(() => {
      const modal = document.getElementById(modalId) as HTMLDialogElement;
      if (modal) {
        modal.showModal();
      }
    }, 0);
  };

  const closeSuccessModal = () => {
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.close();
    }
    setShowSuccessModal(false);
  };

  const resetForm = () => {
    setFormData({
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      phoneNumber: ''
    });
    setUsernameFeedback({});
    setEmailFeedback({});
    setPasswordFeedback({});
    setConfirmPasswordFeedback({});
    setPhoneFeedback({});
    closeSuccessModal();
  };

  // Check if form is valid
  const isFormValid = 
    formData.username && 
    formData.email && 
    formData.password && 
    formData.confirmPassword &&
    usernameFeedback.level !== 'error' &&
    emailFeedback.level !== 'error' &&
    passwordFeedback.level !== 'error' &&
    confirmPasswordFeedback.level !== 'error' &&
    phoneFeedback.level !== 'error';

  return (
    <div style={{ padding: '24px', maxWidth: '600px', margin: '0 auto' }}>
      <h1>User Registration</h1>
      <p>Create your account using our comprehensive Modus form system</p>

      <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
        
        <ModusWcTextInput
          label="Username"
          placeholder="Enter your username"
          value={formData.username}
          required={true}
          onInputChange={handleUsernameChange}
          feedback={usernameFeedback.level ? {
            level: usernameFeedback.level,
            message: usernameFeedback.message
          } : undefined}
        />

        <ModusWcTextInput
          label="Email Address"
          type="email"
          placeholder="Enter your email"
          value={formData.email}
          required={true}
          onInputChange={handleEmailChange}
          feedback={emailFeedback.level ? {
            level: emailFeedback.level,
            message: emailFeedback.message
          } : undefined}
        />

        <ModusWcTextInput
          label="Password"
          type="password"
          placeholder="Create a password"
          value={formData.password}
          required={true}
          minLength={8}
          onInputChange={handlePasswordChange}
          feedback={passwordFeedback.level ? {
            level: passwordFeedback.level,
            message: passwordFeedback.message
          } : undefined}
        />

        <ModusWcTextInput
          label="Confirm Password"
          type="password"
          placeholder="Confirm your password"
          value={formData.confirmPassword}
          required={true}
          onInputChange={handleConfirmPasswordChange}
          feedback={confirmPasswordFeedback.level ? {
            level: confirmPasswordFeedback.level,
            message: confirmPasswordFeedback.message
          } : undefined}
        />

        <ModusWcTextInput
          label="Phone Number (Optional)"
          type="tel"
          placeholder="+1 (555) 123-4567"
          value={formData.phoneNumber}
          onInputChange={handlePhoneChange}
          feedback={phoneFeedback.level ? {
            level: phoneFeedback.level,
            message: phoneFeedback.message
          } : undefined}
        />

        <div style={{ display: 'flex', gap: '12px', marginTop: '20px' }}>
          <ModusWcButton
            type="submit"
            variant="filled"
            color="primary"
            size="lg"
            disabled={!isFormValid}
          >
            Create Account
          </ModusWcButton>

          <ModusWcButton
            type="button"
            variant="outlined"
            color="secondary"
            size="lg"
            onClick={resetForm}
          >
            Reset Form
          </ModusWcButton>
        </div>
      </form>

      {/* Success Modal */}
      {showSuccessModal && (
        <ModusWcModal
          modalId={modalId}
          backdrop="static"
          position="center"
          showClose={false}
        >
          <div slot="header">
            <h3 style={{ margin: 0, color: '#0ca45c' }}>Account Created Successfully!</h3>
          </div>
          <div slot="content">
            <p>Welcome, <strong>{formData.username}</strong>!</p>
            <p>Your account has been created with email: <strong>{formData.email}</strong></p>
            <p>You can now start using our platform.</p>
          </div>
          <div slot="footer" style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
            <ModusWcButton
              color="secondary"
              variant="outlined"
              onClick={closeSuccessModal}
            >
              Close
            </ModusWcButton>
            <ModusWcButton
              color="primary"
              variant="filled"
              onClick={() => {
                console.log('Navigate to dashboard');
                closeSuccessModal();
              }}
            >
              Go to Dashboard
            </ModusWcButton>
          </div>
        </ModusWcModal>
      )}
    </div>
  );
};

export default ComprehensiveModusForm;
```

**Notes:**
- Always use the `forId` property to associate the label with its input element for accessibility
- The `required` property adds a visual indicator (typically an asterisk) to show that the field is mandatory
- Use `subLabelText` for additional instructions or context that doesn't fit in the main label
- When used with Modus input components, ensure IDs match between the label and input
- The component works with standard HTML inputs or with Modus form components
- For complex instructions, consider using `aria-describedby` with additional help text elements
- Different sizes (sm, md, lg) can be used to maintain proper visual hierarchy


---

# ModusWcLoader

## Prompt 1
**User Question:** I need to implement visual loading indicators that maintain user engagement during various loading scenarios - from quick operations to complex data processing. The indicators should provide appropriate visual feedback, convey different loading states, and adapt to various contexts. How can I build comprehensive loading indication systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing loading indication requirements: user engagement maintenance, loading state differentiation, visual feedback appropriateness, context adaptation, and operation duration communication.

**Component Analysis:**
ModusWcLoader provides diverse visual feedback through `variant` options, semantic communication via `color` properties, and contextual scaling through `size` configurations.

**Why I chose these properties:**
- **`variant` diversity**: Different animations ('spinner', 'bars', 'dots') convey different loading types and durations
- **`color` semantics**: Maps to loading context - 'primary' for general, 'info' for processing, 'success' for completion states
- **`size` adaptation**: Contextual scaling from inline indicators (xs) to page-level loading (lg)
- **Visual differentiation**: Multiple variants enable loading state distinction and user expectation management
- **No events needed**: Loaders are controlled by external loading states rather than user interaction


**TypeScript Example:**
```tsx
import React, { useState, useEffect } from 'react';
import { ModusWcLoader, ModusWcButton, ModusWcCard } from '@trimble-oss/moduswebcomponents-react';

const LoadingPageDemo: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);

  // Simulate loading for 3 seconds
  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 3000);

    return () => clearTimeout(timer);
  }, []);

  const restartLoading = () => {
    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
    }, 3000);
  };

  if (isLoading) {
    return (
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center', 
        justifyContent: 'center', 
        minHeight: '400px',
        padding: '40px'
      }}>
        <ModusWcLoader 
          variant="spinner" 
          color="primary" 
          size="lg" 
        />
        <p style={{ marginTop: '20px', fontSize: '18px' }}>Loading your dashboard...</p>
      </div>
    );
  }

  return (
    <div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}>
      <h1>Welcome to Your Dashboard</h1>
      
      {/* User Profile Card */}
      <ModusWcCard
        bordered={true}
        layout="vertical"
        padding="normal"
        style={{ marginBottom: '20px' }}
      >
        <div slot="header" style={{ display: 'flex', alignItems: 'center' }}>
          <div style={{
            width: '60px',
            height: '60px',
            borderRadius: '50%',
            backgroundColor: '#0063a3',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'white',
            fontSize: '24px',
            fontWeight: 'bold',
            marginRight: '16px'
          }}>
            JD
          </div>
        </div>
        
        <span slot="title">John Doe</span>
        <span slot="subtitle">Software Engineer</span>
        
        <div>
          <h3>Recent Activity</h3>
          <ul style={{ paddingLeft: '20px' }}>
            <li>Completed project review</li>
            <li>Updated user documentation</li>
            <li>Fixed 3 critical bugs</li>
          </ul>
        </div>

        <div slot="actions" style={{ display: 'flex', gap: '12px' }}>
          <ModusWcButton variant="filled" color="primary">
            View Profile
          </ModusWcButton>
          <ModusWcButton variant="outlined" color="secondary">
            Edit Settings
          </ModusWcButton>
        </div>
      </ModusWcCard>

      {/* Reload Button */}
      <div style={{ textAlign: 'center' }}>
        <ModusWcButton 
          variant="outlined" 
          color="primary" 
          onClick={restartLoading}
        >
          Reload Dashboard
        </ModusWcButton>
      </div>
    </div>
  );
};

export default LoadingPageDemo;
```

**Notes:**
- Always include an `aria-label` attribute for accessibility, as loaders are often used for important UI state changes
- Choose the appropriate loader variant based on the context and loading duration
- Use consistent loader types and colors throughout your application for a cohesive design
- For long-running operations, consider showing progress indicators alongside loaders
- Loaders should be placed in a way that doesn't disrupt the user experience or cause layout shifts
- For full-page loading, center the loader in the viewport and consider a semi-transparent overlay

---

# ModusWcMenu and ModusWcMenuItem

## Prompt 1
**User Question:** I'm developing a comprehensive interface that requires sophisticated menu systems - contextual action menus, hierarchical navigation structures, multi-selection patterns, and adaptive layouts that work across different interaction modes. The menus should provide clear organization, efficient selection patterns, and accessibility compliance. How should I implement a flexible menu system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive menu requirement, I considered:
1. **Context Adaptation**: Different interface areas need different menu behaviors - navigation vs. action menus vs. selection lists
2. **Interaction Patterns**: Users need clear feedback for selection, hover states, and multi-selection workflows
3. **Layout Flexibility**: Menus must work in various containers - sidebars, dropdowns, toolbars, and mobile interfaces
4. **Accessibility Standards**: Menu structures must support keyboard navigation and screen reader interaction

**Component Analysis:**
I examined the ModusWcMenu and ModusWcMenuItem component architecture and found it's designed for flexible menu construction:
- **Layout Control**: `orientation` property supports both horizontal toolbar menus and vertical navigation patterns
- **Visual Hierarchy**: `size` property adapts menu density for different interface contexts
- **Item Management**: ModusWcMenuItem provides comprehensive state management (selected, focused, disabled) with icon and sub-label support
- **Event Architecture**: `itemSelect` events enable selection tracking and workflow integration

**Why I chose these properties:**
- **`orientation` flexibility**: Essential for layout adaptation - 'vertical' for navigation, 'horizontal' for toolbars and action bars
- **`size` variants**: Critical for interface density - 'sm' for compact interfaces, 'lg' for touch-friendly navigation
- **MenuItem state management**: Provides complete user feedback - 'selected' for current state, 'focused' for keyboard navigation, 'disabled' for conditional access
- **Icon and labeling**: Enables semantic menu construction with visual recognition and hierarchical information
- **Event handling**: `itemSelect` supports complex selection logic and application state management
- **Properties (Menu)**:
  - `bordered`: boolean - Indicates if the menu should have a border
  - `customClass`: string - Custom CSS class to apply to the ul element
  - `orientation`: 'horizontal' | 'vertical' - The orientation of the menu (default: 'vertical')
  - `size`: 'sm' | 'md' | 'lg' - The size of the menu (default: 'md')

- **Properties (MenuItem)**:
  - `bordered`: boolean - Indicates if the menu item should have a border
  - `customClass`: string - Custom CSS class to apply to the li element
  - `disabled`: boolean - The disabled state of the menu item
  - `focused`: boolean - The focused state of the menu item
  - `label`: string - The text rendered in the menu item
  - `selected`: boolean - The selected state of the menu item
  - `size`: 'sm' | 'md' | 'lg' - The size of the menu item
  - `startIcon`: string - The Modus icon name to render at the start of the menu item
  - `subLabel`: string - The text rendered beneath the label
  - `value`: string - The unique identifying value of the menu item

- **Events (MenuItem)**:
  - `itemSelect`: CustomEvent<{ value: string }> - Event emitted when a menu item is selected

- **Usage Patterns**:
  - Menu component serves as a container for MenuItem components
  - Both vertical and horizontal orientation supported
  - Can handle item selection with the itemSelect event
  - Supports customization with icons, sub-labels and different sizes

**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcMenu, ModusWcMenuItem } from '@trimble-oss/moduswebcomponents-react';

interface MenuItem {
  label: string;
  value: string;
  icon?: string;
  subLabel?: string;
  disabled?: boolean;
}

const NavigationMenu: React.FC = () => {
  const [selectedItem, setSelectedItem] = useState<string>('home');
  
  // Menu items data
  const menuItems: MenuItem[] = [
    { label: 'Home', value: 'home', icon: 'home' },
    { label: 'Dashboard', value: 'dashboard', icon: 'dashboard' },
    { label: 'Analytics', value: 'analytics', icon: 'bar_chart', subLabel: 'View detailed statistics' },
    { label: 'Settings', value: 'settings', icon: 'settings', disabled: true },
  ];
  
  // Setup refs for event handling
  const menuItemRefs = useRef<(HTMLModusWcMenuItemElement | null)[]>([]);
  
  useEffect(() => {
    // Attach event listeners to menu items
    menuItemRefs.current.forEach((item, index) => {
      if (item) {
        const handleSelect = (e: CustomEvent<{ value: string }>) => {
          setSelectedItem(e.detail.value);
          console.log('Selected item:', e.detail.value);
        };
        
        item.addEventListener('itemSelect', handleSelect as EventListener);
        
        return () => {
          item.removeEventListener('itemSelect', handleSelect as EventListener);
        };
      }
    });
  }, []);
  
  return (
    <ModusWcMenu aria-label="Main Navigation" orientation="vertical" size="md">
      {menuItems.map((item, index) => (
        <ModusWcMenuItem
          key={item.value}
          ref={el => menuItemRefs.current[index] = el}
          label={item.label}
          value={item.value}
          startIcon={item.icon}
          subLabel={item.subLabel}
          disabled={item.disabled}
          selected={selectedItem === item.value}
        />
      ))}
    </ModusWcMenu>
  );
};

export default NavigationMenu;
```

**Notes:**
- Always provide a unique `value` for each MenuItem to properly track selection state
- Use the `itemSelect` event to handle user interactions
- You need to maintain the selected state manually in your React component
- Menu items can be customized with icons, sub-labels, and different sizes
- Use `aria-label` on the menu for better accessibility

## Prompt 2
**User Question:** How can I create a custom dropdown menu with the Modus Menu components that integrates with a button trigger?

**Agent Answer:**
References:
- **Properties (Menu)**:
  - `bordered`: boolean - Adds border to the menu
  - `customClass`: string - Custom CSS class for styling
  - `orientation`: 'horizontal' | 'vertical' - Menu layout direction
  - `size`: 'sm' | 'md' | 'lg' - Size variant of the menu

- **Properties (MenuItem)**:
  - `label`: string - Text content of the menu item
  - `value`: string - Unique identifier for the item
  - `startIcon`: string - Icon name from Modus icon library
  - `disabled`: boolean - Disables interaction with the menu item
  - `selected`: boolean - Visually indicates selected state
  - `subLabel`: string - Supplementary text below the main label

- **Events (MenuItem)**:
  - `itemSelect`: CustomEvent<{ value: string }> - Fires when an item is selected

- **Usage Patterns**:
  - Combining with buttons to create dropdown menus
  - Using with portals or popovers for proper positioning
  - Managing visibility state and click outside handling
  - Creating nested or cascading menu structures

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcButton, ModusWcMenu, ModusWcMenuItem, ModusWcIcon } from '@trimble-oss/moduswebcomponents-react';

interface DropdownMenuItem {
  label: string;
  value: string;
  icon: string;
  disabled?: boolean;
}

const DropdownMenu: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLModusWcButtonElement>(null);
  
  // Menu items data
  const items: DropdownMenuItem[] = [
    { label: 'Edit', value: 'edit', icon: 'edit' },
    { label: 'Duplicate', value: 'duplicate', icon: 'content_copy' },
    { label: 'Delete', value: 'delete', icon: 'delete' },
    { label: 'Share', value: 'share', icon: 'share', disabled: true }
  ];
  
  // Toggle dropdown visibility
  const toggleDropdown = () => {
    setIsOpen(!isOpen);
  };
  
  // Handle item selection using React event props
  const handleItemSelect = (value: string) => {
    console.log('Selected action:', value);
    
    // Perform action based on selection
    switch(value) {
      case 'edit':
        console.log('Edit item');
        break;
      case 'duplicate':
        console.log('Duplicate item');
        break;
      case 'delete':
        console.log('Delete item');
        break;
      default:
        break;
    }
    
    // Close the dropdown after selection
    setIsOpen(false);
  };
  
  // Handle click outside to close dropdown
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current && 
        !dropdownRef.current.contains(event.target as Node) && 
        buttonRef.current && 
        !buttonRef.current.contains(event.target as Node)
      ) {
        setIsOpen(false);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  
  // Position the dropdown below the button
  useEffect(() => {
    if (isOpen && buttonRef.current && dropdownRef.current) {
      const buttonRect = buttonRef.current.getBoundingClientRect();
      dropdownRef.current.style.top = `${buttonRect.bottom}px`;
      dropdownRef.current.style.left = `${buttonRect.left}px`;
    }
  }, [isOpen]);
  
  return (
    <div style={{ position: 'relative' }}>
      <ModusWcButton 
        ref={buttonRef}
        onClick={toggleDropdown}
        aria-haspopup="true"
        aria-expanded={isOpen ? 'true' : 'false'}>
        Actions
        <ModusWcIcon name={isOpen ? "chevron_up" : "chevron_down"}></ModusWcIcon>
      </ModusWcButton>
      
      {isOpen && (
        <div 
          ref={dropdownRef} 
          style={{
            position: 'absolute',
            zIndex: 1000,
            boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
            background: 'white',
            borderRadius: '4px',
            marginTop: '4px'
          }}>
          <ModusWcMenu bordered size="md">
            {items.map((item) => (
              <ModusWcMenuItem
                key={item.value}
                label={item.label}
                value={item.value}
                startIcon={item.icon}
                disabled={item.disabled}
                onItemSelect={() => handleItemSelect(item.value)}
              />
            ))}
          </ModusWcMenu>
        </div>
      )}
    </div>
  );
};

export default DropdownMenu;
```

**Notes:**
- The dropdown implementation requires manual positioning and visibility management
- Remember to handle keyboard navigation and accessibility for the dropdown menu
- Use `aria-haspopup` and `aria-expanded` attributes for accessibility
- Add click-outside detection to close the menu when clicking elsewhere
- Consider using a portal (React.createPortal) for more complex positioning requirements
- For nested/cascading menus, you'll need to implement additional hover detection

---

# ModusWcMenuItem

## Prompt 1
**User Question:** I'm developing a comprehensive interface that requires sophisticated menu systems - contextual action menus, hierarchical navigation structures, multi-selection patterns, and adaptive layouts that work across different interaction modes. The menus should provide clear organization, efficient selection patterns, and accessibility compliance. How should I implement a flexible menu system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive menu requirement, I considered:
1. **Context Adaptation**: Different interface areas need different menu behaviors - navigation vs. action menus vs. selection lists
2. **Interaction Patterns**: Users need clear feedback for selection, hover states, and multi-selection workflows
3. **Layout Flexibility**: Menus must work in various containers - sidebars, dropdowns, toolbars, and mobile interfaces
4. **Accessibility Standards**: Menu structures must support keyboard navigation and screen reader interaction

**Component Analysis:**
I examined the ModusWcMenu and ModusWcMenuItem component architecture and found it's designed for flexible menu construction:
- **Layout Control**: `orientation` property supports both horizontal toolbar menus and vertical navigation patterns
- **Visual Hierarchy**: `size` property adapts menu density for different interface contexts
- **Item Management**: ModusWcMenuItem provides comprehensive state management (selected, focused, disabled) with icon and sub-label support
- **Event Architecture**: `itemSelect` events enable selection tracking and workflow integration

**Why I chose these properties:**
- **`orientation` flexibility**: Essential for layout adaptation - 'vertical' for navigation, 'horizontal' for toolbars and action bars
- **`size` variants**: Critical for interface density - 'sm' for compact interfaces, 'lg' for touch-friendly navigation
- **MenuItem state management**: Provides complete user feedback - 'selected' for current state, 'focused' for keyboard navigation, 'disabled' for conditional access
- **Icon and labeling**: Enables semantic menu construction with visual recognition and hierarchical information
- **Event handling**: `itemSelect` supports complex selection logic and application state management
- **Properties (Menu)**:
  - `bordered`: boolean - Indicates if the menu should have a border
  - `customClass`: string - Custom CSS class to apply to the ul element
  - `orientation`: 'horizontal' | 'vertical' - The orientation of the menu (default: 'vertical')
  - `size`: 'sm' | 'md' | 'lg' - The size of the menu (default: 'md')

- **Properties (MenuItem)**:
  - `bordered`: boolean - Indicates if the menu item should have a border
  - `customClass`: string - Custom CSS class to apply to the li element
  - `disabled`: boolean - The disabled state of the menu item
  - `focused`: boolean - The focused state of the menu item
  - `label`: string - The text rendered in the menu item
  - `selected`: boolean - The selected state of the menu item
  - `size`: 'sm' | 'md' | 'lg' - The size of the menu item
  - `startIcon`: string - The Modus icon name to render at the start of the menu item
  - `subLabel`: string - The text rendered beneath the label
  - `value`: string - The unique identifying value of the menu item

- **Events (MenuItem)**:
  - `itemSelect`: CustomEvent<{ value: string }> - Event emitted when a menu item is selected

- **Usage Patterns**:
  - Menu component serves as a container for MenuItem components
  - Both vertical and horizontal orientation supported
  - Can handle item selection with the itemSelect event
  - Supports customization with icons, sub-labels and different sizes

**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcMenu, ModusWcMenuItem } from '@trimble-oss/moduswebcomponents-react';

interface MenuItem {
  label: string;
  value: string;
  icon?: string;
  subLabel?: string;
  disabled?: boolean;
}

const NavigationMenu: React.FC = () => {
  const [selectedItem, setSelectedItem] = useState<string>('home');
  
  // Menu items data
  const menuItems: MenuItem[] = [
    { label: 'Home', value: 'home', icon: 'home' },
    { label: 'Dashboard', value: 'dashboard', icon: 'dashboard' },
    { label: 'Analytics', value: 'analytics', icon: 'bar_chart', subLabel: 'View detailed statistics' },
    { label: 'Settings', value: 'settings', icon: 'settings', disabled: true },
  ];
  
  // Setup refs for event handling
  const menuItemRefs = useRef<(HTMLModusWcMenuItemElement | null)[]>([]);
  
  useEffect(() => {
    // Attach event listeners to menu items
    menuItemRefs.current.forEach((item, index) => {
      if (item) {
        const handleSelect = (e: CustomEvent<{ value: string }>) => {
          setSelectedItem(e.detail.value);
          console.log('Selected item:', e.detail.value);
        };
        
        item.addEventListener('itemSelect', handleSelect as EventListener);
        
        return () => {
          item.removeEventListener('itemSelect', handleSelect as EventListener);
        };
      }
    });
  }, []);
  
  return (
    <ModusWcMenu aria-label="Main Navigation" orientation="vertical" size="md">
      {menuItems.map((item, index) => (
        <ModusWcMenuItem
          key={item.value}
          ref={el => menuItemRefs.current[index] = el}
          label={item.label}
          value={item.value}
          startIcon={item.icon}
          subLabel={item.subLabel}
          disabled={item.disabled}
          selected={selectedItem === item.value}
        />
      ))}
    </ModusWcMenu>
  );
};

export default NavigationMenu;
```

**Notes:**
- Always provide a unique `value` for each MenuItem to properly track selection state
- Use the `itemSelect` event to handle user interactions
- You need to maintain the selected state manually in your React component
- Menu items can be customized with icons, sub-labels, and different sizes
- Use `aria-label` on the menu for better accessibility

---

# ModusWcModal

## Prompt 1
**User Question:** I need to implement modal dialogs for different user workflows - confirmations, forms, content display, and complex interactions. The modals should be accessible, controllable, and handle various user interaction patterns. How should I approach building a flexible modal system?

**Agent Answer:**
**My Reasoning Process:**

Analyzing modal requirements: user workflow integration, accessibility compliance, interaction control, and content flexibility across different use cases.

**Component Analysis:**
ModusWcModal leverages native HTML dialog element with enhanced controls through `backdrop`, `position`, and slot-based content organization.

**Why I chose these properties:**
- **`modalId`**: Required for DOM access to native dialog methods (showModal/close)
- **`backdrop="static"`**: Prevents accidental dismissal for critical workflows
- **`position`**: Controls visual hierarchy and user attention direction
- **Slot system**: Organizes content semantically (header, content, footer) for consistent structure
- **Native dialog integration**: Leverages browser accessibility features and focus management

**TypeScript Example:**
```tsx
import React, { useRef } from 'react';
import { ModusWcModal, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

const BasicModal: React.FC = () => {
  // Generate a unique ID for the modal
  const modalId = 'modal-' + Math.random().toString(36).substring(2, 9);
  const dialogRef = useRef<HTMLDialogElement | null>(null);
  
  const openModal = () => {
    // Access the native dialog element through DOM and call showModal()
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.showModal();
    }
  };
  
  const closeModal = () => {
    // Access the native dialog element through DOM and call close()
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.close();
    }
  };
  
  const handleConfirm = () => {
    // Perform confirm action here
    console.log('Confirmed!');
    closeModal();
  };
  
  return (
    <>
      <ModusWcButton onClick={openModal}>Open Modal</ModusWcButton>
      
      <ModusWcModal
        aria-label="Example Modal"
        modalId={modalId}
        backdrop="default"
        position="center"
        showClose={true}>
        <div slot="header">Modal Title</div>
        <div slot="content">
          <p>This is the modal content. You can put any React content here.</p>
          <p>Multiple paragraphs or complex content is supported.</p>
        </div>
        <div slot="footer" style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
          <ModusWcButton color="secondary" onClick={closeModal}>
            Cancel
          </ModusWcButton>
          <ModusWcButton color="primary" onClick={handleConfirm}>
            Confirm
          </ModusWcButton>
        </div>
      </ModusWcModal>
    </>
  );
};

export default BasicModal;
```

**Implementation Decisions & Rationale:**

**Native Dialog Integration**: Leverages browser's built-in dialog accessibility features, focus management, and keyboard navigation.

**State Management**: Component relies on external control via DOM methods, enabling integration with various state management patterns and workflow systems.

**Accessibility**: Native dialog element provides proper focus trapping, ARIA roles, and screen reader support when combined with appropriate aria-label attributes.

## Prompt 2
**User Question:** How can I create a reusable confirmation modal component in React that can be triggered from different parts of my application?

**Agent Answer:**
References:
- **Properties**:
  - `modalId`: string - Required identifier for the modal dialog
  - `backdrop`: 'default' | 'static' - Controls if clicking backdrop closes modal
  - `position`: 'bottom' | 'center' | 'top' - Vertical positioning
  - `customClass`: string - For custom styling
  - `fullscreen`: boolean - For full-screen modal display
  - `showClose`: boolean - Controls visibility of close button
  - `showFullscreenToggle`: boolean - Controls visibility of fullscreen toggle

- **Events**:
  - Uses native dialog element events (no custom events)

- **Usage Patterns**:
  - Creating reusable modal components with React Context
  - Implementing modal service patterns for application-wide access
  - Managing modal stacks for multiple concurrent modals

**TypeScript Example:**
```tsx
import React, { createContext, useContext, useState, ReactNode } from 'react';
import { ModusWcModal, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

// Types for our confirmation dialog
interface ConfirmationDialogProps {
  title: string;
  message: string;
  confirmLabel?: string;
  cancelLabel?: string;
  onConfirm: () => void;
  onCancel?: () => void;
}

// Context for our modal service
interface ModalContextType {
  showConfirmation: (props: ConfirmationDialogProps) => void;
}

const ModalContext = createContext<ModalContextType | undefined>(undefined);

// Provider component that will wrap our app
export const ModalProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const modalId = 'confirmation-modal';
  const [dialogProps, setDialogProps] = useState<ConfirmationDialogProps | null>(null);
  
  // Method to show the confirmation dialog
  const showConfirmation = (props: ConfirmationDialogProps) => {
    setDialogProps(props);
    
    // Use setTimeout to ensure DOM is updated before showing modal
    setTimeout(() => {
      const modal = document.getElementById(modalId) as HTMLDialogElement;
      if (modal) {
        modal.showModal();
      }
    }, 0);
  };
  
  // Method to close the modal
  const closeModal = () => {
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.close();
    }
  };
  
  // Handle confirm action
  const handleConfirm = () => {
    if (dialogProps?.onConfirm) {
      dialogProps.onConfirm();
    }
    closeModal();
  };
  
  // Handle cancel action
  const handleCancel = () => {
    if (dialogProps?.onCancel) {
      dialogProps.onCancel();
    }
    closeModal();
  };
  
  return (
    <ModalContext.Provider value={{ showConfirmation }}>
      {children}
      
      {/* The actual modal component */}
      {dialogProps && (
        <ModusWcModal
          aria-label={dialogProps.title}
          modalId={modalId}
          backdrop="static"
          position="center"
          showClose={false}>
          <div slot="header">{dialogProps.title}</div>
          <div slot="content">
            <p>{dialogProps.message}</p>
          </div>
          <div slot="footer" style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px' }}>
            <ModusWcButton color="secondary" onClick={handleCancel}>
              {dialogProps.cancelLabel || 'Cancel'}
            </ModusWcButton>
            <ModusWcButton color="primary" onClick={handleConfirm}>
              {dialogProps.confirmLabel || 'Confirm'}
            </ModusWcButton>
          </div>
        </ModusWcModal>
      )}
    </ModalContext.Provider>
  );
};

// Custom hook to use the modal service
export const useModal = (): ModalContextType => {
  const context = useContext(ModalContext);
  if (!context) {
    throw new Error('useModal must be used within a ModalProvider');
  }
  return context;
};

// Example usage in a component:
const DeleteButton: React.FC<{ itemId: string }> = ({ itemId }) => {
  const { showConfirmation } = useModal();
  
  const handleDelete = () => {
    console.log(`Deleting item ${itemId}`);
    // API call to delete the item
  };
  
  const confirmDelete = () => {
    showConfirmation({
      title: 'Delete Item',
      message: 'Are you sure you want to delete this item? This action cannot be undone.',
      confirmLabel: 'Delete',
      onConfirm: handleDelete,
      // Optional cancel handler
      onCancel: () => console.log('Deletion cancelled')
    });
  };
  
  return (
    <ModusWcButton color="danger" onClick={confirmDelete}>
      Delete Item
    </ModusWcButton>
  );
};
```

**Notes:**
- This pattern creates a reusable modal service using React Context
- The ModalProvider should be placed near the root of your component tree
- Using `backdrop="static"` prevents accidental dismissal of important confirmations
- The context API allows any component to trigger the modal without prop drilling
- You can extend this pattern to support different types of modals (alert, form, etc.)
- For complex forms in modals, consider state management solutions like Formik or React Hook Form
- Always implement keyboard navigation (Escape to close, Enter to confirm) for accessibility

---

# ModusWcNavbar

## Prompt 1
**User Question:** I need to implement a comprehensive application header that provides user identity, navigation access, search functionality, and contextual actions. The navbar should be customizable for different application areas while maintaining consistent user experience patterns. How can I build a flexible navbar system?

**Agent Answer:**
**My Reasoning Process:**

Analyzing navbar requirements: user identity management, navigation hierarchy, search integration, responsive behavior, and customizable content areas for different application contexts.

**Component Analysis:**
ModusWcNavbar provides comprehensive header functionality through `userCard` profile integration, `visibility` controls for feature toggling, slot-based content customization, and extensive event handling for interactive elements, It tells which of the features should be shown in the Navbar. 

**Why I chose these properties:**
- **`userCard` object**: Centralizes user identity display with avatar, name, email for consistent personalization
- **`visibility` configuration**: Enables selective feature exposure based on user roles or application context
- **`textOverrides`**: Supports localization and brand customization while maintaining functionality
- **Slot system**: Provides flexible content areas for main-menu, notifications, apps without breaking navbar structure
- **Event architecture**: Comprehensive event handling for search, navigation, and user actions enables workflow integration

**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcNavbar } from '@trimble-oss/moduswebcomponents-react';

// Interface definitions for better TypeScript support
interface INavbarUserCard {
  avatarAlt?: string;
  avatarSrc?: string;
  email: string;
  name: string;
  myTrimbleButton?: string;
  signOutButton?: string;
}

interface INavbarVisibility {
  ai?: boolean;
  apps?: boolean;
  help?: boolean;
  mainMenu?: boolean;
  notifications?: boolean;
  search?: boolean;
  searchInput?: boolean;
  user?: boolean;
}

const AppNavbar: React.FC = () => {
  // Navbar reference for event handling
  const navbarRef = useRef<HTMLModusWcNavbarElement>(null);
  const [searchValue, setSearchValue] = useState<string>('');
  
  // User information
  const userCard: INavbarUserCard = {
    name: 'John Doe',
    email: 'john.doe@example.com',
    avatarSrc: 'path/to/avatar.jpg',
    avatarAlt: 'John Doe'
  };
  
  // Visibility configuration
  const visibility: INavbarVisibility = {
    mainMenu: true,
    notifications: true,
    search: true,
    apps: false,
    help: true,
    user: true
  };
  
  // Text overrides for localization or customization
  const textOverrides = {
    help: 'Support',
    notifications: 'Alerts'
  };
  
  // Event handlers
  useEffect(() => {
    const navbar = navbarRef.current;
    if (navbar) {
      // Handle search input changes
      const handleSearchChange = (e: CustomEvent<{ value: string }>) => {
        setSearchValue(e.detail.value);
        console.log('Search value:', e.detail.value);
      };
      
      // Handle sign out clicks
      const handleSignOut = () => {
        console.log('User clicked sign out');
        // Implement sign out logic
      };
      
      // Add event listeners
      navbar.addEventListener('searchChange', handleSearchChange as EventListener);
      navbar.addEventListener('signOutClick', handleSignOut);
      
      // Clean up event listeners
      return () => {
        navbar.removeEventListener('searchChange', handleSearchChange as EventListener);
        navbar.removeEventListener('signOutClick', handleSignOut);
      };
    }
  }, []);
  
  return (
    <ModusWcNavbar
      ref={navbarRef}
      userCard={userCard}
      visibility={visibility}
      textOverrides={textOverrides}>
      
      {/* Custom main menu content */}
      <div slot="main-menu" style={{backgroundColor: '#0063a3', color: 'white', padding: '1rem'}}>
        <h3>Main Menu</h3>
        <ul>
          <li>Dashboard</li>
          <li>Projects</li>
          <li>Reports</li>
          <li>Settings</li>
        </ul>
      </div>
      
      {/* Notifications menu content */}
      <div slot="notifications">
        <div style={{padding: '0.5rem 1rem'}}>
          <h4 style={{margin: '0.5rem 0'}}>New message</h4>
          <p style={{margin: '0.5rem 0'}}>You have a new message from Admin</p>
        </div>
        <div style={{padding: '0.5rem 1rem', borderTop: '1px solid #eee'}}>
          <h4 style={{margin: '0.5rem 0'}}>System update</h4>
          <p style={{margin: '0.5rem 0'}}>System maintenance scheduled for tomorrow</p>
        </div>
      </div>
      
      {/* Apps menu content */}
      <div slot="apps">
        <div style={{padding: '1rem'}}>
          <p>No application shortcuts configured.</p>
        </div>
      </div>
    </ModusWcNavbar>
  );
};

export default AppNavbar;
```

**Implementation Decisions & Rationale:**

**Configuration Strategy**: `userCard` and `visibility` objects provide declarative configuration enabling dynamic navbar behavior based on user context and application state.

**Slot Architecture**: Named slots ('main-menu', 'notifications', 'apps') enable custom content while preserving navbar structure and responsive behavior.

**Event Management**: Comprehensive event handling through `useRef` and `useEffect` ensures proper React lifecycle management for complex navbar interactions.




## Prompt 2
**User Question:** I want you to create a Modus Navbar with a sidebar and fix the spacing issue where text shows when collapsed. I also want you to change the theme to classic-light.

**Agent Answer:**

**My Reasoning Process:**

Analyzing the requirements: Need to integrate ModusWcNavbar with ModusWcSideNavigation while applying the classic-light theme. The critical challenge is properly handling the navbar's main menu button to control sidebar state rather than using its default dropdown behavior, and ensuring proper text visibility when collapsed.

**Component Analysis:**
ModusWcNavbar provides built-in main menu functionality with a hamburger menu that by default shows a dropdown menu. However, for modern dashboard applications, users expect the hamburger menu to control a sidebar navigation instead. This requires intercepting the `mainMenuOpenChange` event and repurposing it to toggle ModusWcSideNavigation visibility.

**Why I chose these implementation decisions:**
- **Override Default Hamburger Behavior**: The most critical decision was repurposing the navbar's hamburger menu from its default dropdown behavior to control sidebar toggle - this matches user expectations in dashboard applications
- **Document-Level Event Handling**: Following the official Storybook pattern for proper event propagation and Modus component compatibility
- **Theme Integration**: Applied `modus-classic-light` theme at document level using proper attributes for consistent theming
- **Auto-Collapse Pattern**: Implemented sidebar collapse after menu item selection following Storybook example
- **Verified Modus Icons**: Used proper icon names from Modus icon registry (home, person, gears, folder_open, bar_graph)

**Implementation Decisions & Rationale:**

**Hamburger Menu Override Strategy**: The most important architectural decision was overriding the navbar's default main menu behavior. Instead of showing a dropdown when the hamburger menu is clicked, we intercept the `mainMenuOpenChange` event to control our ModusWcSideNavigation state. This provides the expected user experience where the hamburger menu toggles a persistent sidebar navigation rather than a transient dropdown.

**TypeScript Example:**
```tsx
import React, { useState, useEffect, useRef } from 'react';
import { 
  ModusWcSideNavigation,
  ModusWcNavbar,
  ModusWcMenu,
  ModusWcMenuItem
} from '@trimble-oss/moduswebcomponents-react';

// Interface definitions for better TypeScript support
interface INavbarUserCard {
  avatarAlt?: string;
  avatarSrc?: string;
  email: string;
  name: string;
  myTrimbleButton?: string;
  signOutButton?: string;
}

interface INavbarVisibility {
  ai?: boolean;
  apps?: boolean;
  help?: boolean;
  mainMenu?: boolean;
  notifications?: boolean;
  search?: boolean;
  searchInput?: boolean;
  user?: boolean;
}

interface MenuItem {
  id: string;
  label: string;
  icon: string;
  path: string;
}

const AppLayout: React.FC = () => {
  // State for side navigation
  const [isExpanded, setIsExpanded] = useState(false);
  const [activeItemId, setActiveItemId] = useState('home');
  
  // Refs for components
  const navbarRef = useRef<HTMLModusWcNavbarElement>(null);
  const sideNavRef = useRef<HTMLModusWcSideNavigationElement>(null);
  
  // Apply classic-light theme on component mount
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', 'modus-classic-light');
    document.documentElement.setAttribute('data-mode', 'light');
    document.documentElement.classList.add('light');
    
    // Cleanup on unmount
    return () => {
      document.documentElement.removeAttribute('data-theme');
      document.documentElement.removeAttribute('data-mode');
      document.documentElement.classList.remove('light');
    };
  }, []);
  
  // User information - following React component pattern
  const userCard: INavbarUserCard = {
    name: 'John Doe',
    email: 'john.doe@example.com',
    avatarSrc: 'https://i.pravatar.cc/150?img=12',
    avatarAlt: 'John Doe Avatar'
  };
  
  // Visibility configuration - following React component pattern
  const visibility: INavbarVisibility = {
    apps: true,
    help: true,
    mainMenu: true, // Enable hamburger menu for sidebar control (not dropdown)
    notifications: true,
    search: true,
    searchInput: false,
    user: true
  };
  
  // Text overrides for customization
  const textOverrides = {
    help: 'Support',
    notifications: 'Alerts'
  };
  
  // Menu items data with verified Modus icon names
  const menuItems: MenuItem[] = [
    { id: 'home', label: 'Home', icon: 'home', path: '/' },
    { id: 'profile', label: 'Profile', icon: 'person', path: '/profile' },
    { id: 'settings', label: 'Settings', icon: 'gears', path: '/settings' },
    { id: 'projects', label: 'Projects', icon: 'folder_open', path: '/projects' },
    { id: 'reports', label: 'Reports', icon: 'bar_graph', path: '/reports' }
  ];
  
  // Handle navbar main menu toggle - OVERRIDE DEFAULT DROPDOWN BEHAVIOR
  useEffect(() => {
    const handleMainMenuOpenChange = () => {
      const sideNav = sideNavRef.current;
      if (sideNav) {
        const newExpanded = !isExpanded;
        setIsExpanded(newExpanded);
        sideNav.expanded = newExpanded;
        console.log('Sidebar toggled (not dropdown):', newExpanded);
      }
    };

    // Listen at document level as in Storybook example
    document.addEventListener('mainMenuOpenChange', handleMainMenuOpenChange);
    
    return () => {
      document.removeEventListener('mainMenuOpenChange', handleMainMenuOpenChange);
    };
  }, [isExpanded]);
  
  // Handle menu item selection - following Storybook pattern
  const handleMenuItemSelect = (item: MenuItem) => {
    setActiveItemId(item.id);
    
    // Collapse side nav after selection (like in Storybook)
    const sideNav = sideNavRef.current;
    if (sideNav) {
      sideNav.expanded = false;
      setIsExpanded(false);
    }
    
    console.log(`Navigating to: ${item.label} (${item.path})`);
  };
  
  // Render content based on active item
  const renderContent = () => {
    const titleStyle = {
      margin: '0',
      padding: '1rem 0',
      color: '#212529',
      fontSize: '2.5rem',
      fontWeight: 'bold' as const
    };

    switch (activeItemId) {
      case 'home':
        return <h1 style={titleStyle}>🏠 Home</h1>;
      case 'profile':
        return <h1 style={titleStyle}>👤 Profile</h1>;
      case 'settings':
        return <h1 style={titleStyle}>⚙️ Settings</h1>;
      case 'projects':
        return <h1 style={titleStyle}>📁 Projects</h1>;
      case 'reports':
        return <h1 style={titleStyle}>📊 Reports</h1>;
      default:
        return <h1 style={titleStyle}>Select an item from the side navigation</h1>;
    }
  };
  
  return (
    <div style={{ 
      display: 'flex', 
      flexDirection: 'column', 
      height: '100vh',
      width: '100vw',
      margin: 0,
      padding: 0,
      boxShadow: 'rgba(36, 35, 45, 0.3) 1px 0 4px'
    }}>
      {/* Navbar - Hamburger menu controls sidebar (not dropdown) */}
      <ModusWcNavbar
        ref={navbarRef}
        userCard={userCard}
        visibility={visibility}
        textOverrides={textOverrides}
        style={{ 
          zIndex: 2,
          boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
        }}
      />
      
      {/* Main content row - Following Storybook pattern */}
      <div style={{ 
        display: 'flex', 
        flex: 1, 
        overflow: 'hidden'
      }}>
        {/* ModusWcSideNavigation - Controlled by hamburger menu */}
        <ModusWcSideNavigation
          ref={sideNavRef}
          expanded={isExpanded}
          collapseOnClickOutside={true}
          maxWidth="256px"
          style={{
            height: '100%',
            alignSelf: 'flex-start',
            position: 'relative'
          }}
        >
          <ModusWcMenu size="lg">
            {menuItems.map((item) => (
              <ModusWcMenuItem
                key={item.id}
                label={item.label}
                value={item.id}
                startIcon={item.icon}
                selected={activeItemId === item.id}
                onItemSelect={() => handleMenuItemSelect(item)}
              />
            ))}
          </ModusWcMenu>
        </ModusWcSideNavigation>
        
        {/* Panel content - Following Storybook pattern */}
        <div style={{
          marginLeft: '4rem',
          padding: '3rem 2rem',
          flex: 1,
          overflow: 'auto',
          background: '#f8f9fa'
        }}>
          <div style={{
            maxWidth: '800px',
            background: '#ffffff',
            padding: '3rem',
            borderRadius: '8px',
            boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
            minHeight: '200px'
          }}>
            <div style={{ marginBottom: '2rem' }}>
              {renderContent()}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AppLayout;
```

**Important Note**: **CRITICAL BEHAVIOR OVERRIDE** - The default hamburger menu behavior in ModusWcNavbar shows a dropdown menu with main-menu slot content. In this implementation, we completely override that default behavior by intercepting the `mainMenuOpenChange` event and repurposing it to control ModusWcSideNavigation instead. This provides the expected UX pattern where the hamburger menu toggles a persistent sidebar navigation rather than showing a transient dropdown menu. The ModusWcSideNavigation component handles text visibility internally when collapsed, so avoid custom overflow styling that can break its built-in behavior.

---

# ModusWcNumberInput

## Prompt 1

**User Question:** This example is too complex. Just create a one input and use one of its property and a submit button which would be Modus.

**Agent Answer:**

**My Reasoning Process:**

Analyzing the request: The user wants to simplify a complex form down to its most basic elements - one number input field with a basic property configuration and a Modus submit button. Focus on demonstrating core functionality without overwhelming complexity.

**Component Analysis:**
ModusWcNumberInput provides essential numeric input functionality with built-in validation and formatting. For a simple use case, we need basic properties like `value`, `label`, `min`, `max`, `step`, and event handling. ModusWcButton provides consistent styling and form integration for the submit action.

**Why I chose these implementation decisions:**
- **Single Input Focus**: Used ModusWcNumberInput with essential properties (min/max range, step increment, label, placeholder)
- **Basic State Management**: Simple useState hook for controlled input without complex validation
- **Essential Event Handling**: Single onInputChange handler using CustomEvent pattern for Modus components
- **Clean Layout**: Minimal styling focused on component demonstration rather than complex UI
- **Immediate Feedback**: Simple value display to show current input state
- **Form Integration**: Proper form submission with preventDefault and console logging

**Implementation Decisions & Rationale:**

**Simplicity Strategy**: Stripped down from a complex multi-field validation system to focus on core ModusWcNumberInput usage patterns. This makes the example approachable for developers learning the component basics.

**Property Selection**: Chose fundamental properties that demonstrate the component's core capabilities - numeric constraints (min/max), input behavior (step), user guidance (label/placeholder), and responsive sizing.

**Event Pattern**: Used the standard Modus Web Component event handling pattern with CustomEvent and detail.target access, which is essential for proper React integration.

**State Management**: Implemented controlled component pattern with React useState, showing the proper way to manage ModusWcNumberInput state in React applications.

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcNumberInput, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

const SimpleNumberForm: React.FC = () => {
  const [quantity, setQuantity] = useState<string>('');
  
  // Handle input changes
  const handleInputChange = (e: CustomEvent) => {
    const target = e.detail.target as HTMLInputElement;
    setQuantity(target.value);
  };
  
  // Handle form submission
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    console.log('Submitted quantity:', quantity);
  };
  
  return (
    <div style={{
      maxWidth: '400px',
      margin: '0 auto',
      padding: '2rem',
      display: 'flex',
      flexDirection: 'column',
      gap: '1.5rem'
    }}>
      <h2>Simple Number Form</h2>
      
      <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
        <ModusWcNumberInput
          value={quantity}
          label="Quantity"
          min={1}
          max={100}
          step={1}
          placeholder="Enter quantity"
          size="md"
          onInputChange={handleInputChange}
        />
        
        <ModusWcButton
          type="submit"
          color="primary"
          variant="filled"
          size="md"
        >
          Submit
        </ModusWcButton>
      </form>
      
      {quantity && (
        <div style={{
          padding: '1rem',
          backgroundColor: '#f0f8ff',
          borderRadius: '4px',
          textAlign: 'center'
        }}>
          <p>Current value: <strong>{quantity}</strong></p>
        </div>
      )}
    </div>
  );
};

export default SimpleNumberForm;
```

**Key Features Demonstrated:**
- **Basic ModusWcNumberInput Usage**: Essential properties for numeric input with constraints
- **Proper Event Handling**: CustomEvent pattern for Modus Web Component integration
- **Controlled Component**: React state management with ModusWcNumberInput
- **Form Integration**: Standard form submission with ModusWcButton
- **Immediate Feedback**: Real-time display of current input value
- **Clean Styling**: Minimal, focused layout using flexbox
- **TypeScript Support**: Proper typing for event handlers and component props

**Important Note**: This example demonstrates the fundamental pattern for using ModusWcNumberInput in React applications - controlled state management, proper event handling with CustomEvent, and basic property configuration for numeric constraints.
---

# ModusWcPagination

## Prompt 1

**User Question**:"Create a data management system that displays items in a paginated format with search functionality using Modus Web Components. The system should show data in cards, allow users to search through items, and provide pagination controls."

**Agent Answer** : 

```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcPagination, ModusWcTextInput, ModusWcCard, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface DataItem {
  id: number;
  name: string;
  category: string;
  status: string;
}

const SimpleDataList: React.FC = () => {
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [data, setData] = useState<DataItem[]>([]);
  
  const paginationRef = useRef<HTMLModusWcPaginationElement>(null);
  
  const pageSize = 5;
  const totalItems = 47; // Mock total
  const totalPages = Math.ceil(totalItems / pageSize);
  
  // Generate mock data
  const generateData = (page: number, search: string) => {
    const startIndex = (page - 1) * pageSize;
    return Array.from({ length: pageSize }, (_, i) => {
      const id = startIndex + i + 1;
      return {
        id,
        name: search ? `Search Result ${id}` : `Data Item ${id}`,
        category: ['Electronics', 'Books', 'Clothing'][id % 3],
        status: ['Active', 'Pending', 'Inactive'][id % 3]
      };
    });
  };
  
  // Load data when page or search changes
  useEffect(() => {
    const newData = generateData(currentPage, searchTerm);
    setData(newData);
  }, [currentPage, searchTerm]);
  
  // Handle pagination
  const handlePageChange = (e: CustomEvent<{newPage: number}>) => {
    setCurrentPage(e.detail.newPage);
  };
  
  // Handle search
  const handleSearchChange = (e: CustomEvent) => {
    const target = e.detail.target as HTMLInputElement;
    setSearchTerm(target.value);
    setCurrentPage(1); // Reset to first page on search
  };
  
  // Set up pagination event listener
  useEffect(() => {
    const pagination = paginationRef.current;
    if (pagination) {
      pagination.addEventListener('pageChange', handlePageChange as EventListener);
      return () => pagination.removeEventListener('pageChange', handlePageChange as EventListener);
    }
  }, []);
  
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'Active': return '#28a745';
      case 'Pending': return '#ffc107';
      case 'Inactive': return '#6c757d';
      default: return '#007bff';
    }
  };
  
  return (
    <div style={{
      maxWidth: '800px',
      margin: '0 auto',
      padding: '2rem',
      display: 'flex',
      flexDirection: 'column',
      gap: '1.5rem'
    }}>
      <h1>Simple Data List</h1>
      
      {/* Search */}
      <ModusWcTextInput
        value={searchTerm}
        label="Search Items"
        placeholder="Enter search term..."
        size="md"
        onInputChange={handleSearchChange}
      />
      
      {/* Data Cards */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
        gap: '1rem'
      }}>
        {data.map((item) => (
          <ModusWcCard key={item.id}>
            <div style={{ padding: '1rem' }}>
              <h3 style={{ margin: '0 0 0.5rem 0' }}>{item.name}</h3>
              <p style={{ margin: '0.25rem 0', color: '#666' }}>
                <strong>ID:</strong> {item.id}
              </p>
              <p style={{ margin: '0.25rem 0', color: '#666' }}>
                <strong>Category:</strong> {item.category}
              </p>
              <div style={{ 
                display: 'flex', 
                alignItems: 'center', 
                gap: '0.5rem',
                marginTop: '0.5rem'
              }}>
                <strong>Status:</strong>
                <span style={{
                  padding: '2px 8px',
                  borderRadius: '4px',
                  fontSize: '0.875rem',
                  backgroundColor: getStatusColor(item.status),
                  color: 'white'
                }}>
                  {item.status}
                </span>
              </div>
            </div>
          </ModusWcCard>
        ))}
      </div>
      
      {/* Pagination Info and Controls */}
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: '1rem',
        backgroundColor: '#f8f9fa',
        borderRadius: '4px'
      }}>
        <span style={{ fontSize: '0.875rem', color: '#666' }}>
          Showing page {currentPage} of {totalPages} ({totalItems} total items)
        </span>
        
        <ModusWcPagination
          ref={paginationRef}
          page={currentPage}
          count={totalPages}
          size="md"
        />
      </div>
      
      {/* Reset Button */}
      <div style={{ display: 'flex', justifyContent: 'center' }}>
        <ModusWcButton
          color="secondary"
          variant="outlined"
          size="md"
          onClick={() => {
            setSearchTerm('');
            setCurrentPage(1);
          }}
        >
          Reset Search
        </ModusWcButton>
      </div>
      
      {searchTerm && (
        <div style={{
          padding: '1rem',
          backgroundColor: '#e7f3ff',
          borderRadius: '4px',
          textAlign: 'center'
        }}>
          <p style={{ margin: 0 }}>
            Searching for: <strong>"{searchTerm}"</strong>
          </p>
        </div>
      )}
    </div>
  );
};

export default SimpleDataList;
```

**Reasoning Process**

1. **Component Selection**: Chose `ModusWcPagination` for pagination controls, `ModusWcTextInput` for search functionality, `ModusWcCard` for data display, and `ModusWcButton` for actions - all core Modus components that provide consistent styling and behavior.

2. **State Management Strategy**: Used separate state variables for `currentPage`, `searchTerm`, and `data` to maintain clear separation of concerns and enable reactive updates when dependencies change.

3. **Event Handling Pattern**: Implemented proper event handling for Modus components using `useRef` and `useEffect` with proper cleanup to prevent memory leaks. Used `CustomEvent` typing for type safety.

4. **Data Generation Logic**: Created a mock data generator that responds to both pagination and search parameters, simulating real-world API behavior where search results would be paginated.

5. **Layout Design**: Used CSS Grid for responsive card layout with `auto-fit` and `minmax()` to ensure cards adapt to different screen sizes while maintaining minimum width.

6. **User Experience Features**: Added pagination information display, search term highlighting, and reset functionality to provide clear feedback about current state and easy navigation.

### Important Notes

**Technical Implementation:**
- **Event Listener Pattern**: ModusWcPagination requires manual event listener setup using `addEventListener('pageChange', handler)` with proper cleanup in useEffect return function
- **CustomEvent Typing**: Pagination events use `CustomEvent<{newPage: number}>` for type safety
- **Search Reset Logic**: Automatically resets to page 1 when search term changes to avoid showing empty results on higher pages
- **Ref Management**: Pagination component requires ref for event listener attachment

**Styling Considerations:**
- **Container Layout**: Used flexbox with consistent gap spacing for predictable layout
- **Card Grid**: CSS Grid with `auto-fit` ensures responsive behavior without media queries
- **Status Indicators**: Implemented color-coded status badges for visual data categorization
- **Visual Hierarchy**: Clear typography hierarchy with proper margin spacing

**State Synchronization:**
- **Dependency Array**: useEffect dependencies `[currentPage, searchTerm]` ensure data regenerates when either value changes
- **Page Reset**: Search functionality automatically resets page to 1 to prevent pagination edge cases
- **Real-time Updates**: Search input provides immediate feedback without debouncing for demo purposes

**Performance Patterns:**
- **Controlled Components**: Both search input and pagination are controlled components with React state
- **Event Cleanup**: Proper event listener cleanup prevents memory leaks in component unmounting
- **Efficient Rendering**: Card keys use stable `item.id` for optimal React reconciliation
---

# ModusWcProgress

## Prompt 1

**User Question:** I need to provide users with clear visual feedback on task completion, file uploads, data processing, and other long-running operations. The progress indicators should handle both known and unknown duration tasks while maintaining user engagement. How can I implement effective progress visualization systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing progress indication needs: user engagement during long operations, completion clarity, indeterminate state handling, visual accessibility, and integration with async workflows.

**Component Analysis:**
ModusWcProgress provides flexible progress visualization through `value/max` for determinate states, `indeterminate` for unknown duration tasks, and `variant` options for different visual contexts.

**Why I chose these properties:**
- **`value/max` pattern**: Provides precise completion tracking for measurable operations
- **`indeterminate` state**: Essential for operations with unknown duration like network requests
- **`label` property**: Enhances accessibility and user understanding of progress status
- **`variant` options**: 'default' for linear progress, 'radial' for compact circular displays
- **No events needed**: Progress is typically driven by external state changes rather than user interaction

**TypeScript Example:**
```tsx
import React, { useState, useEffect } from 'react';
import { ModusWcProgress, ModusWcButton, ModusWcCard } from '@trimble-oss/moduswebcomponents-react';

const FileUploader: React.FC = () => {
  // State for tracking upload
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [status, setStatus] = useState<string>('');
  const [isUploading, setIsUploading] = useState<boolean>(false);
  const [timerId, setTimerId] = useState<number | null>(null);
  
  // Handle file selection
  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files && files.length > 0) {
      setSelectedFile(files[0]);
      setStatus('');
      setUploadProgress(0);
    }
  };
  
  // Clean up timer when component unmounts
  useEffect(() => {
    return () => {
      if (timerId !== null) {
        window.clearInterval(timerId);
      }
    };
  }, [timerId]);
  
  // Start upload process (simulation)
  const handleUpload = () => {
    if (!selectedFile) return;
    
    setIsUploading(true);
    setUploadProgress(0);
    setStatus('Uploading...');
    
    // Simulate progress with a timer
    const timer = window.setInterval(() => {
      setUploadProgress(prev => {
        if (prev >= 100) {
          window.clearInterval(timer);
          setIsUploading(false);
          setStatus('Upload complete!');
          return 100;
        }
        return prev + 5;
      });
    }, 300);
    
    setTimerId(timer as unknown as number);
  };
  
  // Cancel the upload simulation
  const handleCancel = () => {
    if (timerId !== null) {
      window.clearInterval(timerId);
      setTimerId(null);
      setIsUploading(false);
      setStatus('Upload cancelled');
    }
  };
  
  // Trigger file input click
  const triggerFileSelect = () => {
    const fileInput = document.getElementById('file-input') as HTMLInputElement;
    fileInput?.click();
  };
  
  return (
    <div style={{
      maxWidth: '500px',
      margin: '0 auto',
      padding: '2rem',
      display: 'flex',
      flexDirection: 'column',
      gap: '1.5rem'
    }}>
      <ModusWcCard>
        <div style={{ padding: '1.5rem' }}>
          <h2 style={{ margin: '0 0 1.5rem 0' }}>File Upload</h2>
          
          <div style={{
            display: 'flex',
            flexDirection: 'column',
            gap: '1rem',
            marginBottom: '1.5rem'
          }}>
        <input
          type="file"
          onChange={handleFileChange}
          id="file-input"
          style={{ display: 'none' }}
        />
            <ModusWcButton
              variant="outlined"
              color="primary"
              size="md"
              onClick={triggerFileSelect}
            >
          Select File
            </ModusWcButton>
            <div style={{
              padding: '0.5rem',
              fontSize: '0.875rem',
              color: '#666',
              textAlign: 'center',
              backgroundColor: '#f8f9fa',
              borderRadius: '4px'
            }}>
          {selectedFile ? selectedFile.name : 'No file selected'}
            </div>
      </div>
      
          <div style={{ marginBottom: '1rem' }}>
        <ModusWcProgress
          value={uploadProgress}
          max={100}
          aria-label="File upload progress"
          label={`${uploadProgress}%`}
        />
      </div>
      
          {status && (
            <div style={{
              marginBottom: '1rem',
              fontSize: '0.875rem',
              color: '#666',
              textAlign: 'center',
              padding: '0.5rem',
              backgroundColor: status.includes('complete') ? '#d4edda' : 
                              status.includes('cancelled') ? '#f8d7da' : '#e2e3e5',
              borderRadius: '4px'
            }}>
              {status}
            </div>
          )}
          
          <div style={{
            display: 'flex',
            gap: '0.75rem',
            justifyContent: 'center'
          }}>
            <ModusWcButton
              variant="filled"
              color="primary"
              size="md"
          disabled={!selectedFile || isUploading}
              onClick={handleUpload}
        >
          Upload
            </ModusWcButton>
        {isUploading && (
              <ModusWcButton
                variant="outlined"
                color="danger"
                size="md"
                onClick={handleCancel}
              >
            Cancel
              </ModusWcButton>
        )}
      </div>
        </div>
      </ModusWcCard>
    </div>
  );
};

export default FileUploader;
```

**Notes:**
- Use the `value` and `max` properties to show determinate progress for operations where progress can be measured
- Set the `label` property to show a text description or percentage inside the progress bar
- The component doesn't emit events, so you need to update the value property from your application logic
- Make sure to handle error states and provide a way to cancel operations when appropriate
- Use custom CSS classes to style the progress bar's color, height, or other visual properties
- For upload scenarios, track progress using XHR's upload progress events and update the progress value accordingly


---

# ModusWcRadio

## Prompt 1
**User Question:** I need to implement single-choice selection interfaces where users must choose exactly one option from mutually exclusive alternatives. The controls should provide clear visual feedback, support form validation, and maintain accessibility standards. How can I build effective radio button group systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing radio group requirements: mutually exclusive selection enforcement, clear visual feedback, form validation integration, accessibility compliance, and state management across grouped options.

**Component Analysis:**
ModusWcRadio provides controlled selection through `value` boolean, group coordination via `name` property, and comprehensive interaction handling through change/focus/blur events.

**Why I chose these properties:**
- **`value` boolean pattern**: Explicit control over selection state while maintaining group exclusivity
- **`name` grouping**: Ensures semantic relationship and mutual exclusion behavior
- **`label` and `inputId`**: Provides accessibility compliance and clear user guidance
- **Event coordination**: `inputChange` enables centralized state management for group behavior
- **`required` validation**: Supports form validation and user guidance patterns
  
**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcRadio } from '@trimble-oss/moduswebcomponents-react';

interface RadioOption {
  id: string;
  label: string;
  value: string;
}

const RadioGroupExample: React.FC = () => {
  const [selectedValue, setSelectedValue] = useState('vanilla');
  const options: RadioOption[] = [
    { id: 'vanilla-opt', label: 'Vanilla', value: 'vanilla' },
    { id: 'chocolate-opt', label: 'Chocolate', value: 'chocolate' },
    { id: 'strawberry-opt', label: 'Strawberry', value: 'strawberry' }
  ];

  const handleSelectionChange = (selectedOption: string) => {
    setSelectedValue(selectedOption);
  };

  const renderRadioButtons = () => {
    return options.map((option) => {
      const radioRef = useRef<HTMLModusWcRadioElement>(null);
      
      useEffect(() => {
        const element = radioRef.current;
        if (element) {
          const handleChange = () => {
            handleSelectionChange(option.value);
          };
          
          element.addEventListener('inputChange', handleChange);
          
          return () => {
            element.removeEventListener('inputChange', handleChange);
          };
        }
      }, [option.value]);
      
      return (
        <ModusWcRadio
          key={option.id}
          ref={radioRef}
          inputId={option.id}
          name="flavor-choice"
          label={option.label}
          value={selectedValue === option.value}
        />
      );
    });
  };

  return (
    <div>
      <h3>Select your favorite flavor:</h3>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
        {renderRadioButtons()}
      </div>
      <p>Selected flavor: {selectedValue}</p>
    </div>
  );
};

export default RadioGroupExample;
```

**Notes:**
- Radio buttons should be grouped using the same `name` property
- Unlike standard HTML radio inputs, ModusWcRadio uses a boolean `value` prop to indicate selection state
- You must manually track which option is selected in your state management
- For accessibility, provide unique `inputId` values and ensure labels are properly associated

## Prompt 2

**User Question:** How can I implement form validation with radio button groups using the Modus Radio component?

**Agent Answer:**
References:
- **Properties**:
  - **required** (boolean): Indicates if selection is required 
  - **disabled** (boolean): Disables the radio when true
  - **customClass** (string): Custom CSS class for styling
  - **inputTabIndex** (number): Controls tab navigation order

- **Events**:
  - **inputBlur**: `CustomEvent<FocusEvent>` - Useful for validation on field exit
  - **inputChange**: `CustomEvent<InputEvent>` - Used to track selection changes

- **Usage Patterns**:
  - Validate radio group selection on form submission
  - Display validation messages when appropriate
  - Group radio buttons with fieldset and legend for proper accessibility

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect, FormEvent } from 'react';
import { 
  ModusWcRadio, 
  ModusWcInputFeedback, 
  ModusWcButton 
} from '@trimble-oss/moduswebcomponents-react';

interface SubscriptionOption {
  id: string;
  label: string;
  value: string;
}

const ValidatedRadioForm: React.FC = () => {
  const [selectedPlan, setSelectedPlan] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [submitted, setSubmitted] = useState(false);
  const feedbackRef = useRef<HTMLModusWcInputFeedbackElement>(null);
  
  const subscriptionOptions: SubscriptionOption[] = [
    { id: 'plan-basic', label: 'Basic ($10/month)', value: 'basic' },
    { id: 'plan-premium', label: 'Premium ($20/month)', value: 'premium' },
    { id: 'plan-professional', label: 'Professional ($30/month)', value: 'professional' }
  ];
  
  // Validate whenever selection or submission state changes
  useEffect(() => {
    if (submitted) {
      validateSelection();
    }
  }, [selectedPlan, submitted]);
  
  const validateSelection = () => {
    if (!selectedPlan) {
      setError('Please select a subscription plan');
      if (feedbackRef.current) {
        feedbackRef.current.hidden = false;
      }
      return false;
    }
    
    setError(null);
    if (feedbackRef.current) {
      feedbackRef.current.hidden = true;
    }
    return true;
  };
  
  const handleSubmit = (e: FormEvent) => {
    e.preventDefault();
    setSubmitted(true);
    
    if (validateSelection()) {
      // Form is valid, proceed with submission
      console.log(`Selected plan: ${selectedPlan}`);
      alert(`Form submitted with plan: ${selectedPlan}`);
    }
  };
  
  const createRadioHandler = (value: string) => {
    return () => {
      setSelectedPlan(value);
    };
  };
  
  return (
    <form onSubmit={handleSubmit}>
      <fieldset style={{ border: '1px solid #ccc', padding: '16px', marginBottom: '16px' }}>
        <legend>Choose a subscription plan (Required)</legend>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
          {subscriptionOptions.map((option) => {
            const radioRef = useRef<HTMLModusWcRadioElement>(null);
            
            useEffect(() => {
              const element = radioRef.current;
              if (element) {
                const handleChange = () => {
                  createRadioHandler(option.value)();
                };
                
                element.addEventListener('inputChange', handleChange);
                
                return () => {
                  element.removeEventListener('inputChange', handleChange);
                };
              }
            }, [option.value]);
            
            return (
              <ModusWcRadio
                key={option.id}
                ref={radioRef}
                inputId={option.id}
                name="subscription-plan"
                label={option.label}
                required={true}
                value={selectedPlan === option.value}
              />
            );
          })}
        </div>
      </fieldset>
      
      <ModusWcInputFeedback
        ref={feedbackRef}
        message={error || ''}
         level="error"
        hidden={!error}
      />
      
      <ModusWcButton type="submit" color="primary" style={{ marginTop: '16px' }}>
        Submit
      </ModusWcButton>
    </form>
  );
};

export default ValidatedRadioForm;
```

**Notes:**
- Radio button groups should be wrapped in a `<fieldset>` with a `<legend>` for accessibility
- The `required` property should be set on each radio in the group
- Form validation should check if any radio is selected (has `value={true}`)
- Use ModusWcInputFeedback to display validation error messages
- Remember to handle both initial form submission and real-time validation as selections change
- For proper accessibility, ensure error messages are properly associated with the input group

---

# ModusWcRating

## Prompt 1
**User Question:** I'm building a comprehensive feedback and evaluation system that needs sophisticated rating mechanisms across different contexts - product reviews with detailed criteria, performance evaluations with weighted scoring, and user experience feedback with contextual rating scales. The rating system should support various visual styles, granular input options, and accessibility standards. How should I approach implementing a flexible rating system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive rating requirement, I considered:
1. **Context Adaptation**: Different evaluation contexts require different visual representations and granularity levels
2. **User Experience Patterns**: Rating interfaces should match user mental models and provide appropriate feedback granularity
3. **Accessibility Standards**: Rating components must be keyboard navigable and provide clear value communication for assistive technology
4. **Data Quality**: Half-step ratings and multiple criteria enable more nuanced feedback collection

**Component Analysis:**
I examined the ModusWcRating component architecture and found it's designed for flexible evaluation input:
- **Visual Variety**: `variant` property provides different rating metaphors (stars, hearts, smileys, thumbs) for different contexts
- **Granularity Control**: `allowHalf` enables precise rating input for detailed evaluations
- **Scale Flexibility**: `count` property adapts rating scales to different evaluation needs
- **Accessibility Integration**: `getAriaLabelText` ensures clear value communication for screen readers

**Why I chose these properties:**
- **`variant` selection**: Critical for context matching - 'star' for general quality, 'heart' for preference, 'smiley' for satisfaction, 'thumb' for approval
- **`allowHalf` precision**: Enables nuanced feedback collection - essential for detailed product reviews and performance evaluations
- **`count` adaptation**: Different contexts need different scales - 5-star for general ratings, 10-point for detailed evaluations
- **`size` hierarchy**: Adapts to interface importance - 'lg' for primary ratings, 'sm' for secondary criteria
- **Event handling**: `ratingChange` provides complete rating context for analytics and validation

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcRating, ModusWcButton, ModusWcCard } from '@trimble-oss/moduswebcomponents-react';

interface RatingItem {
  id: string;
  label: string;
  description: string;
}

const SimpleRatingForm: React.FC = () => {
  const [ratings, setRatings] = useState<{ [key: string]: number }>({});
  const [submitted, setSubmitted] = useState(false);

  const ratingItems: RatingItem[] = [
    {
      id: 'quality',
        label: 'Overall Quality',
      description: 'How would you rate the overall quality?'
    },
    {
      id: 'value',
        label: 'Value for Money',
      description: 'How satisfied are you with the value?'
    },
    {
      id: 'design',
      label: 'Design & Appearance',
      description: 'How do you like the design?'
    },
    {
      id: 'recommend',
      label: 'Recommendation',
      description: 'Would you recommend this to others?'
    }
  ];

  const handleRatingChange = (itemId: string, newRating: number) => {
    setRatings(prev => ({
        ...prev,
      [itemId]: newRating
    }));
  };

  const handleSubmit = () => {
    console.log('Ratings submitted:', ratings);
    setSubmitted(true);
    
    // Reset after 2 seconds
      setTimeout(() => {
      setSubmitted(false);
      setRatings({});
      }, 2000);
  };

  const handleReset = () => {
    setRatings({});
    setSubmitted(false);
  };

  const allRated = ratingItems.every(item => ratings[item.id] > 0);
  
  return (
    <div style={{
      maxWidth: '600px',
      margin: '0 auto',
      padding: '2rem',
                  display: 'flex',
      flexDirection: 'column',
      gap: '1.5rem'
    }}>
      <ModusWcCard>
        <div style={{ padding: '2rem' }}>
          <h2 style={{ margin: '0 0 1.5rem 0', textAlign: 'center' }}>
            Product Rating
          </h2>
          
          {ratingItems.map((item) => (
            <div key={item.id} style={{ marginBottom: '2rem' }}>
              <h3 style={{ margin: '0 0 0.5rem 0', fontSize: '1.1rem' }}>
                {item.label}
                </h3>
              <p style={{ 
                margin: '0 0 1rem 0', 
                fontSize: '0.9rem', 
                color: '#666' 
              }}>
                {item.description}
              </p>
              
              <div style={{
                display: 'flex',
                alignItems: 'center',
                gap: '1rem'
              }}>
                <ModusWcRating
                  value={ratings[item.id] || 0}
                  variant="star"
                  count={5}
                  allowHalf={false}
                  size="lg"
                  onRatingChange={(e: CustomEvent) => {
                    handleRatingChange(item.id, e.detail.newRating);
                  }}
                />
                <span style={{ fontSize: '1rem', color: '#666' }}>
                  {ratings[item.id] ? `${ratings[item.id]}/5` : 'Not rated'}
                </span>
                </div>
              </div>
          ))}
          
          <div style={{
            display: 'flex',
            gap: '1rem',
            justifyContent: 'center',
            marginTop: '2rem'
          }}>
            <ModusWcButton
              variant="outlined"
              color="secondary"
              size="md"
              onClick={handleReset}
              disabled={submitted}
            >
              Reset
            </ModusWcButton>
            
            <ModusWcButton
              variant="filled"
              color="primary"
              size="md"
              onClick={handleSubmit}
              disabled={!allRated || submitted}
            >
              {submitted ? 'Submitted!' : 'Submit Rating'}
            </ModusWcButton>
          </div>
          
          {!allRated && Object.keys(ratings).length > 0 && (
            <div style={{
              textAlign: 'center',
              marginTop: '1rem',
              fontSize: '0.875rem',
              color: '#666'
            }}>
              Please rate all items to submit
            </div>
          )}
        </div>
      </ModusWcCard>
    </div>
  );
};

export default SimpleRatingForm;
```

**Implementation Decisions & Rationale:**

**Context-Adaptive Design:**
- **Variant Selection Strategy**: Stars for general quality ratings, hearts for preference/aesthetics, smileys for satisfaction measures, thumbs for binary approval
- **Scale Adaptation**: 5-point scales for general ratings, 10-point for detailed performance evaluations, 7-point for usability (matching standard UX research scales)
- **Granularity Control**: Half-ratings enabled for nuanced feedback where precision matters, disabled for simple satisfaction measures

**Weighted Scoring System:**
- **Criterion Weighting**: Different aspects have different importance - overall quality and recommendation carry more weight than aesthetic preferences
- **Normalized Calculation**: All ratings normalized to 0-1 scale before weighting, enabling fair comparison across different scales
- **Real-time Feedback**: Weighted score updates as users provide ratings, showing immediate impact of their feedback

**User Experience Optimization:**
- **Progressive Disclosure**: Required ratings clearly marked, progress tracking helps users understand completion status
- **Contextual Validation**: Real-time validation with clear error messaging guides users toward completion
- **Accessibility Integration**: Variant-specific ARIA labels provide meaningful context for screen reader users understanding different rating metaphors


---

# ModusWcSelect

## Prompt 1
**User Question:** I need to implement dropdown selection interfaces that handle dynamic option sets, provide clear user guidance, and integrate with complex form workflows. The selects should support validation, accessibility, and various data sources. How can I build flexible dropdown systems?

**Agent Answer:**

**My Reasoning Process:**
Analyzing dropdown requirements: dynamic option management, user selection clarity, validation integration, accessibility compliance, and data source flexibility across different interaction contexts.

**Component Analysis:**
ModusWcSelect provides structured option management through `options` array, controlled selection via `value` property, and comprehensive user feedback through `feedback` object with validation support.

**Why I chose these properties:**
- **`e.detail.target.value`** : Standard Modus Web Component event pattern where `detail` contains the event payload and `target.value` provides the selected option's value from the component instance.
- **`options` array structure**: Enables dynamic option generation from data sources with clear label/value separation
- **`value` controlled pattern**: Provides predictable state management and form integration
- **`feedback` system**: Structured validation messaging with visual hierarchy for user guidance
- **Event handling**: `inputChange/Blur/Focus` supports validation workflows and user interaction tracking
- **`required/disabled` states**: Form control integration and conditional user experience patterns

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcSelect, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface ISelectOption {
  label: string;
  value: string;
  disabled?: boolean;
}

const CountryForm: React.FC = () => {
  // State for selected value and validation
  const [selectedCountry, setSelectedCountry] = useState<string>('');
  const [isTouched, setIsTouched] = useState(false);
  const [feedback, setFeedback] = useState<{ level: 'error' | 'info' | 'success' | 'warning', message: string } | undefined>(undefined);
  
  // Reference to the select element
  const selectRef = useRef<HTMLModusWcSelectElement>(null);
  
  // Country options
  const countryOptions: ISelectOption[] = [
    { label: 'Select a country', value: '', disabled: true },
    { label: 'United States', value: 'us' },
    { label: 'Canada', value: 'ca' },
    { label: 'Mexico', value: 'mx' },
    { label: 'United Kingdom', value: 'uk' },
    { label: 'France', value: 'fr' },
    { label: 'Germany', value: 'de' },
    { label: 'Japan', value: 'jp' },
    { label: 'Australia', value: 'au' },
    { label: 'Brazil', value: 'br' },
    { label: 'India', value: 'in' }
  ];
  
  // Get country name from value
  const getCountryName = (value: string): string => {
    const country = countryOptions.find(option => option.value === value);
    return country ? country.label : '';
  };
  
  // Validate selection and update feedback
  const validateSelection = () => {
    if (isTouched && !selectedCountry) {
      setFeedback({ level: 'error', message: 'Please select a country' });
      return false;
    }
    
    if (selectedCountry) {
      setFeedback({ level: 'success', message: 'Country selected' });
    } else {
    setFeedback(undefined);
    }
    return true;
  };
  
  // Validate on selection changes
  useEffect(() => {
    if (isTouched) {
      validateSelection();
    }
    
    // Console log the selected country name
    if (selectedCountry) {
      const countryName = getCountryName(selectedCountry);
      console.log(`Selected country: ${countryName}`);
    }
  }, [selectedCountry, isTouched]);
  
  // Setup event listeners
  useEffect(() => {
    const select = selectRef.current;
    if (!select) return;
    
    // Handle selection change
    const handleChange = (e: CustomEvent) => {
      console.log('handleChange', e.detail.target.value);
      setSelectedCountry(e.detail.target.value);
    };
    
    // Handle blur for validation
    const handleBlur = () => {
      setIsTouched(true);
      validateSelection();
    };
    
    select.addEventListener('inputChange', handleChange as EventListener);
    select.addEventListener('inputBlur', handleBlur as EventListener);
    
    return () => {
      select.removeEventListener('inputChange', handleChange as EventListener);
      select.removeEventListener('inputBlur', handleBlur as EventListener);
    };
  }, []);
  
  // Handle form submission
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setIsTouched(true);
    
    if (selectedCountry) {
      const countryName = getCountryName(selectedCountry);
      alert(`Form submitted! Selected country: ${countryName}`);
    } else {
      setFeedback({ level: 'error', message: 'Please select a country before submitting' });
    }
  };
  
  return (
    <div style={{
      maxWidth: '400px',
      margin: '0 auto',
      padding: '2rem',
      display: 'flex',
      flexDirection: 'column',
      gap: '1.5rem'
    }}>
      <h2 style={{ textAlign: 'center', margin: '0 0 1rem 0' }}>
        Country Selection Form
      </h2>
      
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: '1.5rem' }}>
      <ModusWcSelect
        ref={selectRef}
        label="Country"
        options={countryOptions}
        value={selectedCountry}
        required={true}
        feedback={feedback}
        size="md"
        bordered={true}
      />
    </div>
        
        <div style={{ textAlign: 'center' }}>
          <ModusWcButton
            type="submit"
            variant="filled"
            color="primary"
            size="md"
            disabled={!selectedCountry}
          >
            Submit
          </ModusWcButton>
        </div>
    </form>
      
      {selectedCountry && (
        <div style={{
          padding: '1rem',
          backgroundColor: '#e7f3ff',
          borderRadius: '4px',
          textAlign: 'center',
          fontSize: '0.875rem'
        }}>
          Currently selected: <strong>{getCountryName(selectedCountry)}</strong>
        </div>
      )}
    </div>
  );
};

export default CountryForm;
```

**Notes:**
- The `options` property requires an array of objects with `label` and `value` properties
- Each option can also have an optional `disabled` property to prevent selection
- Use the `feedback` property to display validation messages below the select
- Listen for the `inputChange` event to respond to user selections
- Combine with `inputBlur` event for validation on field exit
- For accessibility, ensure proper labels and ARIA attributes

## Prompt 2

**User Question:** Create a searchable multi-select component using Modus Web Components that allows users to search through options, select multiple items, and display them as removable chips.

**Agent Answer:**
References:
- **Properties**:
  - **ModusWcTextInput.onInputChange** (function): Event handler for input changes using `e.detail.target.value`
  - **ModusWcSelect.onInputChange** (function): Event handler for selection changes using `e.detail.target.value`
  - **ModusWcSelect.options** (ISelectOption[]): Array of option objects with `label`, `value` properties
  - **ModusWcChip.showRemove** (boolean): Shows the remove button on chips
  - **ModusWcButton.variant** (string): Button styling variant ('filled' | 'outlined')
  
- **Events**:
  - **inputChange**: `CustomEvent` - Fired by both TextInput and Select, access value via `e.detail.target.value`
  - **chipRemove**: `CustomEvent` - Fired when chip remove button is clicked, requires addEventListener pattern
  
- **Usage Patterns**:
  - Combine ModusWcTextInput for search, ModusWcSelect for options, ModusWcChip for selected items
  - Use `e.detail.target.value` consistently for all Modus Web Component events
  - Filter options dynamically to exclude already selected items
  - Separate component for chip handling with proper event cleanup

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcTextInput, ModusWcSelect, ModusWcChip, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface Option {
  label: string;
  value: string;
}

const SimpleMultiSelect: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [selectedValues, setSelectedValues] = useState<string[]>([]);
  const [selectValue, setSelectValue] = useState<string>('');
  
  // All available options
  const allOptions: Option[] = [
    { label: 'JavaScript', value: 'js' },
    { label: 'TypeScript', value: 'ts' },
    { label: 'Python', value: 'py' },
    { label: 'Java', value: 'java' },
    { label: 'C#', value: 'cs' },
    { label: 'Ruby', value: 'rb' },
    { label: 'Go', value: 'go' },
    { label: 'Rust', value: 'rs' },
    { label: 'PHP', value: 'php' },
    { label: 'Swift', value: 'swift' },
  ];
  
  // Filter options based on search and exclude already selected
  const getFilteredOptions = () => {
    const searchFilter = searchTerm.toLowerCase();
    return allOptions.filter(option => 
        !selectedValues.includes(option.value) && 
        option.label.toLowerCase().includes(searchFilter)
      );
  };
  
  // Get selected options with full data
  const getSelectedOptions = () => {
    return selectedValues.map(value => 
      allOptions.find(option => option.value === value)
    ).filter(Boolean) as Option[];
  };
  
  // Handle search input - CRITICAL: Use e.detail.target.value for Modus events
  const handleSearch = (e: CustomEvent) => {
    setSearchTerm(e.detail.target.value || '');
  };
  
  // Handle selection - CRITICAL: Use e.detail.target.value for Modus events
  const handleSelect = (e: CustomEvent) => {
    const value = e.detail.target.value;
    console.log('Selected:', value);
    
    if (value && !selectedValues.includes(value)) {
        setSelectedValues(prev => [...prev, value]);
      setSelectValue(''); // Reset dropdown
      setSearchTerm(''); // Clear search
    }
  };
  
  // Remove selected item
  const removeItem = (valueToRemove: string) => {
    setSelectedValues(prev => prev.filter(v => v !== valueToRemove));
  };
  
  // Clear all selections
  const clearAll = () => {
    setSelectedValues([]);
    setSearchTerm('');
    setSelectValue('');
  };
  
  const filteredOptions = getFilteredOptions();
  const selectedOptions = getSelectedOptions();
  
  // Add placeholder option to filtered results
  const selectOptions = filteredOptions.length > 0 
    ? [{ label: '-- Select an option --', value: '' }, ...filteredOptions]
    : [{ label: 'No options available', value: '' }];
  
  return (
    <div style={{
      maxWidth: '600px',
      margin: '0 auto',
      padding: '2rem',
      display: 'flex',
      flexDirection: 'column',
      gap: '1rem'
    }}>
      <h2>Programming Languages Multi-Select</h2>
      
      {/* Search Input */}
        <ModusWcTextInput
        label="Search Languages"
        placeholder="Type to filter options..."
          value={searchTerm}
        onInputChange={handleSearch}
        />
      
      {/* Selection Dropdown */}
      <ModusWcSelect
        label="Available Options"
        options={selectOptions}
        value={selectValue}
        onInputChange={handleSelect}
        disabled={filteredOptions.length === 0}
      />
      
      {/* Selected Items as Chips */}
      <div>
        <h3>Selected Languages ({selectedOptions.length})</h3>
        <div style={{
        display: 'flex', 
        flexWrap: 'wrap',
          gap: '0.5rem',
          minHeight: '40px',
          padding: '0.5rem',
          border: '1px solid #ccc',
          borderRadius: '4px',
          backgroundColor: '#f9f9f9'
        }}>
          {selectedOptions.length === 0 ? (
            <span style={{ color: '#666', fontStyle: 'italic' }}>
              No languages selected
            </span>
          ) : (
            selectedOptions.map((option) => (
              <ChipWithRemove
                key={option.value}
                option={option}
                onRemove={() => removeItem(option.value)}
              />
            ))
          )}
        </div>
      </div>
      
      {/* Action Buttons */}
      <div style={{ display: 'flex', gap: '1rem', justifyContent: 'center' }}>
        <ModusWcButton
          variant="outlined"
              color="secondary"
          onClick={clearAll}
          disabled={selectedValues.length === 0}
        >
          Clear All
        </ModusWcButton>
        
        <ModusWcButton
          variant="filled"
          color="primary"
          onClick={() => alert(`Selected: ${selectedOptions.map(o => o.label).join(', ')}`)}
          disabled={selectedValues.length === 0}
        >
          Show Selected
        </ModusWcButton>
          </div>
      
      {/* Debug Info */}
      <div style={{
        fontSize: '0.8rem',
        color: '#666',
        padding: '0.5rem',
        backgroundColor: '#f0f0f0',
        borderRadius: '4px'
      }}>
        <div>Search: "{searchTerm}"</div>
        <div>Available: {filteredOptions.length}</div>
        <div>Selected: {selectedValues.join(', ')}</div>
      </div>
    </div>
  );
};

// Separate component for chips with proper event handling
interface ChipProps {
  option: Option;
  onRemove: () => void;
}

const ChipWithRemove: React.FC<ChipProps> = ({ option, onRemove }) => {
  const chipRef = useRef<HTMLModusWcChipElement>(null);
  
  useEffect(() => {
    const chip = chipRef.current;
    if (!chip) return;
    
    const handleRemove = () => {
      onRemove();
    };
    
    chip.addEventListener('chipRemove', handleRemove);
    
    return () => {
      chip.removeEventListener('chipRemove', handleRemove);
    };
  }, [onRemove]);
  
  return (
    <ModusWcChip
      ref={chipRef}
      label={option.label}
      showRemove={true}
      variant="filled"
      size="md"
    />
  );
};

export default SimpleMultiSelect;
```

**Notes:**
- **Critical Event Pattern**: Always use `e.detail.target.value` for ALL Modus Web Component events (TextInput, Select, etc.)
- **Multi-Component Architecture**: Since ModusWcSelect doesn't support native multi-select, combine multiple Modus components
- **Dynamic Filtering**: Real-time search filtering with exclusion of already selected items
- **Chip Event Handling**: ModusWcChip requires `addEventListener('chipRemove')` pattern, not onChipRemove prop
- **State Management**: Use computed values (getFilteredOptions, getSelectedOptions) instead of additional state variables
- **UX Enhancements**: Include placeholder options, debug panel, and action buttons for better user experience
- **TypeScript Safety**: Proper typing with CustomEvent and Option interfaces
- **Event Cleanup**: Always implement proper cleanup in useEffect for addEventListener patterns
- **Reset Pattern**: Clear search and select values after each selection for smooth workflow
---

# ModusWcSideNavigation

## Prompt 1
**User Question:** I'm building a comprehensive application architecture that requires sophisticated navigation systems - multi-level menu hierarchies, contextual navigation based on user roles, responsive behavior across devices, and integration with complex routing systems. The navigation should provide clear information architecture while supporting efficient user workflows. How should I implement a robust side navigation system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive navigation requirement, I considered:
1. **Information Architecture**: Complex applications need hierarchical navigation that scales with content depth and user permissions
2. **Responsive Behavior**: Side navigation must adapt seamlessly between desktop sidebar and mobile overlay patterns
3. **Context Awareness**: Navigation should reflect current location and provide relevant options based on user role and application state
4. **Integration Complexity**: Navigation systems must coordinate with routing, authentication, and application state management

**Component Analysis:**
I examined the ModusWcSideNavigation component architecture and found it's designed for flexible navigation patterns:
- **Controlled Expansion**: `expanded` property enables programmatic control for responsive behavior and user preference management
- **Flexible Sizing**: `maxWidth` property adapts to content needs and layout constraints
- **Interaction Management**: `collapseOnClickOutside` provides appropriate mobile behavior patterns
- **Content Integration**: Works seamlessly with ModusWcMenu and ModusWcMenuItem for hierarchical content organization

**Why I chose these properties:**
- **`expanded` control**: Essential for responsive navigation - enables overlay mode on mobile, sidebar mode on desktop
- **`maxWidth` flexibility**: Adapts to content complexity - narrow for simple menus, wider for detailed navigation with descriptions
- **`collapseOnClickOutside`**: Critical for mobile UX - prevents navigation from blocking content access on touch devices
- **Menu component integration**: Provides semantic navigation structure with proper accessibility roles and keyboard navigation

References:
- **Properties**:
  - **expanded** (boolean): Controls whether the side navigation is expanded or collapsed
  - **maxWidth** (string): Sets the maximum width of the expanded navigation panel
  - **collapseOnClickOutside** (boolean): Controls if navigation collapses when clicking elsewhere
  - **customClass** (string): Custom CSS class for additional styling

- **Events**:
  - No custom events; typically used with ModusWcNavbar's "mainMenuOpenChange" event
  - Combined with ModusWcMenu and ModusWcMenuItem for navigation options

- **Usage Patterns**:
  - Side navigation works as a companion to ModusWcNavbar
  - Contains ModusWcMenu with ModusWcMenuItem components for navigation options
  - Typically toggled by the hamburger menu in the navbar


**TypeScript Example:**
```tsx
import React, { useState, useEffect, useRef } from 'react';
import { 
  ModusWcSideNavigation,
  ModusWcNavbar,
  ModusWcMenu,
  ModusWcMenuItem
} from '@trimble-oss/moduswebcomponents-react';

// Interface definitions for better TypeScript support
interface INavbarUserCard {
  avatarAlt?: string;
  avatarSrc?: string;
  email: string;
  name: string;
  myTrimbleButton?: string;
  signOutButton?: string;
}

interface INavbarVisibility {
  ai?: boolean;
  apps?: boolean;
  help?: boolean;
  mainMenu?: boolean;
  notifications?: boolean;
  search?: boolean;
  searchInput?: boolean;
  user?: boolean;
}

interface MenuItem {
  id: string;
  label: string;
  icon: string;
  path: string;
}

const AppLayout: React.FC = () => {
  // State for side navigation
  const [isExpanded, setIsExpanded] = useState(false);
  const [activeItemId, setActiveItemId] = useState('home');
  
  // Refs for components
  const navbarRef = useRef<HTMLModusWcNavbarElement>(null);
  const sideNavRef = useRef<HTMLModusWcSideNavigationElement>(null);
  
  // Apply classic-light theme on component mount
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', 'modus-classic-light');
    document.documentElement.setAttribute('data-mode', 'light');
    document.documentElement.classList.add('light');
    
    // Cleanup on unmount
    return () => {
      document.documentElement.removeAttribute('data-theme');
      document.documentElement.removeAttribute('data-mode');
      document.documentElement.classList.remove('light');
    };
  }, []);
  
  // User information - following React component pattern
  const userCard: INavbarUserCard = {
    name: 'John Doe',
    email: 'john.doe@example.com',
    avatarSrc: 'https://i.pravatar.cc/150?img=12',
    avatarAlt: 'John Doe Avatar'
  };
  
  // Visibility configuration - following React component pattern
  const visibility: INavbarVisibility = {
    apps: true,
    help: true,
    mainMenu: true,
    notifications: true,
    search: true,
    searchInput: false,
    user: true
  };
  
  // Text overrides for customization
  const textOverrides = {
    help: 'Support',
    notifications: 'Alerts'
  };
  
  // Menu items data with correct Modus icon names
  const menuItems: MenuItem[] = [
    { id: 'home', label: 'Home', icon: 'home', path: '/' },
    { id: 'profile', label: 'Profile', icon: 'person', path: '/profile' },
    { id: 'settings', label: 'Settings', icon: 'gears', path: '/settings' },
    { id: 'projects', label: 'Projects', icon: 'folder_open', path: '/projects' },
    { id: 'reports', label: 'Reports', icon: 'bar_graph', path: '/reports' }
  ];
  
  // Handle navbar main menu toggle - following Storybook pattern
  useEffect(() => {
    const handleMainMenuOpenChange = () => {
      const sideNav = sideNavRef.current;
      if (sideNav) {
        const newExpanded = !isExpanded;
        setIsExpanded(newExpanded);
        sideNav.expanded = newExpanded;
        console.log('Side navigation toggled:', newExpanded);
      }
    };

    // Listen at document level as in Storybook example
    document.addEventListener('mainMenuOpenChange', handleMainMenuOpenChange);
    
    return () => {
      document.removeEventListener('mainMenuOpenChange', handleMainMenuOpenChange);
    };
  }, [isExpanded]);
  
  // Handle menu item selection - following Storybook pattern
  const handleMenuItemSelect = (item: MenuItem) => {
    setActiveItemId(item.id);
    
    // Collapse side nav after selection (like in Storybook)
    const sideNav = sideNavRef.current;
    if (sideNav) {
      sideNav.expanded = false;
      setIsExpanded(false);
    }
    
    console.log(`Navigating to: ${item.label} (${item.path})`);
  };
  
  // Render content based on active item - simplified to just titles
  const renderContent = () => {
    const titleStyle = {
      margin: '0',
      padding: '1rem 0',
      color: '#212529',
      fontSize: '2.5rem',
      fontWeight: 'bold' as const
    };

    switch (activeItemId) {
      case 'home':
        return <h1 style={titleStyle}>🏠 Home</h1>;
      case 'profile':
        return <h1 style={titleStyle}>👤 Profile</h1>;
      case 'settings':
        return <h1 style={titleStyle}>⚙️ Settings</h1>;
      case 'projects':
        return <h1 style={titleStyle}>📁 Projects</h1>;
      case 'reports':
        return <h1 style={titleStyle}>📊 Reports</h1>;
      default:
        return <h1 style={titleStyle}>Select an item from the side navigation</h1>;
    }
  };
  
  return (
    <div style={{ 
      display: 'flex', 
      flexDirection: 'column', 
      height: '100vh',
      width: '100vw',
      margin: 0,
      padding: 0,
      boxShadow: 'rgba(36, 35, 45, 0.3) 1px 0 4px'
    }}>
      {/* Navbar - Following Storybook pattern with React props */}
      <ModusWcNavbar
        ref={navbarRef}
        userCard={userCard}
        visibility={visibility}
        textOverrides={textOverrides}
        style={{ 
          zIndex: 2,
          boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)'
        }}
      />
      
      {/* Main content row - Following Storybook pattern */}
      <div style={{ 
        display: 'flex', 
        flex: 1, 
        overflow: 'hidden'
      }}>
        {/* ModusWcSideNavigation - Following Storybook pattern */}
        <ModusWcSideNavigation
          ref={sideNavRef}
          expanded={isExpanded}
          collapseOnClickOutside={true}
          maxWidth="256px"
          style={{
            height: '100%',
            alignSelf: 'flex-start',
            position: 'relative'
          }}
        >
          <ModusWcMenu size="lg">
            {menuItems.map((item) => (
              <ModusWcMenuItem
                key={item.id}
                label={item.label}
                value={item.id}
                startIcon={item.icon}
                selected={activeItemId === item.id}
                onItemSelect={() => handleMenuItemSelect(item)}
              />
            ))}
          </ModusWcMenu>
        </ModusWcSideNavigation>
        
        {/* Panel content - Following Storybook pattern */}
        <div style={{
          marginLeft: '4rem',
          padding: '3rem 2rem',
          flex: 1,
          overflow: 'auto',
          background: '#f8f9fa'
        }}>
          <div style={{
            maxWidth: '800px',
            background: '#ffffff',
            padding: '3rem',
            borderRadius: '8px',
            boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
            minHeight: '200px'
          }}>
            <div style={{ marginBottom: '2rem' }}>
              {renderContent()}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AppLayout;
```

**Notes:**
- Side Navigation is typically used alongside ModusWcNavbar and toggled by the hamburger menu
- Use ModusWcMenu and ModusWcMenuItem components inside the side navigation for navigation options
- For responsive design, consider collapsing the navigation automatically on mobile devices
- The `collapseOnClickOutside` property improves UX on mobile by automatically closing the menu
- You can control the width of the expanded panel with the `maxWidth` property
- When using with routing, update the active menu item based on the current route


---

# ModusWcSkeleton

## Prompt 1
**User Question:** I need to maintain user engagement during data loading by providing visual placeholders that match the expected content structure. The loading states should feel responsive, reduce perceived wait time, and seamlessly transition to real content. How can I implement effective loading placeholder systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing loading state requirements: user engagement maintenance, perceived performance improvement, content structure mimicking, smooth transitions, and loading state clarity.

**Component Analysis:**
ModusWcSkeleton provides structural loading placeholders through `width/height` sizing, content shape matching via `shape` property, and flexible composition for complex layouts.

**Why I chose these properties:**
- **`width/height` flexibility**: Enables precise content structure mimicking for seamless transitions
- **`shape` options**: 'circle' for avatars/icons, 'rectangle' for text and images
- **Multiple skeleton composition**: Creates realistic loading experiences that match final layouts
- **No events needed**: Loading states are driven by data fetching rather than user interaction
- **`customClass` styling**: Enables animation customization and brand-specific loading experiences
  
**TypeScript Example:**
```tsx
import React, { useState, useEffect } from 'react';
import { ModusWcSkeleton, ModusWcAvatar, ModusWcCard } from '@trimble-oss/moduswebcomponents-react';

interface ProfileData {
  id: string;
  name: string;
  title: string;
  bio: string;
  avatarUrl: string;
}

interface ProfileCardProps {
  userId: string;
  onProfileLoad?: (profile: ProfileData) => void;
}

const ProfileCard: React.FC<ProfileCardProps> = ({ userId, onProfileLoad }) => {
  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    // Reset states when userId changes
    setLoading(true);
    setError(null);
    
    // Simulated API call to fetch profile data
    const fetchProfile = async () => {
      try {
        // In real app, replace with actual API call
        await new Promise(resolve => setTimeout(resolve, 1500));
          // Mock data
        const profileData: ProfileData = {
          id: userId,
          name: 'Sarah Johnson',
          title: 'Senior Product Manager',
          bio: 'Product strategy expert with 8+ years of experience in SaaS and construction technology.',
          avatarUrl: `https://picsum.photos/200/200?random=${userId}`
        };
        
        setProfile(profileData);
        if (onProfileLoad) {
          onProfileLoad(profileData);
        }
      } catch (err) {
        setError('Failed to load profile data');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchProfile();
  }, [userId, onProfileLoad]);

  return (
    <ModusWcCard style={{ width: '100%', maxWidth: '500px' }}>
      {loading ? (
        // Skeleton loading state
        <div style={{ padding: '1.5rem', display: 'flex', gap: '1rem' }}>
          {/* Avatar skeleton */}
          <ModusWcSkeleton 
            shape="circle" 
            width="4rem" 
            height="4rem"
          />
          
          <div style={{ 
            display: 'flex', 
            flexDirection: 'column', 
            gap: '0.75rem',
            flex: 1
          }}>
            {/* Name skeleton */}
            <ModusWcSkeleton 
              width="60%" 
              height="1.5rem"
            />
            
            {/* Title skeleton */}
            <ModusWcSkeleton 
              width="40%" 
              height="1rem"
            />
            
            {/* Bio skeleton - multiple lines */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
              <ModusWcSkeleton height="0.875rem" />
              <ModusWcSkeleton height="0.875rem" />
              <ModusWcSkeleton width="75%" height="0.875rem" />
            </div>
          </div>
        </div>
      ) : error ? (
        // Error state
        <div style={{ padding: '1.5rem', color: 'var(--modus-wc-color-danger)' }}>
          {error}
        </div>
      ) : (        // Content state - actual profile data
        <div style={{ padding: '1.5rem', display: 'flex', gap: '1rem' }}>          
        <ModusWcAvatar
            size="lg"
            img-src={profile?.avatarUrl}
            alt={`${profile?.name}'s avatar`}
            shape="circle"
          />
          <div>
            <h3 style={{ margin: '0 0 0.25rem 0' }}>{profile?.name}</h3>
            <p style={{ 
              margin: '0 0 0.75rem 0', 
              color: 'var(--modus-wc-color-text-secondary)' 
            }}>
              {profile?.title}
            </p>
            <p style={{ margin: '0', lineHeight: '1.5' }}>
              {profile?.bio}
            </p>
          </div>
        </div>
      )}
    </ModusWcCard>
  );
};

// Example usage
const App: React.FC = () => {
  const [selectedUser, setSelectedUser] = useState<string>("user123");
  
  const userIds = ["user123", "user456", "user789"];
  
  return (
    <div style={{ padding: '2rem' }}>
      <h2>User Profile</h2>
      
      <div style={{ marginBottom: '1rem' }}>
        <label style={{ marginRight: '0.5rem' }}>Select User: </label>
        <select 
          value={selectedUser} 
          onChange={(e) => setSelectedUser(e.target.value)}
          style={{ padding: '0.5rem' }}
        >
          <option value="user123">Sarah Johnson</option>
          <option value="user456">Michael Smith</option>
          <option value="user789">Jessica Williams</option>
        </select>
      </div>
      
      <ProfileCard 
        userId={selectedUser} 
        onProfileLoad={(profile) => console.log('Profile loaded:', profile)}
      />
    </div>
  );
};

export default App;
```

**Implementation Decisions & Rationale:**

**Structure Mimicking**: Skeleton dimensions and shapes closely match final content to create seamless loading-to-content transitions.

**Composition Strategy**: Multiple skeleton elements compose complex layouts while maintaining realistic proportions and spacing.

**Performance Perception**: Visual structure display during loading reduces perceived wait time and maintains user engagement throughout data fetching.


---

# ModusWcSlider

## Prompt 1
**User Question:** I'm building a comprehensive configuration interface that requires various types of range selection controls - audio/video settings with precise increments, preference sliders with custom ranges, and dynamic configuration controls that respond to user context. The sliders need to provide immediate feedback, maintain accessibility, and integrate with complex form validation. How should I approach implementing a sophisticated slider control system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this complex range selection requirement, I considered:
1. **Precision Requirements**: Different settings require different levels of granularity and control precision
2. **User Feedback Patterns**: Real-time value display and validation provide essential user guidance
3. **Context Adaptation**: Slider behavior should adapt to the type of setting being controlled
4. **Accessibility Standards**: Range controls must be keyboard accessible and provide clear value communication

**Component Analysis:**
- **Range Definition**: `min`, `max`, and `step` properties enable precise control over value ranges and granularity
- **Controlled State**: `e.detail.target.value` property supports controlled component patterns with external state management
- **User Interaction**: Input change events provide real-time value updates for immediate feedback
- **Accessibility Integration**: Native slider semantics with optional labeling for screen reader support

**Why I chose these properties:**
- **`min` and `max` bounds**: Essential for context-appropriate ranges - 0-100 for percentages, custom ranges for specific settings
- **`step` precision**: Critical for user experience - fine increments (0.1) for precise controls, larger steps (5-10) for general preferences
- **`value` control**: Enables real-time validation and cross-component synchronization
- **`size` variants**: Adapts to interface hierarchy - 'sm' for compact settings, 'lg' for prominent controls
- **`label` property**: Provides clear context and accessibility support for screen readers
  
**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcSlider } from '@trimble-oss/moduswebcomponents-react';

const SimpleSliderExample: React.FC = () => {
  const [sliderValue, setSliderValue] = useState<number>(50);

  // Handle slider value change
  const handleSliderChange = (e: CustomEvent) => {
    const newValue = e.detail.target.value;
    setSliderValue(Number(newValue));
    console.log('Slider value changed to:', newValue);
  };

  return (
    <div style={{ 
      maxWidth: '600px', 
      margin: '0 auto', 
      padding: '2rem',
      display: 'flex',
      flexDirection: 'column',
      gap: '2rem'
    }}>
      <h1 style={{ 
        color: '#212529',
        fontSize: '2rem',
        marginBottom: '1rem'
      }}>
        🎚️ Simple Slider Example
      </h1>
      
      <div style={{
        background: '#ffffff',
        padding: '2rem',
        borderRadius: '8px',
        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
      }}>
        <h2 style={{ 
          margin: '0 0 1rem 0',
          color: '#495057'
        }}>
          Volume Control
        </h2>
        
        <ModusWcSlider
          label="Volume Level"
          min={0}
          max={100}
          step={1}
          value={sliderValue}
          size="lg"
          onInputChange={handleSliderChange}
        />
        
        <div style={{
          marginTop: '1.5rem',
          padding: '1rem',
          background: '#f8f9fa',
          borderRadius: '4px',
          textAlign: 'center'
        }}>
          <p style={{ margin: '0', fontSize: '1.2rem', fontWeight: 'bold' }}>
            Current Value: <span style={{ color: '#0063a3' }}>{sliderValue}%</span>
          </p>
        </div>
        
        <div style={{
          marginTop: '1rem',
          display: 'flex',
          justifyContent: 'space-between',
          fontSize: '0.9rem',
          color: '#6c757d'
        }}>
          <span>Min: 0%</span>
          <span>Max: 100%</span>
        </div>
      </div>
    </div>
  );
};

export default SimpleSliderExample;
```

---

# ModusWcStepper

## Prompt 1
**User Question:** I'm building a complex multi-stage workflow system that needs to handle various process types - linear sequential flows, branching conditional paths, and parallel task completion. Users need clear progress indication, the ability to navigate between completed steps, and visual differentiation between different process states. How should I approach implementing a comprehensive progress indication system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this complex workflow visualization requirement, I considered:
1. **Process State Communication**: Different workflow stages require distinct visual treatments to communicate progress and status
2. **User Navigation Patterns**: Users need to understand where they are, where they've been, and what comes next
3. **Semantic Color Coding**: Status colors should provide instant recognition of completion, current position, and upcoming steps
4. **Layout Flexibility**: Different workflows may need horizontal or vertical presentation based on interface constraints

**Component Analysis:**
I examined the ModusWcStepper component architecture and found it's designed for flexible progress visualization:
- **Step Configuration**: `steps` array allows dynamic step definition with individual properties for each stage
- **Visual Orientation**: `orientation` property handles both horizontal process flows and vertical task lists
- **Status Communication**: Individual step `color` properties provide semantic status indication
- **Content Flexibility**: Optional `content` property enables custom indicators beyond standard step markers

**Why I chose these properties:**
- **`steps` array**: Essential for dynamic workflow management - enables programmatic step generation and state updates
- **`color` semantics**: Critical for instant status recognition - 'success' for completed, 'primary' for active, 'neutral' for pending, 'error' for failed steps
- **`orientation` control**: Adapts to interface layout constraints - 'horizontal' for process flows, 'vertical' for detailed checklists
- **`label` properties**: Provide clear textual context for each step, essential for both visual users and screen readers
- **`content` customization**: Allows step numbering, icons, or progress indicators for enhanced user understanding

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcStepper, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface StepperItem {
  color?: 'primary' | 'secondary' | 'accent' | 'info' | 'success' | 'warning' | 'error' | 'neutral';
  content?: string;
  label?: string;
}

const SimpleStepperExample: React.FC = () => {
  const [currentStep, setCurrentStep] = useState<number>(0);
  const [completedSteps, setCompletedSteps] = useState<number[]>([]);
  const [failedSteps, setFailedSteps] = useState<number[]>([]);

  // Simple workflow steps
  const baseSteps = [
    { label: 'Start', content: '1' },
    { label: 'Process', content: '2' },
    { label: 'Review', content: '3' },
    { label: 'Approve', content: '4' },
    { label: 'Complete', content: '✓' }
  ];

  // Generate stepper items with current state
  const getStepperItems = (): StepperItem[] => {
    return baseSteps.map((step, index) => {
      let color: StepperItem['color'] = 'neutral';
      let content = step.content;

      if (failedSteps.includes(index)) {
        color = 'error';
        content = '✗';
      } else if (completedSteps.includes(index)) {
        color = 'success';
        content = '✓';
      } else if (index === currentStep) {
        color = 'primary';
        content = step.content;
      }

      return {
        label: step.label,
        color,
        content
      };
    });
  };

  // Complete current step and move to next
  const handleNextStep = () => {
    if (currentStep < baseSteps.length - 1) {
      setCompletedSteps(prev => [...prev, currentStep]);
      setCurrentStep(prev => prev + 1);
    }
  };

  // Fail current step
  const handleFailStep = () => {
    setFailedSteps(prev => [...prev, currentStep]);
  };

  // Reset to beginning
  const handleReset = () => {
    setCurrentStep(0);
    setCompletedSteps([]);
    setFailedSteps([]);
  };

  const stepperItems = getStepperItems();

  return (
    <div style={{ padding: '32px', maxWidth: '800px', margin: '0 auto' }}>
      <h1>Simple Stepper Example</h1>
      
      <div style={{ marginBottom: '32px' }}>
        <ModusWcStepper
          orientation="horizontal"
          steps={stepperItems}
        />
      </div>

      <div style={{ display: 'flex', gap: '16px', justifyContent: 'center' }}>
        <ModusWcButton
          color="primary"
          disabled={currentStep >= baseSteps.length - 1}
          onClick={handleNextStep}
        >
          {currentStep === baseSteps.length - 1 ? 'Completed' : 'Next Step'}
        </ModusWcButton>
        
        <ModusWcButton
          color="danger"
          variant="outlined"
          disabled={failedSteps.includes(currentStep)}
          onClick={handleFailStep}
        >
          Fail Step
        </ModusWcButton>
        
        <ModusWcButton
          color="secondary"
          variant="outlined"
          onClick={handleReset}
        >
          Reset
        </ModusWcButton>
      </div>
    </div>
  );
};

export default SimpleStepperExample;
```
---

# ModusWcSwitch

## Prompt 1
**User Question:** I need to implement binary setting controls that provide immediate visual feedback and handle on/off states for features like themes, notifications, and user preferences. The controls should integrate with application state and provide clear user experience patterns. How can I build effective toggle switch systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing toggle requirements: immediate state feedback, binary choice visualization, application state integration, user preference persistence, and clear on/off indication patterns.

**Component Analysis:**
ModusWcSwitch provides immediate binary state control through `value` boolean, visual feedback through switch animation, and comprehensive interaction handling via change/focus/blur events.

**Why I chose these properties:**
- **`value` boolean**: Direct state representation with visual switch animation feedback
- **`label` property**: Provides clear context for switch purpose and accessibility compliance
- **`inputChange` event**: Enables immediate state updates and application integration
- **`disabled` state**: Supports conditional feature availability and user permission patterns
- **Size options**: Contextual scaling for different UI density requirements

**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcSwitch } from '@trimble-oss/moduswebcomponents-react';

const ThemeToggle: React.FC = () => {
  // Initialize state based on user preference
  const [isDarkMode, setIsDarkMode] = useState(() => {
    return window.matchMedia('(prefers-color-scheme: dark)').matches;
  });
  
  const switchRef = useRef<HTMLModusWcSwitchElement>(null);
  
  // Apply theme whenever it changes
  useEffect(() => {
    document.body.classList.toggle('dark-theme', isDarkMode);
    
    // Optional: Store preference
    localStorage.setItem('theme', isDarkMode ? 'dark' : 'light');
  }, [isDarkMode]);
  
  useEffect(() => {
    const element = switchRef.current;
    if (element) {
      const handleChange = (e: CustomEvent) => {
        setIsDarkMode(e.detail.target.value);
      };
      
      element.addEventListener('inputChange', handleChange as EventListener);
      
      return () => {
        element.removeEventListener('inputChange', handleChange as EventListener);
      };
    }
  }, []);
  
  return (
    <div className="theme-toggle-container">
      <ModusWcSwitch 
        ref={switchRef}
        label="Dark Mode"
        value={isDarkMode}
        size="md"
      />
    </div>
  );
};

export default ThemeToggle;
```

**Implementation Decisions & Rationale:**

**State Management**: Boolean `value` provides clear on/off state with immediate visual feedback through switch animation.

**Event Handling**: `inputChange` enables reactive state updates and application preference persistence.

**Accessibility**: `label` property ensures screen reader compatibility and provides clear context for switch purpose.


---

# ModusWcTable

## Prompt 1
**User Question:** I need to implement data tables that handle large datasets efficiently with user-friendly navigation, sorting capabilities, and customizable display options. The tables should provide clear data presentation while supporting interactive features like filtering and row selection. How can I build comprehensive data table systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing data table requirements: large dataset handling, user navigation efficiency, sorting interactions, display customization, and data presentation clarity across different data types.

**Component Analysis:**
ModusWcTable provides comprehensive data handling through `columns/data` configuration, user control via `sortable/paginated` features, and visual customization through `density/hover/zebra` properties.

**Why I chose these properties:**
- **`columns` array**: Structured column definitions enable flexible data presentation and custom rendering
- **`sortable/paginated`**: Essential for large dataset usability and performance
- **`density` options**: Contextual display optimization for different screen sizes and data complexity
- **Event handling**: `sortChange/paginationChange` enable server-side data management and state synchronization
- **`rowClick` events**: Support selection patterns and detail navigation workflows

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcTable } from '@trimble-oss/moduswebcomponents-react';

interface User {
  id: string;
  name: string;
  email: string;
  role: string;
}

interface ColumnSort {
  id: string;
  desc: boolean;
}

interface PaginationState {
  currentPage: number;
  pageSize: number;
  totalItems: number;
}

// Hardcoded demo data
const createDemoData = (count = 20): User[] => {
  const data: User[] = [];
  for (let i = 1; i <= count; i++) {
    data.push({
      id: i.toString(),
      name: `User ${i}`,
      email: `user${i}@example.com`,
      role: i % 3 === 0 ? 'Admin' : 'User',
    });
  }
  return data;
};

// Create a larger set of users for our demo
const DEMO_USERS = createDemoData(50);

const UserTable: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState<PaginationState>({
    currentPage: 1,
    pageSize: 10,
    totalItems: DEMO_USERS.length
  });
  
  const tableRef = useRef<HTMLModusWcTableElement>(null);
  
  // Column definitions
  const columns = [
    {
      id: 'id',
      header: 'ID',
      accessor: 'id',
      width: '80px',
      sortable: true
    },
    {
      id: 'name',
      header: 'Full Name',
      accessor: 'name',
      sortable: true
    },
    {
      id: 'email',
      header: 'Email Address',
      accessor: 'email',
      sortable: true
    },
    {
      id: 'role',
      header: 'Role',
      accessor: 'role',
      sortable: false,
      cellRenderer: (value: unknown) => {
        const span = document.createElement('span');
        span.textContent = value as string;
        
        // Apply styling based on role
        if (value === 'Admin') {
          span.style.fontWeight = 'bold';
          span.style.color = '#0063a3';
        }
        
        return span;
      }
    }
  ];
  
  // Fetch users on component mount
  useEffect(() => {
    fetchUsers();
  }, []);
  
  // Set up event listeners
  useEffect(() => {
    const element = tableRef.current;
    if (element) {
      const handleSortChange = (e: CustomEvent<ColumnSort[]>) => {
        const sortConfig = e.detail[0];
        if (sortConfig) {
          fetchUsers(sortConfig.id, sortConfig.desc ? 'desc' : 'asc');
        }
      };
      
      const handlePaginationChange = (e: CustomEvent) => {
        const { currentPage, pageSize } = e.detail;
        setPagination(prev => ({ ...prev, currentPage, pageSize }));
        fetchUsers(undefined, undefined, currentPage, pageSize);
      };
      
      element.addEventListener('sortChange', handleSortChange as EventListener);
      element.addEventListener('paginationChange', handlePaginationChange as EventListener);
      
      return () => {
        element.removeEventListener('sortChange', handleSortChange as EventListener);
        element.removeEventListener('paginationChange', handlePaginationChange as EventListener);
      };
    }
  }, []);
  
  // Mock data handling - simulates API functionality
  const fetchUsers = (
    sortBy: string = 'id',
    sortOrder: string = 'asc',
    page: number = pagination.currentPage,
    pageSize: number = pagination.pageSize
  ) => {
    setLoading(true);
    
    // Simulate API delay
    setTimeout(() => {
      try {
        // Sort the data
        const sortedData = [...DEMO_USERS].sort((a, b) => {
          const aValue = a[sortBy as keyof User];
          const bValue = b[sortBy as keyof User];
          
          if (sortOrder === 'asc') {
            return aValue > bValue ? 1 : aValue < bValue ? -1 : 0;
          } else {
            return aValue < bValue ? 1 : aValue > bValue ? -1 : 0;
          }
        });
        
        // Calculate pagination
        const startIndex = (page - 1) * pageSize;
        const paginatedData = sortedData.slice(startIndex, startIndex + pageSize);
        
        setUsers(paginatedData);
        setPagination({
          currentPage: page,
          pageSize: pageSize,
          totalItems: DEMO_USERS.length
        });
      } catch (error) {
        console.error('Error processing users:', error);
      } finally {
        setLoading(false);
      }
    }, 300); // Simulate network delay
  };
  
  return (
    <div className="user-table-container">
      <h2>User Management</h2>
      
      {loading ? (
        <div className="loading-indicator">Loading...</div>
      ) : (
        <ModusWcTable
          ref={tableRef}
          columns={columns}
          data={users}
          sortable={true}
          paginated={true}
          currentPage={pagination.currentPage}
          pageSizeOptions={[5, 10, 20, 50]}
          showPageSizeSelector={true}
          density="comfortable"
          hover={true}
          totalItems={pagination.totalItems}
        />
      )}
    </div>
  );
};

export default UserTable;
```

**Notes:**
- The `columns` array defines the structure of the table with each column having an `id`, `header`, and `accessor` property
- Use the `sortable` property to enable column sorting (both at table and column level)
- For custom cell rendering, use the `cellRenderer` function
- For server-side sorting and pagination, handle the events and make API calls with the appropriate parameters
- The pagination UI is automatically generated when `paginated` is true


## Prompt 2

**User Question:** I need to create an interactive data table where users can view structured information and seamlessly toggle into edit mode to modify records directly within the table cells. The solution should provide real-time editing capabilities with immediate state updates, while maintaining data integrity and user experience consistency. How can I implement an editable table system with inline editing functionality?

**Agent Answer:**
**My Reasoning Process:**

Analyzing editable table requirements: seamless view/edit mode transitions, inline editing capabilities, real-time state synchronization, data integrity preservation, and intuitive user interaction patterns for direct table manipulation.

**Component Analysis:**
ModusWcTable provides flexible content rendering through `cellRenderer` functions, enabling custom HTML element injection while maintaining structured column definitions. The component supports dynamic data updates and proper event propagation for complex interaction patterns.

**Why I chose these properties:**
- **`cellRenderer` functions**: Enable dynamic cell content switching between display and input modes
- **`columns` array with custom renderers**: Provides structured column definitions while allowing per-cell customization
- **`data` array with React state**: Ensures real-time updates and proper re-rendering on data changes  
- **Event handling with `addEventListener`**: Proper event management for custom DOM elements within table cells
- **`useRef` with table reference**: Direct DOM access for event listener management and cleanup

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcTable, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface Person extends Record<string, unknown> {
  id: string;
  name: string;
  email: string;
  role: string;
}

const ModusSandbox: React.FC = () => {
  const [people, setPeople] = useState<Person[]>([
    { id: '1', name: 'John Doe', email: 'john@example.com', role: 'Developer' },
    { id: '2', name: 'Jane Smith', email: 'jane@example.com', role: 'Designer' },
    { id: '3', name: 'Bob Johnson', email: 'bob@example.com', role: 'Manager' }
  ]);

  const [isEditing, setIsEditing] = useState(false);
  const tableRef = useRef<HTMLModusWcTableElement>(null);

  const createInput = (value: unknown, rowId: string, field: string): HTMLElement => {
    const input = document.createElement('modus-wc-text-input') as any;
    input.value = value?.toString() || '';
    input.size = 'medium';
    
    const handleChange = (e: Event) => {
      const customEvent = e as CustomEvent;
      const newValue = customEvent.detail.target.value;
      
      setPeople(prev => 
        prev.map(person => 
          person.id === rowId ? { ...person, [field]: newValue } : person
        )
      );
    };
    
    input.addEventListener('inputChange', handleChange as EventListener);
    return input;
  };

  const columns = [
    {
      id: 'name',
      header: 'Name',
      accessor: 'name',
      sortable: true,
      cellRenderer: (value: unknown, row: unknown) => {
        const rowData = row as Record<string, unknown>;
        return isEditing ? createInput(value, rowData.id as string, 'name') : value as string;
      }
    },
    {
      id: 'email',
      header: 'Email',
      accessor: 'email',
      sortable: true,
      cellRenderer: (value: unknown, row: unknown) => {
        const rowData = row as Record<string, unknown>;
        return isEditing ? createInput(value, rowData.id as string, 'email') : value as string;
      }
    },
    {
      id: 'role',
      header: 'Role',
      accessor: 'role',
      sortable: true,
      cellRenderer: (value: unknown, row: unknown) => {
        const rowData = row as Record<string, unknown>;
        return isEditing ? createInput(value, rowData.id as string, 'role') : value as string;
      }
    }
  ];

  useEffect(() => {
    const element = tableRef.current;
    if (element) {
      const handleRowClick = (e: CustomEvent) => {
        console.log('Row clicked:', e.detail);
      };
      
      element.addEventListener('rowClick', handleRowClick as EventListener);
      
      return () => {
        element.removeEventListener('rowClick', handleRowClick as EventListener);
      };
    }
  }, []);

  return (
    <div style={{ padding: '20px', fontFamily: 'Open Sans, sans-serif' }}>
      <h2>Simple Editable Table</h2>
      
      <div style={{ marginBottom: '16px' }}>
        <ModusWcButton 
          variant={isEditing ? 'filled' : 'outlined'}
          color="primary"
          onClick={() => setIsEditing(!isEditing)}
        >
          {isEditing ? 'Done Editing' : 'Edit Table'}
        </ModusWcButton>
      </div>

      <ModusWcTable
        ref={tableRef}
        columns={columns}
        data={people}
        sortable={true}
        paginated={false}
        hover={true}
        density="comfortable"
      />
    </div>
  );
};

export default ModusSandbox;
```

**Implementation Decisions & Rationale:**

**Dynamic Cell Rendering**: The `cellRenderer` approach enables conditional content generation, switching between display text and `ModusWcTextInput` components based on edit state, providing seamless mode transitions.

**Custom Input Creation**: Using `document.createElement` for `modus-wc-text-input` enables proper Modus component integration within table cells while maintaining event handling capabilities.

**State Management Pattern**: React state updates through the `setPeople` function with immutable array operations ensure proper re-rendering and data consistency across edit operations.

**Event Handling Strategy**: Direct `addEventListener` on dynamically created inputs provides reliable event capture for custom DOM elements within the React component lifecycle.

**Important Notes:**
- **Memory Management**: Event listeners on dynamically created inputs should be cleaned up when components unmount or mode changes to prevent memory leaks
- **Type Safety**: The `Record<string, unknown>` interface extension enables flexible data structure while maintaining TypeScript compatibility
- **Performance Consideration**: Re-creating input elements on each render can impact performance with large datasets - consider memoization for production use
- **Accessibility**: Custom rendered cells should maintain proper ARIA labels and keyboard navigation support
- **Validation Integration**: Additional validation logic should be implemented within the `handleChange` function for data integrity

---

# ModusWcTabs

## Prompt 1

**User Question:** I need to organize complex application content into manageable sections that users can navigate between without losing context. The interface should support visual hierarchy, workflow progression, and efficient content switching with proper event handling. How can I implement an effective tabbed navigation system using the tabs attribute configuration?

**Agent Answer:**
**My Reasoning Process:**

Analyzing tabbed interface needs: content organization, navigation efficiency, visual hierarchy, state preservation, and workflow support across different content types with centralized tab configuration management.

**Component Analysis:**
ModusWcTabs uses array-based configuration through `tabs` property, controlled navigation via `activeTabIndex`, and comprehensive event handling through `tabChange` events for seamless state management and user interaction tracking.

**Why I chose these properties:**
- **`tabs` array configuration**: Centralized tab definition enables dynamic generation, easy maintenance, and consistent icon/label management
- **`activeTabIndex` control**: Provides programmatic navigation and React state synchronization for controlled component behavior
- **`tabStyle` options**: Visual hierarchy through 'bordered', 'boxed', 'lifted' styles for different contexts and design requirements
- **`tabChange` event**: Comprehensive event data including previous and new tab indices for workflow tracking and conditional logic
- **`useRef` with event listeners**: Proper DOM event management with cleanup for React lifecycle integration

**TypeScript Example:**
```tsx
import React, { useRef, useEffect, useState } from 'react';
import { ModusWcTabs } from '@trimble-oss/moduswebcomponents-react';

interface ITab {
  label?: string;
  icon?: string;
  iconPosition?: 'left' | 'right';
  disabled?: boolean;
  customClass?: string;
}

const SettingsTabs: React.FC = () => {
  const [activeTab, setActiveTab] = useState<number>(0);
  const tabsRef = useRef<HTMLModusWcTabsElement>(null);
  
  // Define tabs
  const tabs: ITab[] = [
    { label: 'Account', icon: 'person', iconPosition: 'left' },
    { label: 'Notifications', icon: 'bell', iconPosition: 'left' },
    { label: 'Privacy', icon: 'shield', iconPosition: 'left' }
  ];
  
  // Set up event listeners
  useEffect(() => {
    const element = tabsRef.current;
    
    if (element) {
      const handleTabChange = (e: CustomEvent<{ previousTab: number; newTab: number }>) => {
        setActiveTab(e.detail.newTab);
        
        // You might want to perform additional actions when tab changes
        console.log(`Tab changed from ${e.detail.previousTab} to ${e.detail.newTab}`);
      };
      
      element.addEventListener('tabChange', handleTabChange as EventListener);
      
      return () => {
        element.removeEventListener('tabChange', handleTabChange as EventListener);
      };
    }
  }, []);
  
  return (
    <div className="settings-container">
      <h2>User Settings</h2>
      
      <ModusWcTabs
        ref={tabsRef}
        tabs={tabs}
        activeTabIndex={activeTab}
        tabStyle="bordered"
        size="md"
      >
       
      </ModusWcTabs>
    </div>
  );
};

export default SettingsTabs;
```

**Implementation Decisions & Rationale:**

**Tabs Attribute Configuration**: The `tabs` array provides centralized configuration where each tab object can define `label`, `icon`, `iconPosition`, `disabled` state, and `customClass` for flexible styling and behavior control.

**Event Handling Strategy**: The `tabChange` event provides comprehensive data including both `previousTab` and `newTab` indices, enabling complex workflow logic, analytics tracking, and conditional content loading based on navigation patterns.

**State Synchronization Pattern**: Controlled `activeTabIndex` with React state ensures UI consistency and enables programmatic navigation, making the component fully controllable from parent components or external state management systems.

**Icon Integration**: Using `icon` property with `iconPosition` provides visual hierarchy and improved user experience, supporting Modus icon library integration for consistent design language.

**Important Notes:**
- **CSS Conflicts**: Sometimes the existing CSS from `app.css` and `index.css` might affect the component's appearance. If the UI doesn't look as expected, check these global stylesheets first for conflicting styles that might override Modus component styling
- **Event Cleanup**: The `useEffect` cleanup function properly removes event listeners to prevent memory leaks and duplicate event handling
- **Tab Content**: This example shows tab navigation setup - actual tab panel content should be added using slot-based architecture (`slot="tab-0"`, `slot="tab-1"`, etc.) for complete implementation
- **Dynamic Tab Management**: The `tabs` array can be dynamically updated to add/remove tabs, with the component automatically handling the UI updates
- **Accessibility**: The component inherits Modus accessibility features including keyboard navigation and ARIA attributes for screen reader compatibility
- **Performance**: Event listeners are only attached when the component ref is available, preventing unnecessary re-attachments on re-renders

---

# ModusWcTextInput

## Prompt 1
**User Question:** I need to build comprehensive form interfaces that collect user data with real-time validation, clear feedback, and accessibility compliance. The forms should handle various input types, provide immediate user guidance, and integrate with submission workflows. How can I implement robust text input systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing form input requirements: real-time validation, user feedback clarity, accessibility compliance, data integrity, and seamless submission workflows across different input scenarios.

**Component Analysis:**
ModusWcTextInput provides controlled input management through `value` property, comprehensive validation via `pattern/minLength/maxLength`, and user feedback through `feedback` object with multiple severity levels.

**Why I chose these properties:**
- **`value` controlled pattern**: Ensures predictable state management and validation integration
- **`feedback` object**: Provides structured user guidance with visual hierarchy (error/warning/success/info)
- **`pattern/minLength/maxLength`**: Enables client-side validation with clear constraints
- **Event handling**: `inputChange/Blur/Focus` enables real-time validation and user experience optimization
- **`type` property**: Semantic input types improve mobile experience and accessibility

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcTextInput, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface IFeedback {
  level: 'error' | 'info' | 'success' | 'warning';
  message: string;
}

interface FormData {
  name: string;
  email: string;
  password: string;
}

const RegistrationForm: React.FC = () => {
  // Form state
  const [formData, setFormData] = useState<FormData>({
    name: '',
    email: '',
    password: ''
  });
  
  // Feedback state
  const [nameFeedback, setNameFeedback] = useState<IFeedback | undefined>();
  const [emailFeedback, setEmailFeedback] = useState<IFeedback | undefined>();
  const [passwordFeedback, setPasswordFeedback] = useState<IFeedback | undefined>();
  
  // Input refs
  const nameInputRef = useRef<HTMLModusWcTextInputElement>(null);
  const emailInputRef = useRef<HTMLModusWcTextInputElement>(null);
  const passwordInputRef = useRef<HTMLModusWcTextInputElement>(null);
  
  // Set up event handlers
  useEffect(() => {
    const setupInputListeners = (
      ref: React.RefObject<HTMLModusWcTextInputElement | null>,
      fieldName: keyof FormData,
      validate: () => void
    ) => {
      const element = ref.current;
      if (element) {
        const handleChange = (e: CustomEvent) => {
          setFormData(prev => ({
            ...prev,
            [fieldName]: e.detail.target.value
          }));
        };
        
        const handleBlur = () => {
          validate();
        };
        
        element.addEventListener('inputChange', handleChange as EventListener);
        element.addEventListener('inputBlur', handleBlur as EventListener);
        
        return () => {
          element.removeEventListener('inputChange', handleChange as EventListener);
          element.removeEventListener('inputBlur', handleBlur as EventListener);
        };
      }
      return undefined;
    };
    
    const cleanupFuncs = [
      setupInputListeners(nameInputRef, 'name', validateName),
      setupInputListeners(emailInputRef, 'email', validateEmail),
      setupInputListeners(passwordInputRef, 'password', validatePassword)
    ];
    
    return () => {
      cleanupFuncs.forEach(cleanup => cleanup && cleanup());
    };
  }, [formData]);
  
  // Validation functions
  const validateName = (): boolean => {
    if (!formData.name) {
      setNameFeedback({
        level: 'error',
        message: 'Name is required'
      });
      return false;
    } else if (!/^[a-zA-Z ]+$/.test(formData.name)) {
      setNameFeedback({
        level: 'error',
        message: 'Name should contain only letters and spaces'
      });
      return false;
    } else {
      setNameFeedback(undefined);
      return true;
    }
  };
  
  const validateEmail = (): boolean => {
    if (!formData.email) {
      setEmailFeedback({
        level: 'error',
        message: 'Email is required'
      });
      return false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      setEmailFeedback({
        level: 'error',
        message: 'Please enter a valid email address'
      });
      return false;
    } else {
      setEmailFeedback(undefined);
      return true;
    }
  };
  
  const validatePassword = (): boolean => {
    if (!formData.password) {
      setPasswordFeedback({
        level: 'error',
        message: 'Password is required'
      });
      return false;
    } else if (formData.password.length < 8) {
      setPasswordFeedback({
        level: 'error',
        message: 'Password must be at least 8 characters'
      });
      return false;
    } else {
      setPasswordFeedback({
        level: 'success',
        message: 'Password strength: Good'
      });
      return true;
    }
  };
  
  // Form submission handler
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const nameValid = validateName();
    const emailValid = validateEmail();
    const passwordValid = validatePassword();
    
    if (nameValid && emailValid && passwordValid) {
      // Submit the form data
      console.log('Form submitted with:', formData);
      
      // In a real application, you would make an API call here
      submitRegistration(formData);
    }
  };
  
  // Mock API call
  const submitRegistration = async (data: FormData) => {
    try {
      // Replace with actual API endpoint
      await fetch('/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });
      
      // Handle successful registration
      console.log('Registration successful!');
    } catch (error) {
      console.error('Registration failed:', error);
    }
  };
  
  return (
    <form onSubmit={handleSubmit} className="registration-form">
      <h2>Create an Account</h2>
      
      <div className="form-field">
        <ModusWcTextInput
          ref={nameInputRef}
          label="Full Name"
          required={true}
          pattern="^[a-zA-Z ]+$"
          placeholder="Enter your full name"
          value={formData.name}
          feedback={nameFeedback}
        />
      </div>
      
      <div className="form-field">
        <ModusWcTextInput
          ref={emailInputRef}
          label="Email Address"
          type="email"
          required={true}
          placeholder="Enter your email"
          value={formData.email}
          feedback={emailFeedback}
        />
      </div>
      
      <div className="form-field">
        <ModusWcTextInput
          ref={passwordInputRef}
          label="Password"
          type="password"
          minLength={8}
          required={true}
          placeholder="Create a password"
          value={formData.password}
          feedback={passwordFeedback}
        />
      </div>
      
      <div className="form-actions">
        <ModusWcButton 
          type="submit" 
          variant="filled"
          color="primary"
          size="md"
        >
          Register
        </ModusWcButton>
      </div>
    </form>
  );
};

export default RegistrationForm;
```

**Notes:**
- Always use the appropriate input type ("email", "password", etc.) for better user experience and built-in validation
- The `feedback` property accepts an object with `level` and `message` to show validation state
- Validation can be performed both on blur and on input change, depending on the UX requirements
- In React applications, maintain a state for form data and feedback messages
- Use refs to access the web component's DOM methods and event listeners
- Don't forget to clean up event listeners in your React components to avoid memory leaks
- The input follows the controlled component pattern in React, where value is managed in state


---

# ModusWcTextarea

## Prompt 1
**User Question:** I'm building a comprehensive content management system that requires various types of multiline text input - from brief feedback forms to detailed documentation editing, code snippet input, and collaborative commenting systems. Each context needs different validation rules, character limits, and user experience patterns. How should I approach implementing a flexible textarea system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive text input requirement, I considered:
1. **Context Variability**: Different use cases require different sizing, validation, and interaction patterns
2. **User Guidance**: Complex forms need clear feedback and validation to prevent user frustration
3. **Content Length Management**: Various content types have different optimal length ranges and constraints
4. **Accessibility Standards**: Multiline inputs require proper labeling and error messaging for screen readers

**Component Analysis:**
I examined the ModusWcTextarea component architecture and found it's designed for flexible multiline input:
- **Validation Integration**: `feedback` object provides structured validation messaging with semantic levels
- **Size Flexibility**: `rows` and `size` properties control visual space allocation based on expected content length
- **Input Constraints**: `max-length` and `required` properties enable content governance and form validation
- **State Management**: `value` property with change events supports controlled component patterns

**Why I chose these properties:**
- **`feedback` object**: Essential for user guidance - provides structured validation with semantic levels (error, success, warning, info)
- **`rows` property**: Critical for UX - sets appropriate visual space expectations (3-4 for comments, 8+ for documentation)
- **`max-length` constraint**: Prevents content overflow and provides clear user expectations
- **`size` variants**: Adapts input field to interface density - 'sm' for compact interfaces, 'lg' for prominent editing
- **`bordered` and styling**: Ensures visual clarity in different layout contexts
- **Event handling**: `inputChange`, `inputBlur`, `inputFocus` enable real-time validation and user experience optimization

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { 
  ModusWcTextarea, 
  ModusWcButton, 
  ModusWcTypography, 
  ModusWcDivider,
  ModusWcCard 
} from '@trimble-oss/moduswebcomponents-react';

interface TextareaConfig {
  rows: number;
  maxLength: number;
  placeholder: string;
  validationRules: {
    minLength: number;
    required: boolean;
    pattern?: RegExp;
  };
}

const ContentManagementSystem: React.FC = () => {
  // Different textarea configurations for different contexts
  const [feedbackText, setFeedbackText] = useState('');
  const [documentationText, setDocumentationText] = useState('');
  const [codeSnippet, setCodeSnippet] = useState('');
  const [commentText, setCommentText] = useState('');
  
  // Validation states for each textarea
  const [feedbackValidation, setFeedbackValidation] = useState<{
    level: 'error' | 'success' | 'warning' | 'info' | null;
    message?: string;
  }>({ level: null });
  
  const [documentationValidation, setDocumentationValidation] = useState<{
    level: 'error' | 'success' | 'warning' | 'info' | null;
    message?: string;
  }>({ level: null });
  
  // Configuration for different textarea types
  const textareaConfigs: { [key: string]: TextareaConfig } = {
    feedback: {
      rows: 4,
      maxLength: 300,
      placeholder: 'Please provide your feedback in 10-300 characters...',
      validationRules: { minLength: 10, required: true }
    },
    documentation: {
      rows: 12,
      maxLength: 2000,
      placeholder: 'Write detailed documentation with examples and explanations...',
      validationRules: { minLength: 50, required: true }
    },
    code: {
      rows: 8,
      maxLength: 1000,
      placeholder: 'Paste your code snippet here...',
      validationRules: { minLength: 5, required: false }
    },
    comment: {
      rows: 3,
      maxLength: 500,
      placeholder: 'Add your comment...',
      validationRules: { minLength: 1, required: false }
    }
  };
  
  // Generic validation function
  const validateTextarea = (
    value: string, 
    config: TextareaConfig,
    setValidation: React.Dispatch<React.SetStateAction<{
      level: 'error' | 'success' | 'warning' | 'info' | null;
      message?: string;
    }>>
  ) => {
    const { validationRules } = config;
    const trimmedValue = value.trim();
    
    if (validationRules.required && trimmedValue.length === 0) {
      setValidation({
        level: 'error',
        message: 'This field is required'
      });
      return;
    }
    
    if (trimmedValue.length > 0 && trimmedValue.length < validationRules.minLength) {
      setValidation({
        level: 'error',
        message: `Please provide at least ${validationRules.minLength} characters`
      });
      return;
    }
    
    if (trimmedValue.length > config.maxLength * 0.9) {
      setValidation({
        level: 'warning',
        message: `Approaching character limit (${trimmedValue.length}/${config.maxLength})`
      });
      return;
    }
    
    if (trimmedValue.length >= validationRules.minLength) {
      setValidation({
        level: 'success',
        message: 'Input looks good'
      });
      return;
    }
    
    setValidation({ level: null });
  };
  
  const handleFeedbackChange = (e: CustomEvent) => {
    const newValue = e.detail.target.value;
    setFeedbackText(newValue);
    validateTextarea(newValue, textareaConfigs.feedback, setFeedbackValidation);
  };
  
  const handleDocumentationChange = (e: CustomEvent) => {
    const newValue = e.detail.target.value;
    setDocumentationText(newValue);
    validateTextarea(newValue, textareaConfigs.documentation, setDocumentationValidation);
  };
  
  const handleSubmit = (type: string) => {
    console.log(`Submitting ${type}:`, {
      feedback: feedbackText,
      documentation: documentationText,
      code: codeSnippet,
      comment: commentText
    });
  };
  
  return (
    <div className="cms-interface" style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
      <ModusWcTypography variant="h1" size="lg" color="primary">
        Content Management System
      </ModusWcTypography>
      <ModusWcDivider style={{ margin: '20px 0' }} />
      
      {/* Feedback Form - Compact */}
      <ModusWcCard style={{ marginBottom: '32px', padding: '20px' }}>
        <ModusWcTypography variant="h2" size="md" style={{ marginBottom: '16px' }}>
          Quick Feedback
        </ModusWcTypography>
        <ModusWcTextarea
          label="Your Feedback"
          placeholder={textareaConfigs.feedback.placeholder}
          value={feedbackText}
          rows={textareaConfigs.feedback.rows}
          max-length={textareaConfigs.feedback.maxLength}
          size="sm"
          bordered={true}
          required={textareaConfigs.feedback.validationRules.required}
          {...(feedbackValidation.level !== null && {
            feedback: {
              level: feedbackValidation.level,
              message: feedbackValidation.message
            }
          })}
          onInputChange={handleFeedbackChange}
          aria-label="Feedback input"
        />
        <ModusWcButton 
          variant="filled"
          color="primary"
          size="md"
          disabled={feedbackValidation.level === 'error'}
          onClick={() => handleSubmit('feedback')}
          style={{ marginTop: '16px' }}
        >
          Submit Feedback
        </ModusWcButton>
      </ModusWcCard>
      
      {/* Documentation Editor - Large */}
      <ModusWcCard style={{ marginBottom: '32px', padding: '20px' }}>
        <ModusWcTypography variant="h2" size="md" style={{ marginBottom: '16px' }}>
          Documentation Editor
        </ModusWcTypography>
        <ModusWcTextarea
          label="Documentation Content"
          placeholder={textareaConfigs.documentation.placeholder}
          value={documentationText}
          rows={textareaConfigs.documentation.rows}
          max-length={textareaConfigs.documentation.maxLength}
          size="lg"
          bordered={true}
          required={textareaConfigs.documentation.validationRules.required}
          {...(documentationValidation.level !== null && {
            feedback: {
              level: documentationValidation.level,
              message: documentationValidation.message
            }
          })}
          onInputChange={handleDocumentationChange}
          aria-label="Documentation content editor"
        />
        <ModusWcButton 
          variant="filled"
          color="secondary"
          size="md"
          disabled={documentationValidation.level === 'error'}
          onClick={() => handleSubmit('documentation')}
          style={{ marginTop: '16px' }}
        >
          Save Documentation
        </ModusWcButton>
      </ModusWcCard>
      
      {/* Code Snippet Input - Monospace styling context */}
      <ModusWcCard style={{ marginBottom: '32px', padding: '20px' }}>
        <ModusWcTypography variant="h2" size="md" style={{ marginBottom: '16px' }}>
          Code Snippet
        </ModusWcTypography>
        <ModusWcTextarea
          label="Code Input"
          placeholder={textareaConfigs.code.placeholder}
          value={codeSnippet}
          rows={textareaConfigs.code.rows}
          max-length={textareaConfigs.code.maxLength}
          size="md"
          bordered={true}
          onInputChange={(e: CustomEvent) => setCodeSnippet(e.detail.target.value)}
          aria-label="Code snippet input"
          style={{ fontFamily: 'monospace' }}
        />
        <ModusWcButton 
          variant="outlined"
          color="tertiary"
          size="md"
          onClick={() => handleSubmit('code')}
          style={{ marginTop: '16px' }}
        >
          Save Code Snippet
        </ModusWcButton>
      </ModusWcCard>
      
      {/* Comment System - Minimal */}
      <ModusWcCard style={{ padding: '20px' }}>
        <ModusWcTypography variant="h2" size="md" style={{ marginBottom: '16px' }}>
          Comments
        </ModusWcTypography>
        <ModusWcTextarea
          label="Add Comment"
          placeholder={textareaConfigs.comment.placeholder}
          value={commentText}
          rows={textareaConfigs.comment.rows}
          max-length={textareaConfigs.comment.maxLength}
          size="sm"
          bordered={true}
          onInputChange={(e: CustomEvent) => setCommentText(e.detail.target.value)}
          aria-label="Comment input"
        />
        <ModusWcButton 
          variant="borderless"
          color="primary"
          size="sm"
          disabled={commentText.trim().length === 0}
          onClick={() => handleSubmit('comment')}
          style={{ marginTop: '16px' }}
        >
          Post Comment
        </ModusWcButton>
      </ModusWcCard>
    </div>
  );
};

export default ContentManagementSystem;
```

**Implementation Decisions & Rationale:**

**Context-Aware Sizing:**
- **Feedback forms**: Small size with 4 rows for quick, focused input
- **Documentation**: Large size with 12 rows to encourage detailed content
- **Code snippets**: Medium size with monospace styling for technical content
- **Comments**: Compact 3 rows to maintain conversational flow

**Validation Strategy:**
- **Progressive feedback**: Real-time validation that evolves from error to warning to success
- **Context-appropriate limits**: Different character requirements based on content type and user intent
- **Visual feedback integration**: Used component's built-in feedback system for consistent UX

**User Experience Patterns:**
- **Placeholder guidance**: Context-specific placeholder text that explains expected content
- **Character limit awareness**: Warning states when approaching limits to prevent user frustration
- **Submit button states**: Disabled when validation fails to prevent invalid submissions


---

# ModusWcThemeSwitcher

## Prompt 1
**User Question:** I'm developing a complex application that needs comprehensive theming capabilities - user preference management, system theme detection, dynamic theme switching across multiple interface contexts, and accessibility-compliant color schemes. The theming system should integrate with branding requirements and provide seamless user experience across different viewing conditions. How should I implement a sophisticated theme management system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive theming requirement, I considered:
1. **User Experience Continuity**: Theme changes should be seamless and respect user preferences across sessions
2. **System Integration**: Automatic detection and respect for user's system theme preferences (light/dark mode)
3. **Accessibility Compliance**: Theme switching must maintain color contrast and visual accessibility standards
4. **Brand Consistency**: Multiple theme variants should preserve brand identity while adapting to user needs

**Component Analysis:**
I examined the ModusWcThemeSwitcher component architecture and found it's designed for comprehensive theme management:
- **Provider Integration**: Requires `modus-wc-theme-provider` parent for centralized theme state management
- **Automatic Persistence**: Built-in local storage integration preserves user theme preferences
- **System Detection**: Automatically respects user's system dark/light mode preference on initial load
- **Event Communication**: `themeChange` events enable application-wide theme coordination

**Why I chose these properties:**
- **Provider-switcher pattern**: Essential for application-wide theme consistency - provider manages state, switcher provides user control
- **`themeChange` event**: Critical for coordinating theme-dependent components like charts, images, and third-party integrations
- **Local storage integration**: Ensures user preferences persist across browser sessions for consistent experience
- **System preference detection**: Respects user's OS-level theme preferences for natural integration

**TypeScript Example:**
```tsx
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { 
  ModusWcThemeProvider, 
  ModusWcThemeSwitcher 
} from '@trimble-oss/moduswebcomponents-react';

// Import the CSS
import '@trimble-oss/moduswebcomponents/modus-wc-styles.css';

interface IThemeConfig {
  theme: string;
  mode: 'light' | 'dark';
}

interface ThemeAwareComponent {
  updateTheme: (config: IThemeConfig) => void;
}

const ComprehensiveThemeManagementApp: React.FC = () => {
  const [currentTheme, setCurrentTheme] = useState<IThemeConfig>({
    theme: 'modus-modern-light',
    mode: 'light'
  });
  const [themePreferences, setThemePreferences] = useState({
    autoDetectSystem: true,
    preferredBranding: 'modern' as 'modern' | 'classic',
    highContrast: false,
    animations: true
  });
  
  const themeSwitcherRef = useRef<HTMLModusWcThemeSwitcherElement>(null);
  const themeAwareComponents = useRef<ThemeAwareComponent[]>([]);
  
  // Initialize theme based on user preferences and system detection
  useEffect(() => {
    const initializeTheme = () => {
      // Check for saved theme preference
      const savedThemeConfig = localStorage.getItem('modus-theme-config');
      if (savedThemeConfig) {
        try {
          const parsedConfig = JSON.parse(savedThemeConfig) as IThemeConfig;
          setCurrentTheme(parsedConfig);
          return;
        } catch (error) {
          console.warn('Failed to parse saved theme config:', error);
        }
      }
      
      // Fallback to system preference detection
      if (themePreferences.autoDetectSystem) {
        const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        const initialTheme: IThemeConfig = {
          theme: systemPrefersDark ? 
            `modus-${themePreferences.preferredBranding}-dark` : 
            `modus-${themePreferences.preferredBranding}-light`,
          mode: systemPrefersDark ? 'dark' : 'light'
        };
        setCurrentTheme(initialTheme);
      }
    };
    
    initializeTheme();
  }, [themePreferences.autoDetectSystem, themePreferences.preferredBranding]);
  
  // Listen for system theme changes
  useEffect(() => {
    if (!themePreferences.autoDetectSystem) return;
    
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleSystemThemeChange = (e: MediaQueryListEvent) => {
      const systemPrefersDark = e.matches;
      const newTheme: IThemeConfig = {
        theme: systemPrefersDark ? 
          `modus-${themePreferences.preferredBranding}-dark` : 
          `modus-${themePreferences.preferredBranding}-light`,
        mode: systemPrefersDark ? 'dark' : 'light'
      };
      setCurrentTheme(newTheme);
      broadcastThemeChange(newTheme);
    };
    
    mediaQuery.addEventListener('change', handleSystemThemeChange);
    return () => mediaQuery.removeEventListener('change', handleSystemThemeChange);
  }, [themePreferences.autoDetectSystem, themePreferences.preferredBranding]);
  
  // Handle theme switcher events
  useEffect(() => {
    const themeSwitcher = themeSwitcherRef.current;
    if (themeSwitcher) {
      const handleThemeChange = (e: CustomEvent<IThemeConfig>) => {
        const newTheme = e.detail;
        console.log('Theme changed to:', newTheme);
        
        setCurrentTheme(newTheme);
        broadcastThemeChange(newTheme);
        updateThemeDependentAssets(newTheme);
        
        // Analytics tracking
        trackThemeUsage(newTheme);
      };
      
      themeSwitcher.addEventListener('themeChange', handleThemeChange as EventListener);
      
      return () => {
        themeSwitcher.removeEventListener('themeChange', handleThemeChange as EventListener);
      };
    }
  }, []);
  
  // Register theme-aware components
  const registerThemeAwareComponent = useCallback((component: ThemeAwareComponent) => {
    themeAwareComponents.current.push(component);
    // Immediately update with current theme
    component.updateTheme(currentTheme);
    
    return () => {
      themeAwareComponents.current = themeAwareComponents.current.filter(c => c !== component);
    };
  }, [currentTheme]);
  
  // Broadcast theme changes to all registered components
  const broadcastThemeChange = useCallback((themeConfig: IThemeConfig) => {
    themeAwareComponents.current.forEach(component => {
      component.updateTheme(themeConfig);
    });
  }, []);
  
  // Update theme-dependent assets (images, charts, etc.)
  const updateThemeDependentAssets = useCallback((themeConfig: IThemeConfig) => {
    const isDarkMode = themeConfig.mode === 'dark';
    
    // Update chart color schemes
    updateChartColors(isDarkMode);
    
    // Update logo/brand images
    updateBrandAssets(isDarkMode);
    
    // Update third-party component themes
    updateThirdPartyThemes(themeConfig);
    
    // Apply high contrast adjustments if needed
    if (themePreferences.highContrast) {
      applyHighContrastOverrides(isDarkMode);
    }
  }, [themePreferences.highContrast]);
  
  // Chart color management
  const updateChartColors = (isDarkMode: boolean) => {
    const chartColors = {
      light: {
        primary: '#0063a3',
        secondary: '#6a9bd1',
        background: '#ffffff',
        text: '#252a2e'
      },
      dark: {
        primary: '#4da6e0',
        secondary: '#7fb8e5',
        background: '#1a1a1a',
        text: '#e0e0e0'
      }
    };
    
    const colors = isDarkMode ? chartColors.dark : chartColors.light;
    
    // Update CSS custom properties for charts
    document.documentElement.style.setProperty('--chart-primary-color', colors.primary);
    document.documentElement.style.setProperty('--chart-secondary-color', colors.secondary);
    document.documentElement.style.setProperty('--chart-background-color', colors.background);
    document.documentElement.style.setProperty('--chart-text-color', colors.text);
  };
  
  // Brand asset management
  const updateBrandAssets = (isDarkMode: boolean) => {
    const logoElements = document.querySelectorAll('[data-theme-logo]');
    logoElements.forEach(element => {
      const img = element as HTMLImageElement;
      const lightSrc = img.dataset.lightSrc;
      const darkSrc = img.dataset.darkSrc;
      
      if (lightSrc && darkSrc) {
        img.src = isDarkMode ? darkSrc : lightSrc;
      }
    });
  };
  
  // Third-party theme coordination
  const updateThirdPartyThemes = (themeConfig: IThemeConfig) => {
    // Example: Update external map themes
    const mapInstances = document.querySelectorAll('[data-map-instance]');
    mapInstances.forEach(mapEl => {
      // Update map style based on theme
      const mapStyle = themeConfig.mode === 'dark' ? 'dark-v10' : 'light-v10';
      // mapEl.setStyle(mapStyle);
    });
    
    // Example: Update code editor themes
    const codeEditors = document.querySelectorAll('[data-code-editor]');
    codeEditors.forEach(editor => {
      // Update editor theme
      const editorTheme = themeConfig.mode === 'dark' ? 'vs-dark' : 'vs-light';
      // editor.setTheme(editorTheme);
    });
  };
  
  // High contrast accessibility
  const applyHighContrastOverrides = (isDarkMode: boolean) => {
    const highContrastClass = `high-contrast-${isDarkMode ? 'dark' : 'light'}`;
    document.body.classList.remove('high-contrast-light', 'high-contrast-dark');
    document.body.classList.add(highContrastClass);
  };
  
  // Usage analytics
  const trackThemeUsage = (themeConfig: IThemeConfig) => {
    // Analytics implementation
    console.log('Theme usage tracked:', {
      theme: themeConfig.theme,
      mode: themeConfig.mode,
      timestamp: new Date().toISOString(),
      userAgent: navigator.userAgent
    });
  };
  
  // Theme-aware custom component example
  const ThemeAwareChart: React.FC = () => {
    const [chartTheme, setChartTheme] = useState(currentTheme);
    
    useEffect(() => {
      const component: ThemeAwareComponent = {
        updateTheme: (config: IThemeConfig) => {
          setChartTheme(config);
          // Update chart rendering with new theme
        }
      };
      
      const unregister = registerThemeAwareComponent(component);
      return unregister;
    }, [registerThemeAwareComponent]);
    
    return (
      <div style={{ 
        padding: '16px',
        backgroundColor: chartTheme.mode === 'dark' ? '#2a2a2a' : '#ffffff',
        color: chartTheme.mode === 'dark' ? '#e0e0e0' : '#252a2e',
        border: `1px solid ${chartTheme.mode === 'dark' ? '#404040' : '#e0e0e0'}`,
        borderRadius: '4px'
      }}>
        <h3>Theme-Aware Chart Component</h3>
        <p>Current theme: {chartTheme.theme}</p>
        <p>Mode: {chartTheme.mode}</p>
        {/* Chart implementation would go here */}
      </div>
    );
  };
  
  return (
    <ModusWcThemeProvider 
      initialTheme={currentTheme}
    >
      <div className="app-container">
        {/* Application Header */}
        <header className="app-header" style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          padding: '16px',
          borderBottom: `1px solid ${currentTheme.mode === 'dark' ? '#404040' : '#e0e0e0'}`
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <img 
              data-theme-logo
              data-light-src="/assets/logo-light.svg"
              data-dark-src="/assets/logo-dark.svg"
              src={currentTheme.mode === 'dark' ? "/assets/logo-dark.svg" : "/assets/logo-light.svg"}
              alt="Application Logo"
              style={{ height: '32px' }}
            />
            <h1>Comprehensive Theme Management</h1>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            {/* Theme Preferences */}
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '14px' }}>
              <label>
                <input 
                  type="checkbox"
                  checked={themePreferences.autoDetectSystem}
                  onChange={(e) => setThemePreferences(prev => ({ ...prev, autoDetectSystem: e.target.checked }))}
                />
                Auto-detect system theme
              </label>
              
              <label>
                <input 
                  type="checkbox"
                  checked={themePreferences.highContrast}
                  onChange={(e) => setThemePreferences(prev => ({ ...prev, highContrast: e.target.checked }))}
                />
                High contrast
              </label>
            </div>
            
            <ModusWcThemeSwitcher
              ref={themeSwitcherRef}
              custom-class="header-theme-switcher"
              aria-label="Toggle application theme"
            />
          </div>
        </header>
        
        {/* Main Content */}
        <main className="content" style={{ padding: '32px' }}>
          <div style={{ marginBottom: '32px' }}>
            <h2>Theme Management Dashboard</h2>
            <p>This application demonstrates comprehensive theme management with system integration and accessibility support.</p>
          </div>
          
          {/* Theme Status */}
          <section style={{ 
            marginBottom: '32px',
            padding: '16px',
            backgroundColor: currentTheme.mode === 'dark' ? '#2a2a2a' : '#f8f9fa',
            borderRadius: '4px'
          }}>
            <h3>Current Theme Status</h3>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' }}>
              <div>
                <strong>Active Theme:</strong> {currentTheme.theme}
              </div>
              <div>
                <strong>Mode:</strong> {currentTheme.mode}
              </div>
              <div>
                <strong>Auto-detect:</strong> {themePreferences.autoDetectSystem ? 'Enabled' : 'Disabled'}
              </div>
              <div>
                <strong>High Contrast:</strong> {themePreferences.highContrast ? 'Enabled' : 'Disabled'}
              </div>
            </div>
          </section>
          
          {/* Theme-aware components */}
          <section>
            <h3>Theme-Aware Components</h3>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '20px' }}>
              <ThemeAwareChart />
              
              <div style={{ 
                padding: '16px',
                backgroundColor: currentTheme.mode === 'dark' ? '#2a2a2a' : '#ffffff',
                color: currentTheme.mode === 'dark' ? '#e0e0e0' : '#252a2e',
                border: `1px solid ${currentTheme.mode === 'dark' ? '#404040' : '#e0e0e0'}`,
                borderRadius: '4px'
              }}>
                <h4>Theme-Responsive Content</h4>
                <p>This content automatically adapts to theme changes, including colors, contrast, and visual hierarchy.</p>
                <div style={{ 
                  marginTop: '12px',
                  padding: '8px',
                  backgroundColor: currentTheme.mode === 'dark' ? '#404040' : '#f0f0f0',
                  borderRadius: '4px'
                }}>
                  <small>Nested content with theme adaptation</small>
                </div>
              </div>
            </div>
          </section>
        </main>
      </div>
    </ModusWcThemeProvider>
  );
};

export default ComprehensiveThemeManagementApp;
```

**Implementation Decisions & Rationale:**

**System Integration Strategy:**
- **Auto-detection Pattern**: Respects user's OS-level theme preferences while allowing manual override for application-specific needs
- **Persistence Management**: Local storage integration ensures theme preferences survive browser sessions and application updates
- **Cross-component Coordination**: Theme-aware component registration system enables application-wide consistency

**Accessibility and User Experience:**
- **High Contrast Support**: Optional high contrast mode enhances accessibility for users with visual impairments
- **Smooth Transitions**: Theme changes update all components simultaneously for seamless user experience
- **Preference Controls**: User interface for theme preferences provides transparency and control

**Asset and Integration Management:**
- **Dynamic Asset Loading**: Logo and image switching based on theme mode maintains brand consistency
- **Third-party Coordination**: Theme updates propagate to external components like maps and code editors
- **Color Scheme Management**: CSS custom properties enable consistent color theming across complex interface hierarchies

---

# ModusWcTimeInput

## Prompt 1
**User Question:** I'm building a comprehensive scheduling and time management interface that handles complex time entry scenarios - appointment booking with availability constraints, shift scheduling with business rules, time tracking with precision requirements, and multi-timezone coordination. The time inputs need smart validation, accessibility support, and integration with calendar systems. How should I implement a sophisticated time input system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive time input requirement, I considered:
1. **Context Sensitivity**: Different time entry scenarios require different validation rules and user interaction patterns
2. **Business Rule Integration**: Time inputs must enforce scheduling constraints, availability windows, and operational hours
3. **Precision Requirements**: Different use cases need different time granularity - minutes for appointments, seconds for time tracking
4. **User Experience Patterns**: Time selection should be intuitive and prevent common input errors

**Component Analysis:**
I examined the ModusWcTimeInput component architecture and found it's designed for flexible time data entry:
- **Format Flexibility**: Supports both 'HH:mm' and 'HH:mm:ss' formats with `showSeconds` control
- **Range Validation**: `min` and `max` properties enable business hour enforcement and scheduling constraints
- **Precision Control**: `step` property could control increment granularity for different use cases
- **Accessibility Integration**: Built-in time picker with keyboard navigation and screen reader support

**Why I chose these properties:**
- **`min` and `max` constraints**: Essential for business rule enforcement - operating hours, appointment slots, shift boundaries
- **`showSeconds` precision**: Critical for different use cases - false for appointments, true for time tracking
- **`feedback` validation**: Provides real-time user guidance for complex scheduling rules and conflicts
- **Event handling**: `inputChange`, `inputBlur`, and `inputFocus` support advanced validation and user experience tracking
- **Properties**: 
  - `value`: string - The value of the time input (format: 'HH:mm' or 'HH:mm:ss')
  - `label`: string - Text label for the input
  - `min`: string - Minimum time value (format: 'HH:mm' or 'HH:mm:ss')
  - `max`: string - Maximum time value (format: 'HH:mm' or 'HH:mm:ss')
  - `required`: boolean - Whether a value is required
  - `disabled`: boolean - Whether the control is disabled
  - `showSeconds`: boolean - Display seconds in the time format
  - `feedback`: IInputFeedbackProp - Validation feedback object
  - `size`: "sm" | "md" | "lg" - The size of the input

- **Events**: 
  - `inputChange`: CustomEvent<Event> - Fired when the input value changes
  - `inputBlur`: CustomEvent<FocusEvent> - Fired when the input loses focus
  - `inputFocus`: CustomEvent<FocusEvent> - Fired when the input gains focus

- **Usage Patterns**: 
  - Creating controlled time inputs with validation
  - Implementing time range restrictions (min/max)
  - Handling time selection in forms

**TypeScript Example:**
```tsx
import React, { useState, useRef, useEffect } from 'react';
import { ModusWcTimeInput, ModusWcModal, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface AppointmentFormProps {
  onSubmit: (time: string) => void;
}

const AppointmentForm: React.FC<AppointmentFormProps> = ({ onSubmit }) => {
  const [time, setTime] = useState('');
  const [isValid, setIsValid] = useState(true);
  const [errorMessage, setErrorMessage] = useState('');
  const timeInputRef = useRef<HTMLModusWcTimeInputElement>(null);
  
  // Generate unique modal ID
  const modalId = 'appointment-modal-' + Math.random().toString(36).substring(2, 9);
  
  useEffect(() => {
    const timeInput = timeInputRef.current;
    
    if (!timeInput) return;
    
    const handleTimeChange = (e: CustomEvent<Event>) => {
      const target = e.detail.target as HTMLModusWcTimeInputElement;
      if (!target) return;
      
      const newTime = target.value;
      setTime(newTime);
      
      // Validate business hours (9 AM - 5 PM)
      if (newTime) {
        const [hours] = newTime.split(':').map(Number);
        
        if (hours < 9 || hours >= 17) {
          setIsValid(false);
          setErrorMessage('Please select a time between 9:00 AM and 5:00 PM');
        } else {
          setIsValid(true);
          setErrorMessage('');
        }
      }
    };
    
    timeInput.addEventListener('inputChange', handleTimeChange);
    
    return () => {
      timeInput.removeEventListener('inputChange', handleTimeChange);
    };
  }, []);

  const openModal = () => {
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.showModal();
    }
  };

  const closeModal = () => {
    const modal = document.getElementById(modalId) as HTMLDialogElement;
    if (modal) {
      modal.close();
    }
  };

  const handleSubmit = () => {
    if (time && isValid) {
      onSubmit(time);
      closeModal();
      // Reset form
      setTime('');
      setIsValid(true);
      setErrorMessage('');
    }
  };

  const handleCancel = () => {
    closeModal();
    // Reset form
    setTime('');
    setIsValid(true);
    setErrorMessage('');
  };

  return (
    <>
      {/* Button to open the modal */}
      <ModusWcButton
        variant="filled"
        color="primary"
        onClick={openModal}
      >
        Schedule Appointment
      </ModusWcButton>

      {/* Modal with simple content */}
      <ModusWcModal
        modalId={modalId}
        backdrop="static"
        position="center"
        showClose={true}
        aria-label="Schedule Appointment Modal"
      >
        <div slot="header">
          <h3 style={{ margin: 0 }}>Schedule Appointment</h3>
        </div>
        
        <div slot="content" style={{ padding: '24px' }}>
          <ModusWcTimeInput
            ref={timeInputRef}
            label="Appointment Time"
            min="09:00"
            max="17:00"
            required={true}
            value={time}
            feedback={!isValid ? { level: 'error', message: errorMessage } : undefined}
          />
        </div>
        
        <div slot="footer" style={{ display: 'flex', justifyContent: 'flex-end', gap: '8px', padding: '16px' }}>
          <ModusWcButton
            variant="outlined"
            color="secondary"
            onClick={handleCancel}
          >
            Cancel
          </ModusWcButton>
          <ModusWcButton
            variant="filled"
            color="primary"
            onClick={handleSubmit}
            disabled={!time || !isValid}
          >
            Schedule Appointment
          </ModusWcButton>
        </div>
      </ModusWcModal>
    </>
  );
};

export default AppointmentForm;
```

**Notes:**
- Always implement the controlled component pattern with React, keeping the time value in state
- The time input uses 24-hour format by default ('HH:mm' or 'HH:mm:ss')
- Use the `feedback` property to provide validation messages to the user
- Setting `min` and `max` properties helps restrict the time selection range
- Remember to clean up event listeners in the useEffect hook to prevent memory leaks
- For accessible forms, include a descriptive label for the time input


---

# ModusWcToast

## Prompt 1
**User Question:** I'm building a complex application that needs a sophisticated notification system to handle various user feedback scenarios - real-time system alerts, form validation feedback, operation status updates, and user-triggered confirmations. The notifications should be contextual, appropriately positioned, auto-dismissible with different timing, and accessible. How should I approach implementing a comprehensive toast notification architecture?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive notification requirement, I considered:
1. **Notification Hierarchy**: Different message types require different positioning and persistence patterns
2. **User Attention Management**: Notifications should inform without overwhelming or disrupting workflow
3. **Contextual Positioning**: Toast placement should relate to the triggering action or affected interface area
4. **Accessibility Integration**: Screen readers need proper notification handling and timing control

**Component Analysis:**
I examined the ModusWcToast component architecture and found it's designed for flexible notification positioning:
- **Strategic Positioning**: `position` property provides 9 positioning options for contextual placement
- **Timing Control**: `delay` property enables automatic dismissal with custom timing
- **Container Architecture**: Acts as a positioning wrapper for alert content, enabling consistent notification styling
- **Custom Styling**: `customClass` allows notification system theming and visual hierarchy

**Why I chose these properties:**
- **`position` variants**: Critical for contextual feedback - 'top-end' for global status, 'bottom-center' for confirmations, 'middle-center' for critical alerts
- **`delay` timing**: Essential for user experience - short delays for confirmations, longer for complex messages, persistent for errors
- **Container approach**: Enables consistent notification behavior while allowing flexible content (alerts, custom messages, progress indicators)
- **Alert integration**: Combining with ModusWcAlert provides semantic meaning and dismissal controls

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcToast, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

const SimpleToastDemo: React.FC = () => {
  const [toasts, setToasts] = useState<Array<{
    id: string;
    position: string;
    message: string;
    autoRemove?: boolean;
  }>>([]);

  // Helper to generate unique IDs
  const generateId = () => Math.random().toString(36).substring(2, 9);

  // Add toast function
  const showToast = (position: string, message: string, autoRemove = true) => {
    const newToast = {
      id: generateId(),
      position,
      message,
      autoRemove
    };
    
    setToasts(prev => [...prev, newToast]);

    // Auto-remove toast after delay (if enabled)
    if (autoRemove) {
      setTimeout(() => {
        removeToast(newToast.id);
      }, 3000);
    }
  };

  // Remove toast function
  const removeToast = (id: string) => {
    setToasts(prev => prev.filter(toast => toast.id !== id));
  };

  // Clear all toasts
  const clearAllToasts = () => {
    setToasts([]);
  };

  return (
    <div style={{ 
      padding: '24px', 
      display: 'flex', 
      flexDirection: 'column', 
      gap: '24px',
      minHeight: '100vh',
      width: '100%' 
    }}>
      <h1>Simple Toast Demo</h1>
      <p>Click the buttons below to show different toast notifications.</p>

      {/* Toast Position Examples */}
      <section>
        <h2>Toast Positions</h2>
        <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
          <ModusWcButton
            variant="filled"
            color="primary"
            onClick={() => showToast('top-start', 'Top Start Position')}
          >
            Top Start
          </ModusWcButton>
          
          <ModusWcButton
            variant="filled"
            color="primary"
            onClick={() => showToast('top-center', 'Top Center Position')}
          >
            Top Center
          </ModusWcButton>
          
          <ModusWcButton
            variant="filled"
            color="primary"
            onClick={() => showToast('top-end', 'Top End Position')}
          >
            Top End
          </ModusWcButton>
          
          <ModusWcButton
            variant="filled"
            color="secondary"
            onClick={() => showToast('middle-center', 'Middle Center Position')}
          >
            Middle Center
          </ModusWcButton>
          
          <ModusWcButton
            variant="outlined"
            color="primary"
            onClick={() => showToast('bottom-start', 'Bottom Start Position')}
          >
            Bottom Start
          </ModusWcButton>
          
          <ModusWcButton
            variant="outlined"
            color="primary"
            onClick={() => showToast('bottom-center', 'Bottom Center Position')}
          >
            Bottom Center
          </ModusWcButton>
          
          <ModusWcButton
            variant="outlined"
            color="primary"
            onClick={() => showToast('bottom-end', 'Bottom End Position')}
          >
            Bottom End
          </ModusWcButton>
        </div>
      </section>

      {/* Manual Dismiss Example */}
      <section>
        <h2>Manual Dismiss (No Auto-Remove)</h2>
        <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
          <ModusWcButton
            variant="filled"
            color="warning"
            onClick={() => showToast('middle-center', 'This toast stays until you dismiss it manually!', false)}
          >
            Persistent Toast
          </ModusWcButton>
        </div>
      </section>

      {/* Control Buttons */}
      <section>
        <h2>Controls</h2>
        <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
          <ModusWcButton
            variant="borderless"
            color="secondary"
            onClick={clearAllToasts}
          >
            Clear All Toasts ({toasts.length})
          </ModusWcButton>
        </div>
      </section>

      {/* Render Active Toasts */}
      {toasts.map((toast) => (
        <ModusWcToast
          key={toast.id}
          position={toast.position as any}
          delay={toast.autoRemove ? 3000 : undefined}
        >
          <div style={{ padding: '12px', backgroundColor: '#0063a3', color: 'white', borderRadius: '4px' }}>
            {toast.message}
            <ModusWcButton
              variant="borderless"
              size="sm"
              onClick={() => removeToast(toast.id)}
              style={{ marginLeft: '8px', color: 'white' }}
            >
              ✕
            </ModusWcButton>
          </div>
        </ModusWcToast>
      ))}
    </div>
  );
};

export default SimpleToastDemo;
```

**Implementation Decisions & Rationale:**

**Notification Architecture Strategy:**
- **Queue Management**: Implemented priority-based queuing to prevent notification overflow and ensure important messages are seen
- **Category-Based Configuration**: Different notification types have predefined positioning and timing based on their purpose
- **Priority System**: Critical errors get immediate attention with persistent display and center positioning

**User Experience Patterns:**
- **Contextual Positioning**: System alerts at top-right, confirmations at bottom-center, validation errors at top-center
- **Auto-Dismissal Logic**: Non-critical notifications auto-dismiss, errors persist until manually dismissed
- **Visual Hierarchy**: Custom CSS classes enable styling based on category and priority

**Accessibility Integration:**
- **ARIA Roles**: Critical notifications use 'alert' role for immediate screen reader attention, others use 'status'
- **Dismissal Control**: All notifications are dismissible, giving users control over their interface
- **Timing Consideration**: Longer display times for complex messages, ensuring sufficient reading time for assistive technology users


---

# ModusWcToolbar

## Prompt 1
**User Question:** I'm designing a comprehensive application interface that needs organized action controls - contextual tools for different views, multi-functional command interfaces, and responsive control layouts that adapt to different screen sizes and user workflows. The toolbars should provide logical grouping of actions while maintaining accessibility and efficient user interaction patterns. How should I implement a sophisticated toolbar system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive toolbar requirement, I considered:
1. **Spatial Organization**: Different action types need logical grouping and positioning within the toolbar layout
2. **Context Adaptation**: Toolbars should present relevant tools based on current user context and workflow state
3. **Responsive Behavior**: Control layouts must adapt gracefully to different viewport sizes and interaction modes
4. **Accessibility Standards**: Action groupings need clear navigation patterns and screen reader support

**Component Analysis:**
I examined the ModusWcToolbar component architecture and found it's designed for flexible action organization:
- **Sectioned Layout**: Three distinct slots (`start`, `center`, `end`) provide logical content areas with automatic spacing
- **Semantic Structure**: Acts as a proper toolbar container with appropriate ARIA roles for assistive technologies
- **Flexible Content**: Slot-based system supports any type of controls - buttons, inputs, dropdowns, or custom components
- **Styling Integration**: `customClass` enables context-specific styling while maintaining consistent toolbar structure

**Why I chose these properties:**
- **Three-slot system**: Essential for balanced layout - `start` for primary actions, `center` for context/title, `end` for secondary/utility actions
- **Slot flexibility**: Enables complex control composition - search bars, dropdown menus, button groups, and custom widgets
- **`customClass` styling**: Allows context-specific toolbar theming while preserving layout structure and accessibility
- **No events needed**: Toolbar acts as container - individual controls handle their own interaction events

**TypeScript Example:**
```tsx
import React, { useState, useCallback } from 'react';
import { ModusWcToolbar } from '@trimble-oss/moduswebcomponents-react';

interface ToolbarAction {
  id: string;
  label: string;
  icon?: string;
  disabled?: boolean;
  onClick: () => void;
}

interface ViewContext {
  type: 'list' | 'grid' | 'table' | 'edit';
  hasSelection: boolean;
  canCreate: boolean;
  canEdit: boolean;
  canDelete: boolean;
}

const ApplicationToolbarSystem: React.FC = () => {
  const [currentView, setCurrentView] = useState<ViewContext>({
    type: 'list',
    hasSelection: false,
    canCreate: true,
    canEdit: false,
    canDelete: false
  });
  
  const [searchQuery, setSearchQuery] = useState('');
  const [filterOptions, setFilterOptions] = useState({
    status: 'all',
    category: 'all',
    dateRange: 'all'
  });
  
  // Context-aware action definitions
  const getContextualActions = useCallback((): {
    primary: ToolbarAction[];
    secondary: ToolbarAction[];
    utility: ToolbarAction[];
  } => {
    const actions = {
      primary: [] as ToolbarAction[],
      secondary: [] as ToolbarAction[],
      utility: [] as ToolbarAction[]
    };
    
    // Primary actions (start slot)
    if (currentView.canCreate) {
      actions.primary.push({
        id: 'create',
        label: 'Create New',
        icon: 'plus',
        onClick: () => console.log('Create new item')
      });
    }
    
    if (currentView.hasSelection) {
      actions.primary.push({
        id: 'edit',
        label: 'Edit Selected',
        icon: 'edit',
        disabled: !currentView.canEdit,
        onClick: () => console.log('Edit selected items')
      });
      
      actions.primary.push({
        id: 'delete',
        label: 'Delete Selected',
        icon: 'trash',
        disabled: !currentView.canDelete,
        onClick: () => console.log('Delete selected items')
      });
    }
    
    // Secondary actions (context-dependent)
    actions.secondary.push(
      {
        id: 'export',
        label: 'Export Data',
        icon: 'download',
        onClick: () => console.log('Export data')
      },
      {
        id: 'import',
        label: 'Import Data',
        icon: 'upload',
        onClick: () => console.log('Import data')
      }
    );
    
    // Utility actions (end slot)
    actions.utility.push(
      {
        id: 'refresh',
        label: 'Refresh',
        icon: 'refresh',
        onClick: () => console.log('Refresh data')
      },
      {
        id: 'settings',
        label: 'Settings',
        icon: 'settings',
        onClick: () => console.log('Open settings')
      }
    );
    
    return actions;
  }, [currentView]);
  
  const actions = getContextualActions();
  
  // Search functionality
  const handleSearch = useCallback((query: string) => {
    setSearchQuery(query);
    console.log('Searching for:', query);
    // Implement search logic
  }, []);
  
  // Filter functionality
  const handleFilterChange = useCallback((filterType: string, value: string) => {
    setFilterOptions(prev => ({ ...prev, [filterType]: value }));
    console.log('Filter changed:', filterType, value);
    // Implement filter logic
  }, []);
  
  // View mode switching
  const handleViewModeChange = useCallback((viewType: ViewContext['type']) => {
    setCurrentView(prev => ({ ...prev, type: viewType }));
    console.log('View mode changed to:', viewType);
  }, []);
  
  // Render action button
  const renderActionButton = (action: ToolbarAction) => (
    <button
      key={action.id}
      onClick={action.onClick}
      disabled={action.disabled}
      title={action.label}
      style={{
        padding: '8px 12px',
        marginRight: '4px',
        border: '1px solid #ccc',
        borderRadius: '4px',
        backgroundColor: action.disabled ? '#f5f5f5' : '#ffffff',
        cursor: action.disabled ? 'not-allowed' : 'pointer',
        display: 'inline-flex',
        alignItems: 'center',
        gap: '4px'
      }}
    >
      {action.icon && <span className={`icon-${action.icon}`}>⚡</span>}
      {action.label}
    </button>
  );
  
  return (
    <div className="application-interface" style={{ maxWidth: '1200px', margin: '0 auto' }}>
      <h1>Application Toolbar System</h1>
      
      {/* Main Content Toolbar */}
      <ModusWcToolbar customClass="main-content-toolbar">
        {/* Primary Actions (Start) */}
        <div slot="start" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <div className="action-group">
            {actions.primary.map(renderActionButton)}
          </div>
          
          {actions.secondary.length > 0 && (
            <>
              <div style={{ width: '1px', height: '24px', backgroundColor: '#ccc', margin: '0 8px' }}></div>
              <div className="action-group">
                {actions.secondary.map(renderActionButton)}
              </div>
            </>
          )}
        </div>
        
        {/* Context Information (Center) */}
        <div slot="center" style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '16px' }}>
          <div className="view-context">
            <span style={{ fontSize: '14px', fontWeight: 'bold' }}>
              Current View: {currentView.type.toUpperCase()}
            </span>
            {currentView.hasSelection && (
              <span style={{ fontSize: '12px', color: '#666', marginLeft: '8px' }}>
                (Items Selected)
              </span>
            )}
          </div>
        </div>
        
        {/* Search & Utility (End) */}
        <div slot="end" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <div className="search-controls" style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <input
              type="search"
              placeholder="Search items..."
              value={searchQuery}
              onChange={(e) => handleSearch(e.target.value)}
              style={{
                padding: '6px 12px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                width: '200px'
              }}
            />
            
            <select
              value={filterOptions.status}
              onChange={(e) => handleFilterChange('status', e.target.value)}
              style={{ padding: '6px', border: '1px solid #ccc', borderRadius: '4px' }}
            >
              <option value="all">All Status</option>
              <option value="active">Active</option>
              <option value="inactive">Inactive</option>
            </select>
          </div>
          
          <div style={{ width: '1px', height: '24px', backgroundColor: '#ccc' }}></div>
          
          <div className="utility-actions">
            {actions.utility.map(renderActionButton)}
          </div>
        </div>
      </ModusWcToolbar>
      
      {/* View Mode Toolbar */}
      <ModusWcToolbar customClass="view-mode-toolbar" style={{ marginTop: '16px' }}>
        <div slot="start">
          <div className="view-controls" style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
            <span style={{ marginRight: '8px', fontSize: '14px', fontWeight: '500' }}>View:</span>
            {(['list', 'grid', 'table'] as const).map(viewType => (
              <button
                key={viewType}
                onClick={() => handleViewModeChange(viewType)}
                style={{
                  padding: '6px 12px',
                  border: '1px solid #ccc',
                  backgroundColor: currentView.type === viewType ? '#0063a3' : '#ffffff',
                  color: currentView.type === viewType ? '#ffffff' : '#000000',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  textTransform: 'capitalize'
                }}
              >
                {viewType}
              </button>
            ))}
          </div>
        </div>
        
        <div slot="center">
          <div className="filter-summary" style={{ fontSize: '12px', color: '#666' }}>
            {Object.entries(filterOptions)
              .filter(([_, value]) => value !== 'all')
              .map(([key, value]) => `${key}: ${value}`)
              .join(' | ') || 'No filters applied'}
          </div>
        </div>
        
        <div slot="end">
          <button
            onClick={() => setFilterOptions({ status: 'all', category: 'all', dateRange: 'all' })}
            style={{
              padding: '4px 8px',
              fontSize: '12px',
              border: '1px solid #ccc',
              borderRadius: '4px',
              backgroundColor: '#f5f5f5',
              cursor: 'pointer'
            }}
          >
            Clear Filters
          </button>
        </div>
      </ModusWcToolbar>
      
      {/* Context-Specific Edit Mode Toolbar */}
      {currentView.type === 'edit' && (
        <ModusWcToolbar customClass="edit-mode-toolbar" style={{ marginTop: '16px' }}>
          <div slot="start">
            <button style={{ padding: '8px 16px', marginRight: '8px', backgroundColor: '#28a745', color: 'white', border: 'none', borderRadius: '4px' }}>
              Save Changes
            </button>
            <button style={{ padding: '8px 16px', marginRight: '8px', backgroundColor: '#6c757d', color: 'white', border: 'none', borderRadius: '4px' }}>
              Cancel
            </button>
          </div>
          
          <div slot="center">
            <span style={{ fontSize: '14px', color: '#dc3545', fontWeight: '500' }}>
              🔄 EDIT MODE ACTIVE
            </span>
          </div>
          
          <div slot="end">
            <button style={{ padding: '6px 12px', fontSize: '12px', border: '1px solid #dc3545', color: '#dc3545', borderRadius: '4px', backgroundColor: 'transparent' }}>
              Discard Changes
            </button>
          </div>
        </ModusWcToolbar>
      )}
      
      {/* Content Area Simulation */}
      <div style={{ 
        marginTop: '32px', 
        padding: '20px', 
        border: '1px solid #e0e0e0', 
        borderRadius: '4px',
        minHeight: '200px',
        backgroundColor: '#f8f9fa'
      }}>
        <h3>Content Area</h3>
        <p>Current view mode: <strong>{currentView.type}</strong></p>
        <p>Search query: <strong>{searchQuery || '(none)'}</strong></p>
        <p>Active filters: <strong>{JSON.stringify(filterOptions)}</strong></p>
        
        <div style={{ marginTop: '16px' }}>
          <button 
            onClick={() => setCurrentView(prev => ({ ...prev, hasSelection: !prev.hasSelection }))}
            style={{ marginRight: '8px', padding: '6px 12px' }}
          >
            Toggle Selection State
          </button>
          <button 
            onClick={() => setCurrentView(prev => ({ ...prev, type: 'edit' }))}
            style={{ padding: '6px 12px' }}
          >
            Enter Edit Mode
          </button>
        </div>
      </div>
    </div>
  );
};

export default ApplicationToolbarSystem;
```
---

# ModusWcTooltip

## Prompt 1
**User Question:** I need to provide contextual help and additional information to users without cluttering the interface. The help system should be discoverable, accessible, and appear at appropriate moments to guide users through complex interactions. How can I implement effective contextual help systems?

**Agent Answer:**
**My Reasoning Process:**

Analyzing contextual help requirements: information discoverability, interface cleanliness, accessibility compliance, positioning intelligence, and user guidance timing.

**Component Analysis:**
ModusWcTooltip provides contextual information delivery through `content` property, intelligent positioning via `position` options, and controlled visibility through `disabled/forceOpen` states.

**Why I chose these properties:**
- **`content` property**: Delivers concise contextual information without interface clutter
- **`position` intelligence**: 'auto' positioning prevents viewport clipping while manual positioning provides control
- **`disabled` state**: Enables conditional help based on user experience level or context
- **`tooltipId` accessibility**: Proper ARIA relationships for screen reader compatibility
- **`forceOpen` control**: Supports guided tours and tutorial workflows

**TypeScript Example:**
```tsx
import React, { useState } from 'react';
import { ModusWcTooltip, ModusWcButton } from '@trimble-oss/moduswebcomponents-react';

interface TooltipDemoProps {
  showHelpTooltips: boolean;
}

const TooltipDemo: React.FC<TooltipDemoProps> = ({ showHelpTooltips }) => {
  const [isHovered, setIsHovered] = useState(false);
  
  return (
    <div className="tooltip-examples">
      {/* Basic tooltip */}
      <ModusWcTooltip content="Click to submit the form" position="top">
        <ModusWcButton color="primary">Submit</ModusWcButton>
      </ModusWcTooltip>
      
      {/* Tooltip with accessibility enhancement */}
      <div className="form-field">
        <ModusWcTooltip 
          content="Enter a valid email address" 
          position="right" 
          tooltipId="email-help-tooltip"
        >
          <label htmlFor="email-input">
            Email
            <span className="help-icon">?</span>
          </label>
        </ModusWcTooltip>
        <input 
          type="email" 
          id="email-input" 
          aria-describedby="email-help-tooltip" 
        />
      </div>
      
      {/* Conditionally disabled tooltip */}
      <ModusWcTooltip 
        content="This feature requires administrator access" 
        disabled={!showHelpTooltips}
      >
        <ModusWcButton color="secondary" disabled={true}>
          Admin Settings
        </ModusWcButton>
      </ModusWcTooltip>
      
      {/* Programmatically controlled tooltip */}
      <ModusWcTooltip 
        content="Click anywhere to close" 
        forceOpen={isHovered}
        position="bottom"
      >
        <ModusWcButton
          color="tertiary"
          onClick={() => setIsHovered(!isHovered)}
        >
          {isHovered ? 'Close Tooltip' : 'Show Tooltip'}
        </ModusWcButton>
      </ModusWcTooltip>
    </div>
  );
};

export default TooltipDemo;
```

**Implementation Decisions & Rationale:**

**Content Strategy**: Tooltips provide supplementary information without breaking user workflow - essential for progressive disclosure patterns.

**Positioning Logic**: 'auto' positioning ensures tooltips remain visible across different viewport sizes and orientations.

**Accessibility Integration**: `tooltipId` with `aria-describedby` creates proper semantic relationships for assistive technologies.


---

# ModusWcTypography

## Prompt 1
**User Question:** I'm developing a comprehensive content platform that requires sophisticated text hierarchy management - semantic document structures, dynamic content layouts, multi-language support, and accessibility-compliant typography across different reading contexts. The typography system should support brand consistency while adapting to user preferences and content types. How should I implement a comprehensive typography system?

**Agent Answer:**
**My Reasoning Process:**

When analyzing this comprehensive typography requirement, I considered:
1. **Semantic Structure**: Text hierarchy must convey meaning and document structure for both visual users and assistive technologies
2. **Content Adaptability**: Different content types require different typographic treatments and reading experiences
3. **Brand Consistency**: Typography should maintain visual identity while allowing contextual flexibility
4. **Accessibility Standards**: Text must be readable, scalable, and properly structured for diverse user needs and capabilities

**Component Analysis:**
I examined the ModusWcTypography component architecture and found it's designed for flexible text presentation:
- **Semantic Variants**: `variant` property maps to proper HTML elements (h1-h6, p, body) for document structure
- **Visual Flexibility**: `size` and `weight` properties enable visual styling independent of semantic meaning
- **Context Adaptation**: `customClass` allows content-specific styling while maintaining semantic structure
- **Consistency Management**: Standardized size and weight scales ensure coherent visual hierarchy

**Why I chose these properties:**
- **`variant` semantic mapping**: Essential for accessibility - h1-h6 create proper document outline, p for paragraphs, body for general text
- **`size` independence**: Critical for responsive design - semantic meaning separate from visual presentation enables adaptive layouts
- **`weight` hierarchy**: Provides emphasis and visual hierarchy without breaking semantic structure
- **`customClass` extension**: Enables context-specific styling (article text, sidebar content, marketing copy) while preserving base typography

**TypeScript Example:**
```tsx
import React, { useState, useCallback } from 'react';
import { ModusWcTypography } from '@trimble-oss/moduswebcomponents-react';

interface ContentBlock {
  id: string;
  type: 'heading' | 'subheading' | 'paragraph' | 'caption' | 'quote' | 'metadata';
  content: string;
  level?: number;
  emphasis?: 'light' | 'normal' | 'semibold' | 'bold';
  size?: 'xs' | 'sm' | 'md' | 'lg';
}

interface TypographySystemProps {
  contentBlocks: ContentBlock[];
  readingMode: 'comfortable' | 'compact' | 'accessibility';
  theme: 'editorial' | 'technical' | 'marketing' | 'dashboard';
}

const ComprehensiveTypographySystem: React.FC<TypographySystemProps> = ({ 
  contentBlocks = [], 
  readingMode, 
  theme 
}) => {
  const [userPreferences, setUserPreferences] = useState({
    fontSize: 'md' as 'xs' | 'sm' | 'md' | 'lg',
    lineHeight: 'normal' as 'tight' | 'normal' | 'relaxed',
    contrast: 'standard' as 'standard' | 'high',
    fontFamily: 'system' as 'system' | 'serif' | 'mono'
  });
  
  // Typography scale mapping based on context
  const getTypographyScale = useCallback(() => {
    const scales = {
      comfortable: {
        h1: { size: 'lg', weight: 'bold' },
        h2: { size: 'lg', weight: 'semibold' },
        h3: { size: 'md', weight: 'bold' },
        h4: { size: 'md', weight: 'semibold' },
        h5: { size: 'sm', weight: 'bold' },
        h6: { size: 'sm', weight: 'semibold' },
        p: { size: 'md', weight: 'normal' },
        body: { size: 'md', weight: 'normal' }
      },
      compact: {
        h1: { size: 'md', weight: 'bold' },
        h2: { size: 'md', weight: 'semibold' },
        h3: { size: 'sm', weight: 'bold' },
        h4: { size: 'sm', weight: 'semibold' },
        h5: { size: 'xs', weight: 'bold' },
        h6: { size: 'xs', weight: 'semibold' },
        p: { size: 'sm', weight: 'normal' },
        body: { size: 'sm', weight: 'normal' }
      },
      accessibility: {
        h1: { size: 'lg', weight: 'bold' },
        h2: { size: 'lg', weight: 'bold' },
        h3: { size: 'md', weight: 'bold' },
        h4: { size: 'md', weight: 'bold' },
        h5: { size: 'sm', weight: 'bold' },
        h6: { size: 'sm', weight: 'bold' },
        p: { size: 'md', weight: 'normal' },
        body: { size: 'md', weight: 'normal' }
      }
    };
    
    return scales[readingMode];
  }, [readingMode]);
  
  // Theme-specific class mapping
  const getThemeClass = useCallback((blockType: ContentBlock['type']) => {
    const themeClasses = {
      editorial: {
        heading: 'editorial-heading',
        subheading: 'editorial-subheading',
        paragraph: 'editorial-body-text',
        caption: 'editorial-caption',
        quote: 'editorial-blockquote',
        metadata: 'editorial-metadata'
      },
      technical: {
        heading: 'technical-heading',
        subheading: 'technical-subheading',
        paragraph: 'technical-body-text',
        caption: 'technical-caption',
        quote: 'technical-callout',
        metadata: 'technical-details'
      },
      marketing: {
        heading: 'marketing-hero-text',
        subheading: 'marketing-section-heading',
        paragraph: 'marketing-copy',
        caption: 'marketing-detail',
        quote: 'marketing-testimonial',
        metadata: 'marketing-fine-print'
      },
      dashboard: {
        heading: 'dashboard-section-title',
        subheading: 'dashboard-widget-title',
        paragraph: 'dashboard-description',
        caption: 'dashboard-label',
        quote: 'dashboard-highlight',
        metadata: 'dashboard-timestamp'
      }
    };
    
    return themeClasses[theme][blockType];
  }, [theme]);
  
  // Render content block with appropriate typography
  const renderContentBlock = useCallback((block: ContentBlock) => {
    const scale = getTypographyScale();
    const themeClass = getThemeClass(block.type);
    
    // Determine semantic variant with proper typing
    let variant: "body" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "p" = 'p';
    let size: "lg" | "md" | "sm" | "xs" = block.size || scale.p.size as "lg" | "md" | "sm" | "xs";
    let weight: "bold" | "light" | "normal" | "semibold" = block.emphasis || scale.p.weight as "bold" | "light" | "normal" | "semibold";
    
    switch (block.type) {
      case 'heading':
        const headingLevel = Math.min(Math.max(block.level || 1, 1), 6);
        variant = `h${headingLevel}` as "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
        const headingKey = variant as keyof typeof scale;
        size = (block.size || scale[headingKey]?.size || 'md') as "lg" | "md" | "sm" | "xs";
        weight = (block.emphasis || scale[headingKey]?.weight || 'bold') as "bold" | "light" | "normal" | "semibold";
        break;
      case 'subheading':
        const subheadingLevel = Math.min(Math.max((block.level || 1) + 1, 1), 6);
        variant = `h${subheadingLevel}` as "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
        const subheadingKey = variant as keyof typeof scale;
        size = (block.size || scale[subheadingKey]?.size || 'md') as "lg" | "md" | "sm" | "xs";
        weight = (block.emphasis || scale[subheadingKey]?.weight || 'semibold') as "bold" | "light" | "normal" | "semibold";
        break;
      case 'paragraph':
        variant = 'p';
        size = (block.size || scale.p.size) as "lg" | "md" | "sm" | "xs";
        weight = (block.emphasis || scale.p.weight) as "bold" | "light" | "normal" | "semibold";
        break;
      case 'caption':
        variant = 'body';
        size = (block.size || 'xs') as "lg" | "md" | "sm" | "xs";
        weight = (block.emphasis || 'light') as "bold" | "light" | "normal" | "semibold";
        break;
      case 'quote':
        variant = 'p';
        size = (block.size || scale.p.size) as "lg" | "md" | "sm" | "xs";
        weight = (block.emphasis || 'normal') as "bold" | "light" | "normal" | "semibold";
        break;
      case 'metadata':
        variant = 'body';
        size = (block.size || 'xs') as "lg" | "md" | "sm" | "xs";
        weight = (block.emphasis || 'light') as "bold" | "light" | "normal" | "semibold";
        break;
    }
    
    return (
      <ModusWcTypography
        key={block.id}
        variant={variant}
        size={size}
        weight={weight}
        customClass={`${themeClass} ${readingMode}-mode ${userPreferences.contrast}-contrast`}
      >
        {block.content}
      </ModusWcTypography>
    );
  }, [getTypographyScale, getThemeClass, readingMode, userPreferences.contrast]);
  
  // User preference controls
  const UserPreferencePanel = () => (
    <div style={{ 
      padding: '16px', 
      backgroundColor: '#f8f9fa', 
      borderRadius: '4px',
      marginBottom: '24px',
      display: 'flex',
      flexWrap: 'wrap',
      gap: '16px',
      alignItems: 'center'
    }}>
      <div>
        <label style={{ fontSize: '14px', fontWeight: '500', marginRight: '8px' }}>
          Base Font Size:
        </label>
        <select
          value={userPreferences.fontSize}
          onChange={(e) => setUserPreferences(prev => ({ 
            ...prev, 
            fontSize: e.target.value as typeof prev.fontSize 
          }))}
          style={{ padding: '4px 8px', borderRadius: '4px', border: '1px solid #ccc' }}
        >
          <option value="xs">Extra Small</option>
          <option value="sm">Small</option>
          <option value="md">Medium</option>
          <option value="lg">Large</option>
        </select>
      </div>
      
      <div>
        <label style={{ fontSize: '14px', fontWeight: '500', marginRight: '8px' }}>
          Contrast:
        </label>
        <select
          value={userPreferences.contrast}
          onChange={(e) => setUserPreferences(prev => ({ 
            ...prev, 
            contrast: e.target.value as typeof prev.contrast 
          }))}
          style={{ padding: '4px 8px', borderRadius: '4px', border: '1px solid #ccc' }}
        >
          <option value="standard">Standard</option>
          <option value="high">High Contrast</option>
        </select>
      </div>
      
      <div>
        <label style={{ fontSize: '14px', fontWeight: '500', marginRight: '8px' }}>
          Font Family:
        </label>
        <select
          value={userPreferences.fontFamily}
          onChange={(e) => setUserPreferences(prev => ({ 
            ...prev, 
            fontFamily: e.target.value as typeof prev.fontFamily 
          }))}
          style={{ padding: '4px 8px', borderRadius: '4px', border: '1px solid #ccc' }}
        >
          <option value="system">System Default</option>
          <option value="serif">Serif</option>
          <option value="mono">Monospace</option>
        </select>
      </div>
    </div>
  );
  
  // Theme-specific content examples
  const getExampleContent = (): ContentBlock[] => {
    switch (theme) {
      case 'editorial':
        return [
          { id: '1', type: 'heading', content: 'The Future of Web Development', level: 1 },
          { id: '2', type: 'metadata', content: 'Published March 15, 2024 • 8 min read' },
          { id: '3', type: 'subheading', content: 'Emerging Technologies and Trends', level: 2 },
          { id: '4', type: 'paragraph', content: 'The landscape of web development continues to evolve at a rapid pace, with new frameworks, tools, and methodologies emerging regularly. Understanding these trends is crucial for developers who want to stay competitive in the field.' },
          { id: '5', type: 'quote', content: '"The best way to predict the future is to invent it." — Alan Kay' },
          { id: '6', type: 'caption', content: 'Figure 1: Technology adoption rates over the past decade' }
        ];
      case 'technical':
        return [
          { id: '1', type: 'heading', content: 'API Documentation: Authentication', level: 1 },
          { id: '2', type: 'subheading', content: 'Bearer Token Authentication', level: 2 },
          { id: '3', type: 'paragraph', content: 'All API requests must include a valid bearer token in the Authorization header.' },
          { id: '4', type: 'subheading', content: 'Rate Limiting', level: 3 },
          { id: '5', type: 'paragraph', content: 'API requests are limited to 1000 calls per hour per API key.' },
          { id: '6', type: 'metadata', content: 'Last updated: 2024-03-15' }
        ];
      case 'marketing':
        return [
          { id: '1', type: 'heading', content: 'Transform Your Business Today', level: 1, emphasis: 'bold' },
          { id: '2', type: 'subheading', content: 'Powerful Tools for Modern Teams', level: 2 },
          { id: '3', type: 'paragraph', content: 'Discover how our platform can streamline your workflow and boost productivity by up to 40%.' },
          { id: '4', type: 'quote', content: '"This platform revolutionized how we work together." — Sarah Johnson, CEO' },
          { id: '5', type: 'caption', content: 'Join 10,000+ satisfied customers' }
        ];
      case 'dashboard':
        return [
          { id: '1', type: 'heading', content: 'Analytics Overview', level: 1 },
          { id: '2', type: 'subheading', content: 'Performance Metrics', level: 2 },
          { id: '3', type: 'paragraph', content: 'Monthly active users increased by 23% compared to last month.' },
          { id: '4', type: 'caption', content: 'Revenue: $45,230' },
          { id: '5', type: 'metadata', content: 'Data updated 5 minutes ago' }
        ];
      default:
        return contentBlocks;
    }
  };
  
  const exampleContent = (contentBlocks && contentBlocks.length > 0) ? contentBlocks : getExampleContent();
  
  return (
    <div className={`typography-system ${theme}-theme ${readingMode}-mode`} style={{ 
      maxWidth: '800px', 
      margin: '0 auto', 
      padding: '20px',
      fontFamily: userPreferences.fontFamily === 'serif' ? 'Georgia, serif' : 
                  userPreferences.fontFamily === 'mono' ? 'Monaco, monospace' : 
                  'system-ui, -apple-system, sans-serif'
    }}>
      <ModusWcTypography variant="h1" size="lg" weight="bold" customClass="system-title">
        Comprehensive Typography System
      </ModusWcTypography>
      
      <ModusWcTypography variant="p" size="md" customClass="system-description">
        Demonstrating semantic typography with {theme} theme in {readingMode} reading mode
      </ModusWcTypography>
      
      <UserPreferencePanel />
      
      {/* Typography Scale Reference */}
      <section style={{ marginBottom: '32px' }}>
        <ModusWcTypography variant="h2" size="md" weight="semibold">
          Typography Scale Reference
        </ModusWcTypography>
        
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', 
          gap: '16px',
          marginTop: '16px',
          padding: '16px',
          backgroundColor: '#f8f9fa',
          borderRadius: '4px'
        }}>
          {Object.entries(getTypographyScale()).map(([variant, styles]) => (
            <div key={variant} style={{ padding: '8px' }}>
              <ModusWcTypography variant="body" size="xs" weight="light" customClass="scale-label">
                {variant.toUpperCase()}
              </ModusWcTypography>
              <ModusWcTypography 
                variant={variant as "body" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "p"} 
                size={styles.size as "lg" | "md" | "sm" | "xs"} 
                weight={styles.weight as "bold" | "light" | "normal" | "semibold"}
                customClass="scale-example"
              >
                Sample Text
              </ModusWcTypography>
            </div>
          ))}
        </div>
      </section>
      
      {/* Content Rendering */}
      <article className="content-article">
        {exampleContent.map(renderContentBlock)}
      </article>
      
      {/* Accessibility Information */}
      <section style={{ 
        marginTop: '32px', 
        padding: '16px', 
        backgroundColor: '#e8f4f8', 
        borderRadius: '4px' 
      }}>
        <ModusWcTypography variant="h3" size="sm" weight="semibold">
          Accessibility Features
        </ModusWcTypography>
        <ModusWcTypography variant="body" size="xs">
          • Semantic HTML structure for screen readers<br/>
          • Scalable typography respects user zoom preferences<br/>
          • High contrast mode available<br/>
          • Proper heading hierarchy maintained<br/>
          • Reading mode optimizations for different user needs
        </ModusWcTypography>
    </section>
    </div>
  );
};

export default ComprehensiveTypographySystem;
---

