# ConditionalView

## Description

A utility component that provides conditional rendering capabilities based on a boolean condition. ConditionalView simplifies the common pattern of conditionally displaying content by wrapping it in a clean, reusable component that only renders its children when a specified condition is met.

## Aliases

- ConditionalView
- Conditional Renderer
- If Component
- Show Component

## Props Breakdown

**Extends:** Standalone interface (no HTML element inheritance)

| Prop | Type | Default | Required | Description |
|------|------|---------|----------|-------------|
| `condition` | `ReactNode \| undefined` | - | Yes | The condition that determines if children should render |
| `children` | `ReactNode` | - | Yes | Content to render when condition is truthy |

## Examples

### Basic Conditional Rendering

```tsx
import { ConditionalView, Button, Text } from '@delightui/components';

function BasicConditionalExample() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  return (
    <div>
      <ConditionalView condition={isLoggedIn}>
        <Text>Welcome back! You are logged in.</Text>
      </ConditionalView>

      <ConditionalView condition={!isLoggedIn}>
        <Text>Please log in to continue.</Text>
      </ConditionalView>

      <Button onClick={() => setIsLoggedIn(!isLoggedIn)}>
        {isLoggedIn ? 'Log Out' : 'Log In'}
      </Button>
    </div>
  );
}
```

### User Permission Based Rendering

```tsx
import { ConditionalView, Button, Text } from '@delightui/components';

function PermissionBasedExample() {
  const [user, setUser] = useState({
    name: 'John Doe',
    role: 'admin',
    permissions: ['read', 'write', 'delete']
  });

  const hasPermission = (permission: string) => {
    return user.permissions.includes(permission);
  };

  return (
    <div style={{ padding: '20px' }}>
      <Text size="large">User Dashboard</Text>
      
      <ConditionalView condition={hasPermission('read')}>
        <div style={{ marginTop: '16px' }}>
          <Text>📊 View Reports</Text>
        </div>
      </ConditionalView>

      <ConditionalView condition={hasPermission('write')}>
        <div style={{ marginTop: '16px' }}>
          <Button>Create New Report</Button>
        </div>
      </ConditionalView>

      <ConditionalView condition={hasPermission('delete')}>
        <div style={{ marginTop: '16px' }}>
          <Button style="Destructive">Delete Data</Button>
        </div>
      </ConditionalView>

      <ConditionalView condition={user.role === 'admin'}>
        <div style={{ marginTop: '16px', padding: '12px', backgroundColor: '#fff3cd' }}>
          <Text weight="Bold">Admin Panel Access</Text>
        </div>
      </ConditionalView>
    </div>
  );
}
```

### Loading State Management

```tsx
import { ConditionalView, Spinner, Button, Text } from '@delightui/components';

function LoadingStateExample() {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState<string[]>([]);
  const [error, setError] = useState<string>('');

  const fetchData = async () => {
    setIsLoading(true);
    setError('');
    
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 2000));
      setData(['Item 1', 'Item 2', 'Item 3']);
    } catch (err) {
      setError('Failed to load data');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <Button onClick={fetchData} disabled={isLoading}>
        Load Data
      </Button>

      <ConditionalView condition={isLoading}>
        <div style={{ textAlign: 'center', padding: '40px' }}>
          <Spinner />
          <Text>Loading data...</Text>
        </div>
      </ConditionalView>

      <ConditionalView condition={error}>
        <div style={{ 
          marginTop: '16px', 
          padding: '12px', 
          backgroundColor: '#f8d7da',
          borderRadius: '4px' 
        }}>
          <Text color="error">{error}</Text>
        </div>
      </ConditionalView>

      <ConditionalView condition={data.length > 0 && !isLoading}>
        <div style={{ marginTop: '16px' }}>
          <Text weight="Bold">Data:</Text>
          {data.map((item, index) => (
            <Text key={index}>• {item}</Text>
          ))}
        </div>
      </ConditionalView>
    </div>
  );
}
```

### Form Field Visibility

