# Events

## Overview

The Events feature provides a mechanism to respond to user interactions and internal state changes of the chip control. Developers can subscribe to events such as chip clicks, close button clicks, selection changes, and state changes to execute custom logic. The available events are:

| Event Name       | Description                                                                                                | Triggered When                                                   |
| ---------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| ChipClicked      | Occurs when the main body of the chip is clicked, excluding the close button area.                         | The user clicks on the chip (not on the close button).           |
| CloseClicked     | Occurs when the close (X) button on the chip is clicked.                                                   | The user clicks on the close button.                             |
| SelectionChanged | Occurs when the chip's selection state changes.                                                            | The chip is selected or deselected.                              |
| StateChanged     | Occurs when any key appearance or state property changes (such as color, selection, or animation toggles). | A monitored property (e.g., IsSelected, AccentColor) is updated. |

### Key Points

| Aspect                    | Details                                                                                                               |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Customizable Interactions | Each event allows developers to implement custom behaviors based on user actions and state updates.                   |
| Decoupled Logic           | Events facilitate a decoupled design, where UI updates and business logic can respond independently to state changes. |
| Comprehensive Feedback    | The availability of multiple events (clicks, selection, state changes) provides comprehensive control feedback.       |

### Best Practices

| Practice                          | Recommendation                                                                                                                         |
| --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| Use Specific Event Handlers       | Handle ChipClicked and CloseClicked events separately to clearly differentiate between standard chip interactions and removal actions. |
| Centralize State Management       | Use the SelectionChanged event to update other UI elements or application logic in response to the chip’s selection state.             |
| Leverage StateChanged for Logging | Utilize the StateChanged event for debugging and logging property changes, ensuring that any unexpected state transitions are caught.  |

### Common Pitfalls

| Pitfall                      | Explanation                                                                                                                                                                                |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Overcomplicating Event Logic | Avoid embedding complex business logic directly within event handlers; instead, delegate to dedicated methods or services.                                                                 |
| Ignoring Event Order         | Be aware that multiple events may fire in quick succession (e.g., a click might trigger both ChipClicked and SelectionChanged), which can lead to race conditions if not managed properly. |
| Unsubscribing When Disposing | Ensure that event handlers are properly unsubscribed when the control is disposed to avoid memory leaks.                                                                                   |

### Usage Scenarios

| Scenario                       | Description                                                                                                                 |
| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------- |
| User Interaction Feedback      | Use ChipClicked to provide immediate feedback, such as displaying details or navigating to a new view.                      |
| Dynamic Content Removal        | Implement CloseClicked to allow users to remove chips dynamically from a list or filter set.                                |
| Synchronized Selection Updates | Use SelectionChanged to trigger updates across multiple components (e.g., updating a summary view when a chip is selected). |
| Debugging and Theming          | Leverage StateChanged to monitor and log property changes for debugging or dynamic theming adjustments.                     |

### Real Life Usage Scenarios

| Scenario                      | Real Life Example                                                                                                                                                |
| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Email Client Label Management | In an email client, clicking a chip may filter emails (ChipClicked), while clicking the close button removes the label (CloseClicked).                           |
| E-Commerce Filter Options     | Selecting a chip representing a product filter (SelectionChanged) updates the displayed product list, while state logging (StateChanged) helps track UI changes. |
| Dashboard Widget Interaction  | In a customizable dashboard, clicking a chip can toggle the visibility of a widget, and state changes can be logged for performance monitoring.                  |

### Troubleshooting Tips

| Tip                        | Recommendation                                                                                                                   |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Verify Event Subscriptions | Ensure that all necessary events (ChipClicked, CloseClicked, SelectionChanged, StateChanged) are subscribed to in your code.     |
| Manage Event Handler Scope | Use lambda expressions or separate methods judiciously to maintain clarity and avoid tightly coupled code within event handlers. |
| Log Event Triggers         | Implement logging within event handlers during development to trace the order and frequency of events, aiding in debugging.      |

### Code Examples

#### Basic Event Handling

The following example demonstrates how to subscribe to the primary events of the chip control and handle them appropriately:

```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
using SiticoneNetFrameworkUI;

public class BasicEventsForm : Form
{
    private SiticoneChip chip;

    public BasicEventsForm()
    {
        this.Text = "Chip Events Demo";
        this.Size = new Size(400, 300);
        InitializeChip();
    }

    private void InitializeChip()
    {
        chip = new SiticoneChip
        {
            Text = "Interactive Chip",
            Location = new Point(50, 50),
            Size = new Size(250, 40),
            // Enable interaction properties for demonstration
            EnableSelection = true,
            ShowCloseButton = true,
            AutoDisposeOnClose = true
        };

        // Subscribe to events
        chip.ChipClicked += Chip_ChipClicked;
        chip.CloseClicked += Chip_CloseClicked;
        chip.SelectionChanged += Chip_SelectionChanged;
        chip.StateChanged += Chip_StateChanged;

        this.Controls.Add(chip);
    }

    private void Chip_ChipClicked(object sender, EventArgs e)
    {
        MessageBox.Show("ChipClicked event fired: Chip body was clicked.");
    }

    private void Chip_CloseClicked(object sender, EventArgs e)
    {
        MessageBox.Show("CloseClicked event fired: Close button was clicked.");
    }

    private void Chip_SelectionChanged(object sender, EventArgs e)
    {
        var currentChip = sender as SiticoneChip;
        MessageBox.Show($"{currentChip.Text} selection state changed to: {currentChip.IsSelected}");
    }

    private void Chip_StateChanged(object sender, ChipStateChangedEventArgs e)
    {
        // Log the property change for debugging purposes
        Console.WriteLine($"StateChanged: Property '{e.PropertyName}' changed to '{e.NewValue}'");
    }

    [STAThread]
    public static void Main()
    {
        Application.Run(new BasicEventsForm());
    }
}
```

