# Date Field Component

A standalone date input component with calendar integration, validation, and form control support.

**Selector:** `ccl-datefield`

## Quick Start

1. **Import the component:**
```typescript
import { DateFieldComponent } from '@Crystal-Code-Labs/ccl-ui-components';
```

2. **Add to your component:**
```typescript
@Component({
  imports: [DateFieldComponent],
  // ... rest of component
})
```

3. **Use in template:**
```html
<ccl-datefield 
  [value]="selectedDate"
  [minDate]="minDate"
  [maxDate]="maxDate"
  (onChange)="onDateChange($event)">
</ccl-datefield>
```

## Inputs

- `value: Date | null` – Current date value (default: null)
- `format: string` – Display format placeholder (default: 'dd/MM/yyyy')
- `minDate?: Date` – Minimum selectable date
- `maxDate?: Date` – Maximum selectable date
- `disabled: boolean` – Disable the input (default: false)
- `required: boolean` – Mark as required field (default: false)
- `locale: string` – Locale for date formatting (default: 'en-US')

## Outputs

- `onChange: EventEmitter<Date | null>` – Emitted when date value changes

## Basic Usage

### Simple Date Input
```html
<ccl-datefield 
  [value]="selectedDate"
  (onChange)="onDateChange($event)">
</ccl-datefield>
```

### With Date Range Validation
```html
<ccl-datefield 
  [value]="selectedDate"
  [minDate]="minDate"
  [maxDate]="maxDate"
  (onChange)="onDateChange($event)">
</ccl-datefield>
```

### With Custom Format
```html
<ccl-datefield 
  [value]="selectedDate"
  format="MM/dd/yyyy"
  (onChange)="onDateChange($event)">
</ccl-datefield>
```

### Disabled State
```html
<ccl-datefield 
  [value]="selectedDate"
  [disabled]="true"
  (onChange)="onDateChange($event)">
</ccl-datefield>
```

## Form Integration

The date field component implements `ControlValueAccessor` for seamless form integration:

```typescript
import { Component } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { DateFieldComponent } from '@Crystal-Code-Labs/ccl-ui-components';

@Component({
  selector: 'app-form-example',
  standalone: true,
  imports: [DateFieldComponent, ReactiveFormsModule],
  template: `
    <form [formGroup]="form">
      <ccl-datefield 
        formControlName="birthDate"
        [minDate]="minDate"
        [maxDate]="maxDate">
      </ccl-datefield>
    </form>
  `
})
export class FormExampleComponent {
  minDate = new Date(1900, 0, 1);
  maxDate = new Date();
  
  form = new FormGroup({
    birthDate: new FormControl<Date | null>(null)
  });
}
```

## Complete Example