```tsx
import { ConditionalView, Form, FormField, Input, Select, Button, RadioButton } from '@delightui/components';

function FormFieldVisibilityExample() {
  const [formData, setFormData] = useState({
    accountType: '',
    hasCompany: false,
    preferredContact: ''
  });

  const handleSubmit = (data: any) => {
    console.log('Form submitted:', data);
  };

  return (
    <Form onSubmit={handleSubmit}>
      <FormField name="accountType" label="Account Type" required>
        <Select 
          value={formData.accountType}
          onValueChange={(value) => setFormData(prev => ({ ...prev, accountType: value }))}
        >
          <option value="">Select account type</option>
          <option value="personal">Personal</option>
          <option value="business">Business</option>
        </Select>
      </FormField>

      <ConditionalView condition={formData.accountType === 'business'}>
        <FormField name="companyName" label="Company Name" required>
          <Input placeholder="Enter company name" />
        </FormField>

        <FormField name="taxId" label="Tax ID">
          <Input placeholder="Enter tax identification number" />
        </FormField>
      </ConditionalView>

      <FormField name="preferredContact" label="Preferred Contact Method">
        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
          <RadioButton
            name="contact"
            value="email"
            checked={formData.preferredContact === 'email'}
            onValueChange={(value) => setFormData(prev => ({ ...prev, preferredContact: value }))}
          >
            Email
          </RadioButton>
          <RadioButton
            name="contact"
            value="phone"
            checked={formData.preferredContact === 'phone'}
            onValueChange={(value) => setFormData(prev => ({ ...prev, preferredContact: value }))}
          >
            Phone
          </RadioButton>
        </div>
      </FormField>

      <ConditionalView condition={formData.preferredContact === 'phone'}>
        <FormField name="phoneNumber" label="Phone Number" required>
          <Input inputType="Text" placeholder="Enter phone number" />
        </FormField>
      </ConditionalView>

      <Button actionType="submit">Create Account</Button>
    </Form>
  );
}
```

### Feature Flag Implementation

```tsx
import { ConditionalView, Button, Text, Card } from '@delightui/components';

function FeatureFlagExample() {
  const [featureFlags, setFeatureFlags] = useState({
    newDesign: true,
    betaFeatures: false,
    advancedSettings: true,
    experimentalUi: false
  });

  const toggleFeature = (feature: keyof typeof featureFlags) => {
    setFeatureFlags(prev => ({
      ...prev,
      [feature]: !prev[feature]
    }));
  };

  return (
    <div style={{ padding: '20px' }}>
      <Text size="large" weight="Bold">Feature Flags Demo</Text>
      
      <div style={{ marginTop: '20px', display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
        {Object.entries(featureFlags).map(([feature, enabled]) => (
          <Button
            key={feature}
            size="Small"
            type={enabled ? 'Filled' : 'Outlined'}
            onClick={() => toggleFeature(feature as keyof typeof featureFlags)}
          >
            {feature}: {enabled ? 'ON' : 'OFF'}
          </Button>
        ))}
      </div>

      <ConditionalView condition={featureFlags.newDesign}>
        <Card style={{ marginTop: '20px', backgroundColor: '#e3f2fd' }}>
          <Text weight="Bold">🎨 New Design System</Text>
          <Text>You're seeing the new design system interface!</Text>
        </Card>
      </ConditionalView>

      <ConditionalView condition={featureFlags.betaFeatures}>
        <Card style={{ marginTop: '20px', backgroundColor: '#fff3e0' }}>
          <Text weight="Bold">🧪 Beta Features</Text>
          <Text>Beta features are now available in your account.</Text>
          <Button size="Small" style={{ marginTop: '8px' }}>
            Try Beta Feature
          </Button>
        </Card>
      </ConditionalView>

      <ConditionalView condition={featureFlags.advancedSettings}>
        <Card style={{ marginTop: '20px', backgroundColor: '#f3e5f5' }}>
          <Text weight="Bold">⚙️ Advanced Settings</Text>
          <Text>Advanced configuration options are enabled.</Text>
        </Card>
      </ConditionalView>

      <ConditionalView condition={featureFlags.experimentalUi}>
        <Card style={{ marginTop: '20px', backgroundColor: '#ffebee' }}>
          <Text weight="Bold">🚀 Experimental UI</Text>
          <Text>Warning: Experimental features may be unstable.</Text>
        </Card>
      </ConditionalView>
    </div>
  );
}
```