#### Advanced Event-Driven Interaction

This example shows a scenario where multiple chips are used, and events are handled to update a shared UI element (e.g., a status label) dynamically based on chip interactions:

```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
using SiticoneNetFrameworkUI;

public class AdvancedEventsForm : Form
{
    private Label statusLabel;
    private SiticoneChip chip1;
    private SiticoneChip chip2;

    public AdvancedEventsForm()
    {
        this.Text = "Advanced Chip Events Demo";
        this.Size = new Size(500, 350);
        InitializeComponents();
    }

    private void InitializeComponents()
    {
        // Create a status label to display event messages
        statusLabel = new Label
        {
            Text = "Status: Waiting for interaction...",
            Location = new Point(50, 20),
            Size = new Size(400, 30)
        };

        // Initialize first chip
        chip1 = new SiticoneChip
        {
            Text = "Chip One",
            Location = new Point(50, 70),
            Size = new Size(200, 40),
            EnableSelection = true,
            ShowCloseButton = true
        };

        // Initialize second chip
        chip2 = new SiticoneChip
        {
            Text = "Chip Two",
            Location = new Point(50, 130),
            Size = new Size(200, 40),
            EnableSelection = true,
            ShowCloseButton = true
        };

        // Subscribe to events for both chips
        chip1.ChipClicked += (s, e) => UpdateStatus("Chip One clicked.");
        chip2.ChipClicked += (s, e) => UpdateStatus("Chip Two clicked.");

        chip1.SelectionChanged += (s, e) => UpdateStatus($"Chip One selection changed: {chip1.IsSelected}");
        chip2.SelectionChanged += (s, e) => UpdateStatus($"Chip Two selection changed: {chip2.IsSelected}");

        chip1.CloseClicked += (s, e) => UpdateStatus("Chip One close button clicked.");
        chip2.CloseClicked += (s, e) => UpdateStatus("Chip Two close button clicked.");

        // Add controls to the form
        this.Controls.Add(statusLabel);
        this.Controls.Add(chip1);
        this.Controls.Add(chip2);
    }

    private void UpdateStatus(string message)
    {
        statusLabel.Text = $"Status: {message}";
    }

    [STAThread]
    public static void Main()
    {
        Application.Run(new AdvancedEventsForm());
    }
}
```

### Review

| Aspect                 | Review Comments                                                                                                                     |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Responsive Interaction | The event-based design ensures that user interactions with the chip are immediately recognized and acted upon.                      |
| Flexibility in Logic   | Multiple events allow developers to separate concerns and handle different aspects of the chip's behavior independently.            |
| Debugging and Logging  | The StateChanged event provides a useful tool for tracking property changes, which is valuable for debugging and theme adjustments. |

### Summary

The Events feature of the SiticoneChip control provides a robust and flexible framework for handling user interactions and internal state changes. By subscribing to events like ChipClicked, CloseClicked, SelectionChanged, and StateChanged, developers can integrate custom logic and feedback mechanisms into their applications, ensuring a responsive and intuitive user experience.

### Additional Useful Sections

#### Integration Checklist

| Checklist Item               | Status/Recommendation                                                                                     |
| ---------------------------- | --------------------------------------------------------------------------------------------------------- |
| Confirm Event Subscriptions  | Ensure that all desired events are correctly subscribed in your code.                                     |
| Validate Event Handler Logic | Test each event handler independently to confirm that the correct logic is executed for each interaction. |
| Unsubscribe Appropriately    | Remove event subscriptions when the chip is disposed to prevent memory leaks.                             |

#### Demo Tips

<table><thead><tr><th width="289">Tip</th><th>Description</th></tr></thead><tbody><tr><td>Interactive Logging</td><td>Use a logging mechanism (e.g., console output or a UI label) to display event triggers and validate behavior during development.</td></tr><tr><td>Simulate Complex Interactions</td><td>Create scenarios where multiple chips interact (e.g., grouping or exclusive selection) to demonstrate advanced event handling.</td></tr><tr><td>Emphasize State Changes</td><td>Leverage the StateChanged event to showcase dynamic UI updates and theming changes in real time.</td></tr></tbody></table>

This comprehensive documentation should assist developers in effectively integrating and managing the Events feature of the SiticoneChip control, ensuring that the chip responds accurately to user actions and state changes throughout the application.