```typescript
import { Component } from '@angular/core';
import { DateFieldComponent } from '@Crystal-Code-Labs/ccl-ui-components';

@Component({
  selector: 'app-date-example',
  standalone: true,
  imports: [DateFieldComponent],
  template: `
    <div class="date-container">
      <h2>Date Selection</h2>
      
      <div class="date-field-wrapper">
        <label for="start-date">Start Date:</label>
        <ccl-datefield 
          [value]="startDate"
          [minDate]="today"
          [maxDate]="maxDate"
          (onChange)="onStartDateChange($event)">
        </ccl-datefield>
      </div>
      
      <div class="date-field-wrapper">
        <label for="end-date">End Date:</label>
        <ccl-datefield 
          [value]="endDate"
          [minDate]="startDate || today"
          [maxDate]="maxDate"
          (onChange)="onEndDateChange($event)">
        </ccl-datefield>
      </div>
      
      <div class="selected-dates">
        <p>Selected Range: {{ getDateRange() }}</p>
      </div>
    </div>
  `,
  styles: [`
    .date-container {
      padding: 1rem;
    }
    
    .date-field-wrapper {
      margin-bottom: 1rem;
    }
    
    .date-field-wrapper label {
      display: block;
      margin-bottom: 0.5rem;
      font-weight: 500;
    }
    
    .selected-dates {
      margin-top: 1rem;
      padding: 1rem;
      background: var(--color-background-surface, #f8f9fa);
      border-radius: var(--radius-md, 6px);
    }
  `]
})
export class DateExampleComponent {
  today = new Date();
  maxDate = new Date(this.today.getFullYear() + 1, 11, 31);
  
  startDate: Date | null = null;
  endDate: Date | null = null;

  onStartDateChange(date: Date | null) {
    this.startDate = date;
    // Reset end date if it's before start date
    if (this.endDate && date && this.endDate < date) {
      this.endDate = null;
    }
  }

  onEndDateChange(date: Date | null) {
    this.endDate = date;
  }

  getDateRange(): string {
    if (!this.startDate && !this.endDate) {
      return 'No dates selected';
    }
    
    if (this.startDate && !this.endDate) {
      return `From ${this.startDate.toLocaleDateString()}`;
    }
    
    if (!this.startDate && this.endDate) {
      return `Until ${this.endDate.toLocaleDateString()}`;
    }
    
    return `${this.startDate!.toLocaleDateString()} - ${this.endDate!.toLocaleDateString()}`;
  }
}
```

## Features

### Date Validation
- **Range Validation**: Respects `minDate` and `maxDate` constraints
- **Input Validation**: Validates user input and shows error messages
- **Format Validation**: Handles various date input formats

### Calendar Integration
- **Calendar Toggle**: Click calendar icon to open/close calendar
- **Today Button**: Quick selection of current date
- **Keyboard Navigation**: Full keyboard support

### Accessibility
- **ARIA Labels**: Proper labeling for screen readers
- **Role Attributes**: Correct roles for input and dialog elements
- **Keyboard Support**: Tab navigation and keyboard interactions

### Form Integration
- **ControlValueAccessor**: Full reactive forms support
- **Validation States**: Integrates with Angular form validation
- **Disabled State**: Proper disabled state handling

## Styling

The date field component uses design tokens for consistent styling:

```css
.ccl-datefield {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.ccl-datefield__wrapper {
  display: flex;
  align-items: center;
  border: 1px solid var(--color-border, #ccc);
  border-radius: var(--radius-md, 4px);
  background: var(--color-background, #fff);
  padding: 0 var(--spacing-sm);
}

.ccl-datefield__input {
  flex: 1;
  border: none;
  outline: none;
  font-size: var(--font-size-md, 14px);
  padding: var(--spacing-sm);
  background: transparent;
}
```

## Theming

Customize the date field appearance with CSS variables:

```css
:root, :host {
  --color-border: #e9ecef;
  --color-background: #ffffff;
  --color-error: #dc3545;
  --color-icon: #6c757d;
  --radius-md: 8px;
  --spacing-sm: 0.75rem;
  --font-size-md: 16px;
}
```

## Testing

The date field component includes comprehensive test coverage:

```typescript
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DateFieldComponent } from '@Crystal-Code-Labs/ccl-ui-components';

describe('DateFieldComponent', () => {
  let fixture: ComponentFixture<DateFieldComponent>;
  let component: DateFieldComponent;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [DateFieldComponent],
    }).compileComponents();

    fixture = TestBed.createComponent(DateFieldComponent);
    component = fixture.componentInstance;
  });

  it('should select date and emit onChange', () => {
    spyOn(component.onChange, 'emit');
    const testDate = new Date(2025, 8, 26);
    
    component.selectDate(testDate);
    
    expect(component.value).toEqual(testDate);
    expect(component.onChange.emit).toHaveBeenCalledWith(testDate);
  });

  it('should not select date outside min/max range', () => {
    const minDate = new Date(2025, 0, 1);
    const maxDate = new Date(2025, 11, 31);
    const outOfRangeDate = new Date(2024, 11, 31);
    
    component.minDate = minDate;
    component.maxDate = maxDate;
    
    component.selectDate(outOfRangeDate);
    
    expect(component.value).toBeNull();
  });

  it('should show error for invalid input', () => {
    const input = fixture.nativeElement.querySelector('input');
    input.value = '32/13/2025';
    input.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    
    expect(component.errorMessage).toBe('Invalid date');
    expect(component.value).toBeNull();
  });
});
```

## Integration with Other Components

### With DataTable
```html
<div class="filter-section">
  <ccl-datefield 
    [value]="filterDate"
    (onChange)="filterByDate($event)">
  </ccl-datefield>
  
  <ccl-datatable
    [columns]="columns"
    [rows]="filteredRows">
  </ccl-datatable>
</div>
```

### With Searchbar
```html
<div class="search-and-filter">
  <ccl-searchbar 
    placeholder="Search events..."
    (onSearch)="searchEvents($event)">
  </ccl-searchbar>
  
  <ccl-datefield 
    [value]="eventDate"
    (onChange)="filterByDate($event)">
  </ccl-datefield>
</div>
```

## Browser Support

The date field component uses modern JavaScript features:
- **Intl.DateTimeFormat**: For locale-aware date formatting
- **Date API**: For date parsing and validation
- **Modern CSS**: Flexbox and CSS custom properties

For older browsers, consider polyfills for:
- `Intl.DateTimeFormat` (if needed for specific locales)
- CSS custom properties (if targeting very old browsers)