### Responsive Content Display

```tsx
import { ConditionalView, Text, Button, Card } from '@delightui/components';

function ResponsiveContentExample() {
  const [screenSize, setScreenSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight
  });

  useEffect(() => {
    const handleResize = () => {
      setScreenSize({
        width: window.innerWidth,
        height: window.innerHeight
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const isMobile = screenSize.width < 768;
  const isTablet = screenSize.width >= 768 && screenSize.width < 1024;
  const isDesktop = screenSize.width >= 1024;

  return (
    <div style={{ padding: '20px' }}>
      <Text size="large">Responsive Content Demo</Text>
      <Text size="small">Screen width: {screenSize.width}px</Text>

      <ConditionalView condition={isMobile}>
        <Card style={{ marginTop: '16px', backgroundColor: '#e8f5e8' }}>
          <Text weight="Bold">📱 Mobile View</Text>
          <Text>Optimized for mobile devices</Text>
          <Button size="Small" style={{ marginTop: '8px', width: '100%' }}>
            Mobile Action
          </Button>
        </Card>
      </ConditionalView>

      <ConditionalView condition={isTablet}>
        <Card style={{ marginTop: '16px', backgroundColor: '#fff3e0' }}>
          <Text weight="Bold">📱 Tablet View</Text>
          <Text>Medium screen layout</Text>
          <div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
            <Button size="Small">Action 1</Button>
            <Button size="Small">Action 2</Button>
          </div>
        </Card>
      </ConditionalView>

      <ConditionalView condition={isDesktop}>
        <Card style={{ marginTop: '16px', backgroundColor: '#e3f2fd' }}>
          <Text weight="Bold">🖥️ Desktop View</Text>
          <Text>Full desktop experience with all features</Text>
          <div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
            <Button>Primary Action</Button>
            <Button type="Outlined">Secondary</Button>
            <Button type="Ghost">Tertiary</Button>
          </div>
        </Card>
      </ConditionalView>
    </div>
  );
}
```

### Error Boundary with Conditional Recovery

```tsx
import { ConditionalView, Button, Text, Card } from '@delightui/components';

function ErrorBoundaryExample() {
  const [hasError, setHasError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [retryCount, setRetryCount] = useState(0);

  const triggerError = () => {
    setHasError(true);
    setErrorMessage('Something went wrong while processing your request.');
  };

  const handleRetry = () => {
    setRetryCount(prev => prev + 1);
    setHasError(false);
    setErrorMessage('');
    
    // Simulate operation that might fail
    if (Math.random() > 0.7) {
      setHasError(true);
      setErrorMessage('Operation failed again. Please try later.');
    }
  };

  const handleReset = () => {
    setHasError(false);
    setErrorMessage('');
    setRetryCount(0);
  };

  return (
    <div style={{ padding: '20px' }}>
      <Text size="large">Error Handling Demo</Text>
      
      <ConditionalView condition={!hasError}>
        <Card style={{ marginTop: '16px', backgroundColor: '#e8f5e8' }}>
          <Text>✅ Everything is working correctly!</Text>
          <Button 
            onClick={triggerError}
            style={{ marginTop: '12px' }}
            size="Small"
          >
            Trigger Error
          </Button>
        </Card>
      </ConditionalView>

      <ConditionalView condition={hasError}>
        <Card style={{ marginTop: '16px', backgroundColor: '#ffebee' }}>
          <Text weight="Bold" color="error">❌ Error Occurred</Text>
          <Text>{errorMessage}</Text>
          
          <ConditionalView condition={retryCount < 3}>
            <Button 
              onClick={handleRetry}
              style={{ marginTop: '12px', marginRight: '8px' }}
              size="Small"
            >
              Retry ({retryCount}/3)
            </Button>
          </ConditionalView>

          <Button 
            onClick={handleReset}
            type="Outlined"
            size="Small"
            style={{ marginTop: '12px' }}
          >
            Reset
          </Button>
        </Card>
      </ConditionalView>

      <ConditionalView condition={retryCount >= 3 && hasError}>
        <Card style={{ marginTop: '16px', backgroundColor: '#fff3e0' }}>
          <Text weight="Bold">⚠️ Maximum Retries Reached</Text>
          <Text>Please contact support if the problem persists.</Text>
          <Button 
            size="Small"
            style={{ marginTop: '8px' }}
          >
            Contact Support
          </Button>
        </Card>
      </ConditionalView>
    </div>
  );
}
```

