//! Universal page translation trait
//!
//! This module provides a unified interface for translation that works
//! across both SSR and client contexts, eliminating code duplication.

use crate::i18n::urls::localize_url;

/// Universal translator trait that works in both SSR and client contexts
pub trait PageTranslator {
    /// Get translated text for a key
    fn t(&self, key: &str) -> String;

    /// Get localized URL for current language context
    fn localized_url(&self, path: &str) -> String;

    /// Get current language code
    fn lang_code(&self) -> String;
}

/// SSR translator implementation using language string
pub struct SsrTranslator {
    language: String,
}

impl SsrTranslator {
    /// Create a new SSR translator for the specified language
    pub fn new(language: String) -> Self {
        Self { language }
    }
}

impl PageTranslator for SsrTranslator {
    fn t(&self, key: &str) -> String {
        crate::i18n::t_for_language(&self.language, key)
    }

    fn localized_url(&self, path: &str) -> String {
        localize_url(path, &self.language)
    }

    fn lang_code(&self) -> String {
        self.language.clone()
    }
}

/// Trait extension for building page content structures
pub trait PageContentBuilder<T> {
    /// Build page content using any translator implementation
    fn build_with_translator<P: PageTranslator>(translator: &P) -> T;
}

/// Macro to generate translator-based builder methods
/// This eliminates the need for separate build_from_client and build_from_ssr
/// methods
#[macro_export]
macro_rules! impl_page_content_builder {
    ($struct_name:ident, $builder_fn:ident) => {
        impl $crate::page_translator::PageContentBuilder<$struct_name> for $struct_name {
            fn build_with_translator<P: $crate::page_translator::PageTranslator>(
                translator: &P,
            ) -> Self {
                $builder_fn(translator)
            }
        }

        impl $struct_name {
            /// Build content using any translator (unified method)
            pub fn build<P: $crate::page_translator::PageTranslator>(translator: &P) -> Self {
                Self::build_with_translator(translator)
            }

            /// Build content for SSR using language string
            pub fn build_for_ssr(language: &str) -> Self {
                let translator = $crate::page_translator::SsrTranslator::new(language.to_string());
                Self::build(&translator)
            }
        }
    };
}

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

    #[test]
    fn test_ssr_translator() {
        let translator = SsrTranslator::new("en".to_string());

        assert_eq!(translator.lang_code(), "en");
        assert_eq!(translator.localized_url("/about"), "/about");

        let es_translator = SsrTranslator::new("es".to_string());
        assert_eq!(es_translator.lang_code(), "es");
        assert_eq!(es_translator.localized_url("/about"), "/es/sobre-mi");
    }
}
