use std::collections::{HashMap, HashSet};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Health status level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum HealthStatus {
    Healthy,
    Warning,
    Critical,
    Unknown,
}

/// System status information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SystemStatus {
    pub level: HealthStatus,
    pub is_healthy: bool,
    pub uptime_hours: u32,
    pub api_status: String,
    pub database_status: String,
    pub last_check: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UserRole {
    Admin,
    User,
    ReadOnly,
    Security,
    Operator,
    Viewer,
}

impl UserRole {
    pub fn can_edit_dashboard(&self) -> bool {
        matches!(self, UserRole::Admin | UserRole::User | UserRole::Operator)
    }

    pub fn can_export(&self) -> bool {
        !matches!(self, UserRole::ReadOnly | UserRole::Viewer)
    }

    pub fn can_access_security_metrics(&self) -> bool {
        matches!(self, UserRole::Admin | UserRole::Security)
    }

    pub fn can_manage_system(&self) -> bool {
        matches!(self, UserRole::Admin | UserRole::Operator)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WidgetConfig {
    pub widget_type: String,
    pub position: GridPosition,
    pub size: GridSize,
    pub enabled: bool,
    pub permissions: Vec<UserRole>,
    pub config: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GridPosition {
    pub x: u32,
    pub y: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GridSize {
    pub width: u32,
    pub height: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardTemplate {
    pub id: String,
    pub name: String,
    pub description: String,
    pub category: String,
    pub target_roles: Vec<UserRole>,
    pub widgets: Vec<WidgetConfig>,
    pub layout_config: LayoutConfig,
    pub theme_preferences: Option<ThemePreferences>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LayoutConfig {
    pub grid_columns: u32,
    pub grid_rows: u32,
    pub compact_mode: bool,
    pub auto_resize: bool,
    pub mobile_layout: Option<MobileLayoutConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MobileLayoutConfig {
    pub stack_vertically: bool,
    pub hide_widgets: Vec<String>,
    pub resize_widgets: HashMap<String, GridSize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThemePreferences {
    pub default_theme: String,
    pub custom_colors: HashMap<String, String>,
    pub font_size: Option<f32>,
}

impl DashboardTemplate {
    pub fn new(
        id: String,
        name: String,
        description: String,
        category: String,
        target_roles: Vec<UserRole>,
    ) -> Self {
        Self {
            id,
            name,
            description,
            category,
            target_roles,
            widgets: Vec::new(),
            layout_config: LayoutConfig::default(),
            theme_preferences: None,
        }
    }

    pub fn is_accessible_by_role(&self, role: &UserRole) -> bool {
        self.target_roles.contains(role)
    }

    pub fn get_widgets_for_role(&self, role: &UserRole) -> Vec<WidgetConfig> {
        self.widgets
            .iter()
            .filter(|widget| {
                widget.enabled
                    && (widget.permissions.is_empty() || widget.permissions.contains(role))
            })
            .cloned()
            .collect()
    }

    pub fn add_widget(&mut self, widget: WidgetConfig) {
        self.widgets.push(widget);
    }

    pub fn remove_widget(&mut self, widget_id: &str) {
        self.widgets.retain(|w| w.widget_type != widget_id);
    }
}

impl Default for LayoutConfig {
    fn default() -> Self {
        Self {
            grid_columns: 12,
            grid_rows: 8,
            compact_mode: false,
            auto_resize: true,
            mobile_layout: Some(MobileLayoutConfig::default()),
        }
    }
}

impl Default for MobileLayoutConfig {
    fn default() -> Self {
        Self {
            stack_vertically: true,
            hide_widgets: vec!["large_chart".to_string(), "detailed_table".to_string()],
            resize_widgets: HashMap::new(),
        }
    }
}

// Pre-built dashboard templates
pub fn get_default_templates() -> Vec<DashboardTemplate> {
    vec![
        create_admin_overview_template(),
        create_security_dashboard_template(),
        create_operations_dashboard_template(),
        create_analytics_dashboard_template(),
        create_readonly_dashboard_template(),
        create_user_dashboard_template(),
    ]
}

fn create_admin_overview_template() -> DashboardTemplate {
    let mut template = DashboardTemplate::new(
        "admin_overview".to_string(),
        "Admin Overview".to_string(),
        "Comprehensive dashboard for system administrators".to_string(),
        "Administrative".to_string(),
        vec![UserRole::Admin],
    );

    template.add_widget(WidgetConfig {
        widget_type: "system_health".to_string(),
        position: GridPosition { x: 0, y: 0 },
        size: GridSize {
            width: 6,
            height: 2,
        },
        enabled: true,
        permissions: vec![UserRole::Admin],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "workflow_metrics".to_string(),
        position: GridPosition { x: 6, y: 0 },
        size: GridSize {
            width: 6,
            height: 2,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Operator],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "security_alerts".to_string(),
        position: GridPosition { x: 0, y: 2 },
        size: GridSize {
            width: 4,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Security],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "resource_usage".to_string(),
        position: GridPosition { x: 4, y: 2 },
        size: GridSize {
            width: 4,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Operator],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "activity_feed".to_string(),
        position: GridPosition { x: 8, y: 2 },
        size: GridSize {
            width: 4,
            height: 6,
        },
        enabled: true,
        permissions: vec![UserRole::Admin],
        config: HashMap::new(),
    });

    template
}

fn create_security_dashboard_template() -> DashboardTemplate {
    let mut template = DashboardTemplate::new(
        "security_dashboard".to_string(),
        "Security Dashboard".to_string(),
        "Security-focused monitoring and alerts".to_string(),
        "Security".to_string(),
        vec![UserRole::Admin, UserRole::Security],
    );

    template.add_widget(WidgetConfig {
        widget_type: "auth_attempts".to_string(),
        position: GridPosition { x: 0, y: 0 },
        size: GridSize {
            width: 6,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Security],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "policy_violations".to_string(),
        position: GridPosition { x: 6, y: 0 },
        size: GridSize {
            width: 6,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Security],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "threat_detection".to_string(),
        position: GridPosition { x: 0, y: 3 },
        size: GridSize {
            width: 8,
            height: 2,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Security],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "security_events".to_string(),
        position: GridPosition { x: 8, y: 3 },
        size: GridSize {
            width: 4,
            height: 5,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Security],
        config: HashMap::new(),
    });

    template
}

fn create_operations_dashboard_template() -> DashboardTemplate {
    let mut template = DashboardTemplate::new(
        "operations_dashboard".to_string(),
        "Operations Dashboard".to_string(),
        "Operational monitoring and system management".to_string(),
        "Operations".to_string(),
        vec![UserRole::Admin, UserRole::Operator],
    );

    template.add_widget(WidgetConfig {
        widget_type: "system_health".to_string(),
        position: GridPosition { x: 0, y: 0 },
        size: GridSize {
            width: 4,
            height: 2,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Operator],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "resource_usage".to_string(),
        position: GridPosition { x: 4, y: 0 },
        size: GridSize {
            width: 8,
            height: 4,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Operator],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "workflow_metrics".to_string(),
        position: GridPosition { x: 0, y: 2 },
        size: GridSize {
            width: 4,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Operator],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "server_status".to_string(),
        position: GridPosition { x: 0, y: 5 },
        size: GridSize {
            width: 12,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::Operator],
        config: HashMap::new(),
    });

    template
}

fn create_analytics_dashboard_template() -> DashboardTemplate {
    let mut template = DashboardTemplate::new(
        "analytics_dashboard".to_string(),
        "Analytics Dashboard".to_string(),
        "Data analytics and reporting interface".to_string(),
        "Analytics".to_string(),
        vec![UserRole::Admin, UserRole::User],
    );

    template.add_widget(WidgetConfig {
        widget_type: "workflow_trends".to_string(),
        position: GridPosition { x: 0, y: 0 },
        size: GridSize {
            width: 8,
            height: 4,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::User],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "performance_metrics".to_string(),
        position: GridPosition { x: 8, y: 0 },
        size: GridSize {
            width: 4,
            height: 4,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::User],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "usage_statistics".to_string(),
        position: GridPosition { x: 0, y: 4 },
        size: GridSize {
            width: 6,
            height: 4,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::User],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "data_export".to_string(),
        position: GridPosition { x: 6, y: 4 },
        size: GridSize {
            width: 6,
            height: 2,
        },
        enabled: true,
        permissions: vec![UserRole::Admin, UserRole::User],
        config: HashMap::new(),
    });

    template
}

fn create_readonly_dashboard_template() -> DashboardTemplate {
    let mut template = DashboardTemplate::new(
        "readonly_dashboard".to_string(),
        "Read-Only Dashboard".to_string(),
        "Limited view dashboard for read-only users".to_string(),
        "Basic".to_string(),
        vec![UserRole::ReadOnly, UserRole::Viewer],
    );

    template.add_widget(WidgetConfig {
        widget_type: "system_status".to_string(),
        position: GridPosition { x: 0, y: 0 },
        size: GridSize {
            width: 6,
            height: 3,
        },
        enabled: true,
        permissions: vec![
            UserRole::ReadOnly,
            UserRole::Viewer,
            UserRole::User,
            UserRole::Admin,
        ],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "basic_metrics".to_string(),
        position: GridPosition { x: 6, y: 0 },
        size: GridSize {
            width: 6,
            height: 3,
        },
        enabled: true,
        permissions: vec![
            UserRole::ReadOnly,
            UserRole::Viewer,
            UserRole::User,
            UserRole::Admin,
        ],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "public_announcements".to_string(),
        position: GridPosition { x: 0, y: 3 },
        size: GridSize {
            width: 12,
            height: 2,
        },
        enabled: true,
        permissions: vec![
            UserRole::ReadOnly,
            UserRole::Viewer,
            UserRole::User,
            UserRole::Admin,
        ],
        config: HashMap::new(),
    });

    template
}

fn create_user_dashboard_template() -> DashboardTemplate {
    let mut template = DashboardTemplate::new(
        "user_dashboard".to_string(),
        "User Dashboard".to_string(),
        "Standard dashboard for regular users".to_string(),
        "User".to_string(),
        vec![UserRole::User],
    );

    template.add_widget(WidgetConfig {
        widget_type: "personal_metrics".to_string(),
        position: GridPosition { x: 0, y: 0 },
        size: GridSize {
            width: 6,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::User, UserRole::Admin],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "workflow_status".to_string(),
        position: GridPosition { x: 6, y: 0 },
        size: GridSize {
            width: 6,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::User, UserRole::Admin],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "notifications".to_string(),
        position: GridPosition { x: 0, y: 3 },
        size: GridSize {
            width: 4,
            height: 3,
        },
        enabled: true,
        permissions: vec![UserRole::User, UserRole::Admin],
        config: HashMap::new(),
    });

    template.add_widget(WidgetConfig {
        widget_type: "quick_actions".to_string(),
        position: GridPosition { x: 4, y: 3 },
        size: GridSize {
            width: 8,
            height: 2,
        },
        enabled: true,
        permissions: vec![UserRole::User, UserRole::Admin],
        config: HashMap::new(),
    });

    template
}

// Template management utilities
pub struct TemplateManager;

impl TemplateManager {
    pub fn get_templates_for_role(role: &UserRole) -> Vec<DashboardTemplate> {
        get_default_templates()
            .into_iter()
            .filter(|template| template.is_accessible_by_role(role))
            .collect()
    }

    pub fn get_template_by_id(id: &str) -> Option<DashboardTemplate> {
        get_default_templates()
            .into_iter()
            .find(|template| template.id == id)
    }

    pub fn create_custom_template(
        base_template_id: &str,
        role: &UserRole,
        customizations: HashMap<String, serde_json::Value>,
    ) -> Option<DashboardTemplate> {
        let mut template = Self::get_template_by_id(base_template_id)?;

        // Apply customizations
        if let Some(name) = customizations.get("name").and_then(|v| v.as_str()) {
            template.name = format!("{} (Custom)", name);
            template.id = format!("{}_custom_{}", template.id, chrono::Utc::now().timestamp());
        }

        // Filter widgets based on role permissions
        template.widgets = template.get_widgets_for_role(role);

        Some(template)
    }

    pub fn validate_template(template: &DashboardTemplate) -> Result<(), String> {
        if template.name.is_empty() {
            return Err("Template name cannot be empty".to_string());
        }

        if template.widgets.is_empty() {
            return Err("Template must have at least one widget".to_string());
        }

        // Validate grid positions don't overlap
        for (i, widget) in template.widgets.iter().enumerate() {
            for (j, other_widget) in template.widgets.iter().enumerate() {
                if i != j && Self::widgets_overlap(widget, other_widget) {
                    return Err(format!(
                        "Widgets '{}' and '{}' overlap",
                        widget.widget_type, other_widget.widget_type
                    ));
                }
            }
        }

        Ok(())
    }

    fn widgets_overlap(widget1: &WidgetConfig, widget2: &WidgetConfig) -> bool {
        let w1_end_x = widget1.position.x + widget1.size.width;
        let w1_end_y = widget1.position.y + widget1.size.height;
        let w2_end_x = widget2.position.x + widget2.size.width;
        let w2_end_y = widget2.position.y + widget2.size.height;

        !(widget1.position.x >= w2_end_x
            || w1_end_x <= widget2.position.x
            || widget1.position.y >= w2_end_y
            || w1_end_y <= widget2.position.y)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_user_role_permissions() {
        assert!(UserRole::Admin.can_edit_dashboard());
        assert!(UserRole::Admin.can_export());
        assert!(UserRole::Admin.can_access_security_metrics());
        assert!(UserRole::Admin.can_manage_system());

        assert!(!UserRole::ReadOnly.can_edit_dashboard());
        assert!(!UserRole::ReadOnly.can_export());
        assert!(!UserRole::ReadOnly.can_access_security_metrics());
        assert!(!UserRole::ReadOnly.can_manage_system());
    }

    #[test]
    fn test_template_role_filtering() {
        let templates = TemplateManager::get_templates_for_role(&UserRole::Admin);
        assert!(!templates.is_empty());

        let readonly_templates = TemplateManager::get_templates_for_role(&UserRole::ReadOnly);
        assert!(readonly_templates.len() <= templates.len());
    }

    #[test]
    fn test_widget_overlap_detection() {
        let widget1 = WidgetConfig {
            widget_type: "test1".to_string(),
            position: GridPosition { x: 0, y: 0 },
            size: GridSize {
                width: 4,
                height: 2,
            },
            enabled: true,
            permissions: vec![],
            config: HashMap::new(),
        };

        let widget2 = WidgetConfig {
            widget_type: "test2".to_string(),
            position: GridPosition { x: 2, y: 1 },
            size: GridSize {
                width: 4,
                height: 2,
            },
            enabled: true,
            permissions: vec![],
            config: HashMap::new(),
        };

        assert!(TemplateManager::widgets_overlap(&widget1, &widget2));

        let widget3 = WidgetConfig {
            widget_type: "test3".to_string(),
            position: GridPosition { x: 4, y: 0 },
            size: GridSize {
                width: 4,
                height: 2,
            },
            enabled: true,
            permissions: vec![],
            config: HashMap::new(),
        };

        assert!(!TemplateManager::widgets_overlap(&widget1, &widget3));
    }
}

// ============================================================================
// User Management Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct User {
    pub id: String,
    pub username: String,
    pub email: String,
    pub display_name: String,
    pub first_name: String,
    pub last_name: String,
    pub phone: Option<String>,
    pub avatar_url: Option<String>,
    pub status: UserStatus,
    pub roles: Vec<UserRole>,
    pub groups: Vec<String>, // Group IDs
    pub permissions: Vec<Permission>,
    pub department: Option<String>,
    pub manager_id: Option<String>,
    pub employee_id: Option<String>,
    pub cost_center: Option<String>,
    pub location: Option<String>,
    pub timezone: String,
    pub language: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub last_login: Option<DateTime<Utc>>,
    pub last_activity: Option<DateTime<Utc>>,
    pub password_last_changed: Option<DateTime<Utc>>,
    pub must_change_password: bool,
    pub failed_login_attempts: u32,
    pub locked_until: Option<DateTime<Utc>>,
    pub two_factor_enabled: bool,
    pub backup_codes: Vec<String>,
    pub security_settings: SecuritySettings,
    pub preferences: UserPreferences,
    pub metadata: HashMap<String, serde_json::Value>,
    pub tags: Vec<String>,
    pub notes: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum UserStatus {
    Active,
    Inactive,
    Suspended,
    PendingActivation,
    PendingDeactivation,
    Locked,
    Expired,
    Terminated,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Permission {
    pub id: String,
    pub resource: String,
    pub action: String,
    pub scope: PermissionScope,
    pub conditions: Vec<PermissionCondition>,
    pub granted_at: DateTime<Utc>,
    pub granted_by: String,
    pub expires_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PermissionScope {
    Global,
    Organization(String),
    Department(String),
    Team(String),
    Project(String),
    Resource(String),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PermissionCondition {
    pub field: String,
    pub operator: ConditionOperator,
    pub value: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ConditionOperator {
    Equals,
    NotEquals,
    GreaterThan,
    LessThan,
    Contains,
    StartsWith,
    EndsWith,
    In,
    NotIn,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecuritySettings {
    pub require_mfa: bool,
    pub allowed_mfa_methods: Vec<MfaMethod>,
    pub session_timeout: u32, // minutes
    pub max_sessions: u32,
    pub ip_whitelist: Vec<String>,
    pub allowed_countries: Vec<String>,
    pub require_device_trust: bool,
    pub password_policy: PasswordPolicy,
    pub login_notifications: bool,
    pub security_questions: Vec<SecurityQuestion>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MfaMethod {
    Totp,
    Sms,
    Email,
    WebAuthn,
    HardwareToken,
    BackupCodes,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PasswordPolicy {
    pub min_length: u32,
    pub require_uppercase: bool,
    pub require_lowercase: bool,
    pub require_numbers: bool,
    pub require_symbols: bool,
    pub prevent_reuse: u32,   // Number of previous passwords to check
    pub max_age: Option<u32>, // Days until password expires
    pub complexity_score: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecurityQuestion {
    pub question: String,
    pub answer_hash: String,
    pub created_at: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UserPreferences {
    pub theme: String,
    pub dashboard_layout: String,
    pub notifications: NotificationPreferences,
    pub locale: String,
    pub date_format: String,
    pub time_format: String,
    pub timezone_display: String,
    pub accessibility: AccessibilitySettings,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NotificationPreferences {
    pub email_notifications: bool,
    pub sms_notifications: bool,
    pub push_notifications: bool,
    pub security_alerts: bool,
    pub system_updates: bool,
    pub workflow_updates: bool,
    pub digest_frequency: DigestFrequency,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DigestFrequency {
    Never,
    Daily,
    Weekly,
    Monthly,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessibilitySettings {
    pub high_contrast: bool,
    pub large_text: bool,
    pub screen_reader: bool,
    pub keyboard_navigation: bool,
    pub reduced_motion: bool,
}

// ============================================================================
// Group Management Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Group {
    pub id: String,
    pub name: String,
    pub description: String,
    pub group_type: GroupType,
    pub parent_id: Option<String>,
    pub children: Vec<String>, // Child group IDs
    pub members: Vec<String>,  // User IDs
    pub roles: Vec<UserRole>,
    pub permissions: Vec<Permission>,
    pub metadata: HashMap<String, serde_json::Value>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub created_by: String,
    pub managed_by: Vec<String>, // User IDs who can manage this group
    pub auto_assignment_rules: Vec<AutoAssignmentRule>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum GroupType {
    Department,
    Team,
    Project,
    Role,
    Security,
    Temporary,
    External,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AutoAssignmentRule {
    pub condition: GroupAssignmentCondition,
    pub action: GroupAssignmentAction,
    pub priority: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum GroupAssignmentCondition {
    UserAttribute { field: String, value: String },
    Department(String),
    JobTitle(String),
    Location(String),
    Domain(String), // Email domain
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum GroupAssignmentAction {
    AddToGroup,
    RemoveFromGroup,
    AssignRole,
    RemoveRole,
}

// ============================================================================
// Role Management Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoleDefinition {
    pub id: String,
    pub name: String,
    pub description: String,
    pub role_type: RoleType,
    pub parent_roles: Vec<String>, // Inherited roles
    pub child_roles: Vec<String>,  // Roles that inherit from this
    pub permissions: Vec<Permission>,
    pub constraints: Vec<RoleConstraint>,
    pub auto_assignment: bool,
    pub assignment_conditions: Vec<RoleAssignmentCondition>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub created_by: String,
    pub approval_required: bool,
    pub approvers: Vec<String>, // User IDs
    pub max_assignments: Option<u32>,
    pub risk_level: RiskLevel,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RoleType {
    System,
    Business,
    Technical,
    Security,
    Compliance,
    Temporary,
    Emergency,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RiskLevel {
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoleConstraint {
    pub constraint_type: ConstraintType,
    pub value: serde_json::Value,
    pub error_message: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ConstraintType {
    MutuallyExclusive,
    RequiredCombination,
    MaxConcurrent,
    TimeBasedAccess,
    LocationRestricted,
    DepartmentRestricted,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RoleAssignmentCondition {
    pub field: String,
    pub operator: ConditionOperator,
    pub value: serde_json::Value,
    pub weight: f32,
}

// ============================================================================
// Access Review Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessReviewCampaign {
    pub id: String,
    pub name: String,
    pub description: String,
    pub campaign_type: CampaignType,
    pub status: CampaignStatus,
    pub scope: ReviewScope,
    pub created_by: String,
    pub reviewers: Vec<String>, // User IDs
    pub escalation_reviewers: Vec<String>,
    pub start_date: DateTime<Utc>,
    pub end_date: DateTime<Utc>,
    pub reminder_schedule: Vec<DateTime<Utc>>,
    pub auto_approve_unchanged: bool,
    pub require_justification: bool,
    pub completion_threshold: f32, // Percentage required for completion
    pub review_items: Vec<AccessReviewItem>,
    pub statistics: ReviewStatistics,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CampaignType {
    UserAccess,
    RoleAccess,
    GroupMembership,
    PermissionAudit,
    ComplianceReview,
    Emergency,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CampaignStatus {
    Draft,
    Scheduled,
    InProgress,
    Completed,
    Cancelled,
    Overdue,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ReviewScope {
    AllUsers,
    Department(String),
    Role(String),
    Group(String),
    HighRiskUsers,
    InactiveUsers,
    CustomQuery(String),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessReviewItem {
    pub id: String,
    pub user_id: String,
    pub resource_type: String, // Role, Group, Permission
    pub resource_id: String,
    pub resource_name: String,
    pub current_access: AccessLevel,
    pub recommended_access: Option<AccessLevel>,
    pub risk_score: f32,
    pub last_used: Option<DateTime<Utc>>,
    pub business_justification: Option<String>,
    pub review_status: ReviewStatus,
    pub reviewer_id: Option<String>,
    pub review_decision: Option<ReviewDecision>,
    pub review_comments: Option<String>,
    pub reviewed_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AccessLevel {
    None,
    Read,
    Write,
    Admin,
    Full,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ReviewStatus {
    Pending,
    InReview,
    Completed,
    Escalated,
    Skipped,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ReviewDecision {
    Approve,
    Revoke,
    Modify,
    Escalate,
    NeedsMoreInfo,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ReviewStatistics {
    pub total_items: u32,
    pub completed_items: u32,
    pub approved_items: u32,
    pub revoked_items: u32,
    pub modified_items: u32,
    pub escalated_items: u32,
    pub avg_review_time: f32, // hours
    pub completion_percentage: f32,
}

// ============================================================================
// Delegation Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Delegation {
    pub id: String,
    pub delegator_id: String,
    pub delegate_id: String,
    pub delegation_type: DelegationType,
    pub scope: DelegationScope,
    pub permissions: Vec<Permission>,
    pub start_date: DateTime<Utc>,
    pub end_date: DateTime<Utc>,
    pub status: DelegationStatus,
    pub approval_required: bool,
    pub approved_by: Option<String>,
    pub approved_at: Option<DateTime<Utc>>,
    pub reason: String,
    pub emergency: bool,
    pub usage_tracking: Vec<DelegationUsage>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DelegationType {
    FullAccess,
    SpecificRoles,
    SpecificPermissions,
    ApprovalAuthority,
    SystemAccess,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DelegationScope {
    Global,
    Department(String),
    Team(String),
    Project(String),
    System(String),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DelegationStatus {
    Pending,
    Active,
    Expired,
    Revoked,
    Suspended,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DelegationUsage {
    pub timestamp: DateTime<Utc>,
    pub action: String,
    pub resource: String,
    pub ip_address: String,
    pub user_agent: String,
}

// ============================================================================
// Access Request Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessRequest {
    pub id: String,
    pub requester_id: String,
    pub requested_for: String, // User ID (could be self or others)
    pub request_type: RequestType,
    pub resource_type: String,
    pub resource_id: String,
    pub resource_name: String,
    pub access_level: AccessLevel,
    pub justification: String,
    pub business_need: String,
    pub duration: Option<u32>, // Days, if temporary
    pub emergency: bool,
    pub status: RequestStatus,
    pub approval_workflow: Vec<ApprovalStep>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub deadline: Option<DateTime<Utc>>,
    pub auto_revoke_date: Option<DateTime<Utc>>,
    pub risk_assessment: RiskAssessment,
    pub attachments: Vec<String>,
    pub comments: Vec<RequestComment>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RequestType {
    NewAccess,
    AdditionalAccess,
    AccessModification,
    AccessExtension,
    EmergencyAccess,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RequestStatus {
    Draft,
    Submitted,
    InReview,
    Approved,
    Rejected,
    Cancelled,
    Provisioned,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApprovalStep {
    pub id: String,
    pub step_number: u32,
    pub approver_id: String,
    pub approver_type: ApproverType,
    pub status: ApprovalStatus,
    pub required: bool,
    pub deadline: Option<DateTime<Utc>>,
    pub decision: Option<ApprovalDecision>,
    pub comments: Option<String>,
    pub decided_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ApproverType {
    User,
    Manager,
    ResourceOwner,
    SecurityTeam,
    ComplianceTeam,
    SystemAdministrator,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ApprovalStatus {
    Pending,
    Approved,
    Rejected,
    Delegated,
    Escalated,
    Expired,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ApprovalDecision {
    Approve,
    Reject,
    ApproveWithConditions,
    RequestMoreInfo,
    Delegate,
    Escalate,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RiskAssessment {
    pub overall_score: f32,
    pub factors: Vec<RiskFactor>,
    pub mitigation_required: bool,
    pub mitigation_measures: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RiskFactor {
    pub factor_type: String,
    pub score: f32,
    pub description: String,
    pub weight: f32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RequestComment {
    pub id: String,
    pub author_id: String,
    pub content: String,
    pub created_at: DateTime<Utc>,
    pub comment_type: CommentType,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CommentType {
    General,
    Approval,
    Rejection,
    Question,
    Answer,
    System,
}

// ============================================================================
// Identity Verification Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct IdentityVerification {
    pub id: String,
    pub user_id: String,
    pub verification_type: VerificationType,
    pub status: VerificationStatus,
    pub initiated_by: String,
    pub verification_methods: Vec<VerificationMethod>,
    pub required_documents: Vec<RequiredDocument>,
    pub submitted_documents: Vec<SubmittedDocument>,
    pub verification_data: HashMap<String, serde_json::Value>,
    pub expiry_date: Option<DateTime<Utc>>,
    pub created_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
    pub verified_by: Option<String>,
    pub notes: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum VerificationType {
    InitialVerification,
    PeriodicReview,
    AccessUpgrade,
    SecurityIncident,
    ComplianceAudit,
    EmergencyVerification,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum VerificationStatus {
    Pending,
    InProgress,
    DocumentsRequired,
    UnderReview,
    Verified,
    Failed,
    Expired,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VerificationMethod {
    pub method_type: VerificationMethodType,
    pub status: MethodStatus,
    pub completed_at: Option<DateTime<Utc>>,
    pub metadata: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum VerificationMethodType {
    Email,
    Phone,
    DocumentUpload,
    VideoCall,
    InPersonVerification,
    BackgroundCheck,
    ReferenceCheck,
    BiometricVerification,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MethodStatus {
    NotStarted,
    InProgress,
    Completed,
    Failed,
    Expired,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RequiredDocument {
    pub document_type: String,
    pub description: String,
    pub required: bool,
    pub accepted_formats: Vec<String>,
    pub max_size_mb: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubmittedDocument {
    pub id: String,
    pub document_type: String,
    pub filename: String,
    pub file_size: u32,
    pub mime_type: String,
    pub upload_url: String,
    pub status: DocumentStatus,
    pub reviewed_by: Option<String>,
    pub reviewed_at: Option<DateTime<Utc>>,
    pub comments: Option<String>,
    pub uploaded_at: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DocumentStatus {
    Uploaded,
    UnderReview,
    Approved,
    Rejected,
    RequiresResubmission,
}

// ============================================================================
// User Analytics Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UserAnalytics {
    pub user_id: String,
    pub period_start: DateTime<Utc>,
    pub period_end: DateTime<Utc>,
    pub activity_metrics: ActivityMetrics,
    pub access_patterns: AccessPatterns,
    pub security_metrics: SecurityMetrics,
    pub compliance_metrics: ComplianceMetrics,
    pub risk_indicators: RiskIndicators,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ActivityMetrics {
    pub total_sessions: u32,
    pub total_session_time: u32, // minutes
    pub avg_session_time: f32,
    pub login_count: u32,
    pub failed_login_attempts: u32,
    pub unique_ip_addresses: u32,
    pub unique_devices: u32,
    pub countries_accessed_from: Vec<String>,
    pub peak_activity_hours: Vec<u32>,
    pub last_activity: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessPatterns {
    pub most_accessed_resources: Vec<ResourceAccess>,
    pub access_by_time: HashMap<String, u32>, // Hour -> count
    pub access_by_day: HashMap<String, u32>,  // Day -> count
    pub unusual_access_detected: bool,
    pub access_anomalies: Vec<AccessAnomaly>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResourceAccess {
    pub resource_type: String,
    pub resource_id: String,
    pub resource_name: String,
    pub access_count: u32,
    pub last_accessed: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessAnomaly {
    pub anomaly_type: String,
    pub description: String,
    pub severity: AnomalySeverity,
    pub detected_at: DateTime<Utc>,
    pub details: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AnomalySeverity {
    Low,
    Medium,
    High,
    Critical,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecurityMetrics {
    pub mfa_usage_rate: f32,
    pub password_strength_score: f32,
    pub security_incidents: u32,
    pub policy_violations: u32,
    pub suspicious_activities: u32,
    pub device_trust_score: f32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ComplianceMetrics {
    pub access_reviews_completed: u32,
    pub certification_compliance: f32,
    pub training_completion: f32,
    pub policy_acknowledgments: u32,
    pub audit_findings: u32,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RiskIndicators {
    pub overall_risk_score: f32,
    pub risk_factors: Vec<RiskIndicator>,
    pub trend: RiskTrend,
    pub recommendations: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RiskIndicator {
    pub indicator_type: String,
    pub score: f32,
    pub weight: f32,
    pub description: String,
    pub last_updated: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RiskTrend {
    Improving,
    Stable,
    Deteriorating,
    Unknown,
}

// ============================================================================
// Bulk Operations Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BulkOperation {
    pub id: String,
    pub operation_type: BulkOperationType,
    pub status: BulkOperationStatus,
    pub total_items: u32,
    pub processed_items: u32,
    pub successful_items: u32,
    pub failed_items: u32,
    pub started_by: String,
    pub started_at: DateTime<Utc>,
    pub completed_at: Option<DateTime<Utc>>,
    pub progress_percentage: f32,
    pub results: Vec<BulkOperationResult>,
    pub errors: Vec<BulkOperationError>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BulkOperationType {
    UserImport,
    UserExport,
    RoleAssignment,
    PermissionGrant,
    GroupAssignment,
    AccountDeactivation,
    PasswordReset,
    NotificationSend,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum BulkOperationStatus {
    Queued,
    InProgress,
    Completed,
    Failed,
    Cancelled,
    PartiallyCompleted,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BulkOperationResult {
    pub item_id: String,
    pub status: ItemStatus,
    pub message: Option<String>,
    pub processed_at: DateTime<Utc>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ItemStatus {
    Success,
    Failed,
    Skipped,
    Warning,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BulkOperationError {
    pub error_type: String,
    pub message: String,
    pub item_id: Option<String>,
    pub line_number: Option<u32>,
}

// ============================================================================
// Import/Export Types
// ============================================================================

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImportTemplate {
    pub template_type: ImportTemplateType,
    pub fields: Vec<ImportField>,
    pub required_fields: Vec<String>,
    pub validation_rules: Vec<ValidationRule>,
    pub sample_data: Option<HashMap<String, serde_json::Value>>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ImportTemplateType {
    Users,
    Groups,
    Roles,
    Permissions,
    AccessRequests,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ImportField {
    pub name: String,
    pub data_type: FieldDataType,
    pub required: bool,
    pub description: String,
    pub example: Option<String>,
    pub validation_pattern: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FieldDataType {
    String,
    Number,
    Boolean,
    Date,
    Email,
    Array,
    Object,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ValidationRule {
    pub field: String,
    pub rule_type: ValidationRuleType,
    pub parameters: HashMap<String, serde_json::Value>,
    pub error_message: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ValidationRuleType {
    Required,
    MinLength,
    MaxLength,
    Pattern,
    UniqueValue,
    ValidEmail,
    ValidDate,
    CustomFunction,
}

// Implementations for User
impl User {
    pub fn new(username: String, email: String) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            username,
            email,
            display_name: String::new(),
            first_name: String::new(),
            last_name: String::new(),
            phone: None,
            avatar_url: None,
            status: UserStatus::PendingActivation,
            roles: vec![UserRole::User],
            groups: Vec::new(),
            permissions: Vec::new(),
            department: None,
            manager_id: None,
            employee_id: None,
            cost_center: None,
            location: None,
            timezone: "UTC".to_string(),
            language: "en".to_string(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            last_login: None,
            last_activity: None,
            password_last_changed: None,
            must_change_password: true,
            failed_login_attempts: 0,
            locked_until: None,
            two_factor_enabled: false,
            backup_codes: Vec::new(),
            security_settings: SecuritySettings::default(),
            preferences: UserPreferences::default(),
            metadata: HashMap::new(),
            tags: Vec::new(),
            notes: None,
        }
    }

    pub fn is_active(&self) -> bool {
        matches!(self.status, UserStatus::Active)
    }

    pub fn is_locked(&self) -> bool {
        self.locked_until.is_some_and(|until| until > Utc::now())
    }

    pub fn has_role(&self, role: &UserRole) -> bool {
        self.roles.contains(role)
    }

    pub fn has_permission(&self, resource: &str, action: &str) -> bool {
        self.permissions.iter().any(|p| {
            p.resource == resource
                && p.action == action
                && p.expires_at.is_none_or(|exp| exp > Utc::now())
        })
    }

    pub fn effective_permissions(&self) -> Vec<Permission> {
        self.permissions
            .iter()
            .filter(|p| p.expires_at.is_none_or(|exp| exp > Utc::now()))
            .cloned()
            .collect()
    }
}

impl Default for SecuritySettings {
    fn default() -> Self {
        Self {
            require_mfa: false,
            allowed_mfa_methods: vec![MfaMethod::Totp, MfaMethod::Email],
            session_timeout: 480, // 8 hours
            max_sessions: 3,
            ip_whitelist: Vec::new(),
            allowed_countries: Vec::new(),
            require_device_trust: false,
            password_policy: PasswordPolicy::default(),
            login_notifications: true,
            security_questions: Vec::new(),
        }
    }
}

impl Default for PasswordPolicy {
    fn default() -> Self {
        Self {
            min_length: 8,
            require_uppercase: true,
            require_lowercase: true,
            require_numbers: true,
            require_symbols: false,
            prevent_reuse: 5,
            max_age: Some(90),
            complexity_score: 3,
        }
    }
}

impl Default for UserPreferences {
    fn default() -> Self {
        Self {
            theme: "light".to_string(),
            dashboard_layout: "default".to_string(),
            notifications: NotificationPreferences::default(),
            locale: "en-US".to_string(),
            date_format: "YYYY-MM-DD".to_string(),
            time_format: "24h".to_string(),
            timezone_display: "local".to_string(),
            accessibility: AccessibilitySettings::default(),
        }
    }
}

impl Default for NotificationPreferences {
    fn default() -> Self {
        Self {
            email_notifications: true,
            sms_notifications: false,
            push_notifications: true,
            security_alerts: true,
            system_updates: true,
            workflow_updates: true,
            digest_frequency: DigestFrequency::Daily,
        }
    }
}

impl Default for AccessibilitySettings {
    fn default() -> Self {
        Self {
            high_contrast: false,
            large_text: false,
            screen_reader: false,
            keyboard_navigation: true,
            reduced_motion: false,
        }
    }
}