### Multi-step Wizard Navigation

```tsx
import { ConditionalView, Button, Text, Card, ProgressBar } from '@delightui/components';

function WizardNavigationExample() {
  const [currentStep, setCurrentStep] = useState(1);
  const [completedSteps, setCompletedSteps] = useState<number[]>([]);
  
  const totalSteps = 4;
  const progress = (currentStep / totalSteps) * 100;

  const markStepComplete = (step: number) => {
    if (!completedSteps.includes(step)) {
      setCompletedSteps(prev => [...prev, step]);
    }
  };

  const goToNextStep = () => {
    markStepComplete(currentStep);
    if (currentStep < totalSteps) {
      setCurrentStep(prev => prev + 1);
    }
  };

  const goToPreviousStep = () => {
    if (currentStep > 1) {
      setCurrentStep(prev => prev - 1);
    }
  };

  return (
    <div style={{ padding: '20px', maxWidth: '600px' }}>
      <Text size="large" weight="Bold">Setup Wizard</Text>
      
      <ProgressBar 
        value={progress}
        max={100}
        style={{ marginTop: '16px' }}
      />
      
      <Text size="small" style={{ marginTop: '8px' }}>
        Step {currentStep} of {totalSteps}
      </Text>

      <ConditionalView condition={currentStep === 1}>
        <Card style={{ marginTop: '20px' }}>
          <Text weight="Bold">Step 1: Personal Information</Text>
          <Text>Please provide your personal details to get started.</Text>
        </Card>
      </ConditionalView>

      <ConditionalView condition={currentStep === 2}>
        <Card style={{ marginTop: '20px' }}>
          <Text weight="Bold">Step 2: Account Preferences</Text>
          <Text>Configure your account settings and preferences.</Text>
        </Card>
      </ConditionalView>

      <ConditionalView condition={currentStep === 3}>
        <Card style={{ marginTop: '20px' }}>
          <Text weight="Bold">Step 3: Security Setup</Text>
          <Text>Set up two-factor authentication and security options.</Text>
        </Card>
      </ConditionalView>

      <ConditionalView condition={currentStep === 4}>
        <Card style={{ marginTop: '20px', backgroundColor: '#e8f5e8' }}>
          <Text weight="Bold">Step 4: Complete Setup</Text>
          <Text>Review your information and complete the setup process.</Text>
        </Card>
      </ConditionalView>

      <div style={{ marginTop: '20px', display: 'flex', gap: '12px' }}>
        <ConditionalView condition={currentStep > 1}>
          <Button 
            type="Outlined"
            onClick={goToPreviousStep}
          >
            Previous
          </Button>
        </ConditionalView>

        <ConditionalView condition={currentStep < totalSteps}>
          <Button onClick={goToNextStep}>
            Next
          </Button>
        </ConditionalView>

        <ConditionalView condition={currentStep === totalSteps}>
          <Button 
            style="Primary"
            onClick={() => console.log('Setup complete!')}
          >
            Complete Setup
          </Button>
        </ConditionalView>
      </div>
    </div>
  );
}
```