//! i18n translation support for form elements
//!
//! Provides functions to translate display items and field definitions.

use crate::i18n::I18nBundle;

use super::types::{DisplayItem, FieldDefinition, SelectOption};

/// Translate a DisplayItem if i18n is enabled
pub(super) fn translate_display_item(
    item: &DisplayItem,
    bundle: Option<&I18nBundle>,
) -> DisplayItem {
    if item.i18n.unwrap_or(false) {
        if let Some(bundle) = bundle {
            let mut translated = item.clone();
            if let Some(content) = &item.content {
                translated.content = Some(bundle.translate_if_key(content, None));
            }
            if let Some(title) = &item.title {
                translated.title = Some(bundle.translate_if_key(title, None));
            }
            return translated;
        }
    }
    item.clone()
}

/// Translate a FieldDefinition if i18n is enabled
pub(super) fn translate_field_definition(
    field: &FieldDefinition,
    bundle: Option<&I18nBundle>,
) -> FieldDefinition {
    if field.i18n.unwrap_or(false) {
        if let Some(bundle) = bundle {
            let mut translated = field.clone();
            translated.prompt = bundle.translate_if_key(&field.prompt, None);
            if let Some(placeholder) = &field.placeholder {
                translated.placeholder = Some(bundle.translate_if_key(placeholder, None));
            }
            if !field.options.is_empty() {
                translated.options = field
                    .options
                    .iter()
                    .map(|opt| SelectOption {
                        value: opt.value.clone(),
                        label: Some(
                            bundle
                                .translate_if_key(opt.label.as_deref().unwrap_or(&opt.value), None),
                        ),
                    })
                    .collect();
            }
            return translated;
        }
    }
    field.clone()
}
