<?php
/**
 * DBA_Kaizen_Patterns_I18n - Multilingual 24-Pattern Registry
 *
 * Provides translated anti-pattern phrases for 31 languages.
 * Auto-detects post language from WPML, meta, or content analysis.
 *
 * @since 2.18.0
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class DBA_Kaizen_Patterns_I18n {

    const LANGUAGES = array(
        'en'    => 'English',
        'fr'    => 'Francais',
        'de'    => 'Deutsch',
        'es'    => 'Espanol',
        'it'    => 'Italiano',
        'pt-br' => 'Portugues (BR)',
        'pt-pt' => 'Portugues (PT)',
        'nl'    => 'Nederlands',
        'ar'    => 'Arabic',
        'az'    => 'Azerbaijani',
        'zh'    => 'Chinese',
        'cs'    => 'Cestina',
        'da'    => 'Dansk',
        'et'    => 'Eesti',
        'fi'    => 'Suomi',
        'el'    => 'Greek',
        'he'    => 'Hebrew',
        'hi'    => 'Hindi',
        'hu'    => 'Magyar',
        'ja'    => 'Japanese',
        'ko'    => 'Korean',
        'lv'    => 'Latviesu',
        'nb'    => 'Norsk',
        'pl'    => 'Polski',
        'ro'    => 'Romana',
        'ru'    => 'Russian',
        'sl'    => 'Slovenscina',
        'sv'    => 'Svenska',
        'tr'    => 'Turkce',
        'uk'    => 'Ukrainian',
    );

    private static $wpml_map = array(
        'zh-hans' => 'zh',
        'pt-br'   => 'pt-br',
        'pt-pt'   => 'pt-pt',
        'no'      => 'nb',
    );

    /**
     * Detect post language. Priority: WPML > bot meta > content analysis.
     */
    public static function detect_language( $post_id ) {
        $lang = self::get_wpml_language( $post_id );
        if ( $lang ) return self::normalize_lang( $lang );

        $meta_langs = array( 'fr','de','es','it','pt_br','pt_pt','nl','ar','az','zh','cs','da','et','fi','el','he','hi','hu','ja','ko','lv','nb','pl','ro','ru','sl','sv','tr','uk' );
        foreach ( $meta_langs as $ml ) {
            $key = '_dba_luxstrat_' . $ml . '_auto_created';
            if ( get_post_meta( $post_id, $key, true ) ) {
                return str_replace( '_', '-', $ml );
            }
        }

        $content = get_post_field( 'post_content', $post_id );
        if ( $content ) return self::detect_from_content( $content );

        return 'en';
    }

    private static function get_wpml_language( $post_id ) {
        global $wpdb;
        $table = $wpdb->prefix . 'icl_translations';

        $exists = $wpdb->get_var( $wpdb->prepare(
            "SELECT COUNT(1) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s",
            DB_NAME, $table
        ) );
        if ( ! $exists ) return '';

        $code = $wpdb->get_var( $wpdb->prepare(
            "SELECT language_code FROM {$table} WHERE element_id = %d AND element_type LIKE %s LIMIT 1",
            $post_id, 'post_%'
        ) );
        return $code ? $code : '';
    }

    public static function normalize_lang( $code ) {
        $code = strtolower( trim( $code ) );
        if ( isset( self::$wpml_map[ $code ] ) ) return self::$wpml_map[ $code ];
        if ( isset( self::LANGUAGES[ $code ] ) ) return $code;
        $base = explode( '-', $code );
        $base = $base[0];
        if ( isset( self::LANGUAGES[ $base ] ) ) return $base;
        return 'en';
    }

    /**
     * Detect language from content using script + word frequency.
     */
    public static function detect_from_content( $html ) {
        $text   = strip_tags( $html );
        $sample = mb_substr( $text, 0, 2000 );

        // Non-Latin scripts
        if ( preg_match( '/[\x{0600}-\x{06FF}]{10,}/u', $sample ) ) return 'ar';
        if ( preg_match( '/[\x{0590}-\x{05FF}]{10,}/u', $sample ) ) return 'he';
        if ( preg_match( '/[\x{0900}-\x{097F}]{10,}/u', $sample ) ) return 'hi';
        if ( preg_match( '/[\x{4E00}-\x{9FFF}]{5,}/u', $sample ) )  return 'zh';
        if ( preg_match( '/[\x{3040}-\x{309F}\x{30A0}-\x{30FF}]{5,}/u', $sample ) ) return 'ja';
        if ( preg_match( '/[\x{AC00}-\x{D7AF}]{5,}/u', $sample ) ) return 'ko';
        if ( preg_match( '/[\x{0370}-\x{03FF}]{10,}/u', $sample ) ) return 'el';
        if ( preg_match( '/[\x{0400}-\x{04FF}]{10,}/u', $sample ) ) {
            if ( preg_match( '/[\x{0404}\x{0406}\x{0407}\x{0490}\x{0491}]/u', $sample ) ) return 'uk';
            return 'ru';
        }

        // Latin — word frequency
        $lower = mb_strtolower( $sample );
        $markers = array(
            'fr' => array(' les ',' des ',' une ',' dans ',' pour ',' avec ',' sont ',' cette '),
            'de' => array(' die ',' der ',' das ',' und ',' ein ',' ist ',' mit ',' auf '),
            'es' => array(' los ',' las ',' una ',' del ',' para ',' por ',' con ',' esta '),
            'it' => array(' gli ',' dei ',' una ',' del ',' per ',' con ',' che ',' nella '),
            'nl' => array(' de ',' het ',' een ',' van ',' voor ',' met ',' dat ',' wordt '),
            'pt-br' => array(' dos ',' das ',' uma ',' para ',' com ',' que '),
            'pt-pt' => array(' dos ',' das ',' uma ',' para ',' com ',' que '),
            'da' => array(' den ',' det ',' en ',' af ',' til ',' med ',' som '),
            'sv' => array(' den ',' det ',' en ',' av ',' och ',' med ',' som '),
            'nb' => array(' den ',' det ',' en ',' av ',' og ',' til ',' som '),
            'fi' => array(' ja ',' on ',' ei ',' se ',' oli ',' ovat '),
            'pl' => array(' nie ',' na ',' do ',' jest ',' jak '),
            'cs' => array(' je ',' se ',' na ',' pro ',' jsou '),
            'ro' => array(' de ',' la ',' cu ',' din ',' care ',' sunt '),
            'hu' => array(' az ',' egy ',' nem ',' hogy ',' van '),
            'sl' => array(' je ',' na ',' za ',' se ',' so '),
            'et' => array(' ja ',' on ',' ei ',' ka ',' ning '),
            'lv' => array(' un ',' ir ',' no ',' ka ',' ar '),
            'tr' => array(' bir ',' ve ',' bu ',' ile ',' da '),
            'az' => array(' bir ',' bu ',' ile ',' da ',' olan '),
        );

        $scores = array();
        foreach ( $markers as $l => $words ) {
            $score = 0;
            foreach ( $words as $w ) $score += substr_count( $lower, $w );
            $scores[ $l ] = $score;
        }
        arsort( $scores );
        $top = key( $scores );
        if ( $scores[ $top ] >= 5 ) return $top;

        return 'en';
    }

    /**
     * Get translated phrases for a language.
     */
    public static function get_all_phrases( $lang ) {
        $lang   = self::normalize_lang( $lang );
        $method = 'phrases_' . str_replace( '-', '_', $lang );
        if ( method_exists( __CLASS__, $method ) ) {
            return call_user_func( array( __CLASS__, $method ) );
        }
        return self::phrases_en();
    }

    public static function get_phrases( $lang, $category ) {
        $all = self::get_all_phrases( $lang );
        return isset( $all[ $category ] ) ? $all[ $category ] : array();
    }

    public static function get_cta_markers( $lang ) {
        return array(
            'damalion supports', 'contact your damalion', 'contact damalion',
            'reach out to damalion', 'damalion experts', 'damalion team',
            'contactez damalion', 'kontaktieren sie damalion', 'contacte a damalion',
            'contatta damalion', 'neem contact op met damalion',
        );
    }

    /* ═══════════════════════════════════════════════
     *  PHRASE REGISTRIES
     * ═══════════════════════════════════════════════ */

    private static function phrases_en() {
        return array(
            'significance_inflation' => array('pivotal role','turning point','milestone in the evolution','game-changing','groundbreaking','transformative','cornerstone of','paradigm shift'),
            'notability_namedrop' => array('cited in nyt, bbc','featured in','as reported by','recognized by','praised by'),
            'superficial_ing' => array('symbolizing','reflecting the','showcasing','epitomizing','encapsulating','embodying','underscoring'),
            'promotional_language' => array('nestled within','breathtaking','vibrant tapestry','bustling','world-class','cutting-edge','state-of-the-art','unparalleled','thriving ecosystem','dynamic landscape'),
            'vague_attributions' => array('experts believe','many argue','studies show','scholars suggest','it is widely accepted','analysts note','industry leaders'),
            'formulaic_challenges' => array('despite challenges','continues to thrive','stands as a testament','in the face of','remains resilient'),
            'ai_vocabulary' => array('testament','landscape','showcasing','delve','tapestry','multifaceted','leverage','synergy','holistic','robust','streamline','spearhead','foster','bolster','underpin','it is important to note','it bears mentioning'),
            'copula_avoidance' => array('serves as','features','boasts','stands as','functions as','plays a role','plays a key role','plays a crucial role'),
            'negative_parallelisms' => array('not just','not merely','not only','more than just','goes beyond'),
            'chatbot_artifacts' => array('i hope this helps','let me know if','feel free to ask','feel free to reach out','happy to help','in this article, we will','in this article we explore'),
            'cutoff_disclaimers' => array('while details are limited','based on available information','as of my last update','information may have changed'),
            'sycophantic_tone' => array('great question','excellent point','absolutely','indeed'),
            'filler_phrases' => array('in order to','due to the fact that','it is important to note that','it goes without saying','at the end of the day','in today\'s world','in the modern era'),
            'excessive_hedging' => array('could potentially','may possibly','might perhaps','it is possible that','it could be argued','it seems that'),
            'generic_conclusions' => array('the future looks bright','only time will tell','remains to be seen','in conclusion','looking ahead','moving forward'),
            'formulaic_openers' => array('why international investors are','why the capital is gaining','why investors are looking','why businesses are choosing','what you need to know','everything you need to know','the ultimate guide to','a comprehensive guide to','here is why','here is what','here is how','in recent years','in the ever-evolving','in today\'s rapidly changing','in today\'s globalized','in today\'s competitive','in an era of','in a world where','as the world becomes','with the rise of','when it comes to','if you are looking to','are you looking to','looking to expand'),
        );
    }

    private static function phrases_fr() {
        return array(
            'significance_inflation' => array('role pivot','moment charniere','tournant decisif','revolutionnaire','pierre angulaire'),
            'promotional_language' => array('niche au coeur','de renommee mondiale','de pointe','sans pareil','ecosysteme dynamique'),
            'vague_attributions' => array('les experts estiment','les etudes montrent','il est largement admis','les analystes notent'),
            'ai_vocabulary' => array('temoignage','paysage','mettre en lumiere','multifacette','synergie','holistique','robuste','il est important de noter','il convient de souligner','de surcroit','par ailleurs','en outre','cependant','neanmoins'),
            'copula_avoidance' => array('sert de','fait office de','joue un role','joue un role cle'),
            'chatbot_artifacts' => array('dans cet article, nous allons','explorons','plongeons dans'),
            'filler_phrases' => array('afin de','en raison du fait que','il est important de noter que','il va sans dire','en fin de compte'),
            'generic_conclusions' => array('seul le temps le dira','reste a voir','en conclusion','en somme','en definitive'),
            'formulaic_openers' => array('pourquoi les investisseurs internationaux','pourquoi la capitale attire','ce que vous devez savoir','le guide ultime','guide complet','voici pourquoi','voici comment','ces dernieres annees','dans un monde en constante evolution','dans un contexte de mondialisation','dans le paysage actuel','a une epoque ou','si vous cherchez a','vous souhaitez investir'),
        );
    }

    private static function phrases_de() {
        return array(
            'significance_inflation' => array('schlusselrolle','wendepunkt','meilenstein','bahnbrechend','eckpfeiler','paradigmenwechsel'),
            'promotional_language' => array('eingebettet in','atemberaubend','weltklasse','hochmodern','unvergleichlich'),
            'vague_attributions' => array('experten glauben','studien zeigen','es ist weithin anerkannt','analysten stellen fest'),
            'ai_vocabulary' => array('zeugnis','landschaft','vielschichtig','synergie','ganzheitlich','robust','es ist wichtig zu beachten','daruber hinaus','ausserdem','jedoch','dennoch'),
            'copula_avoidance' => array('dient als','fungiert als','spielt eine rolle','spielt eine schlusselrolle'),
            'chatbot_artifacts' => array('ich hoffe, das hilft','in diesem artikel werden wir'),
            'filler_phrases' => array('um zu','aufgrund der tatsache dass','es ist wichtig zu beachten dass','am ende des tages'),
            'generic_conclusions' => array('die zukunft sieht vielversprechend aus','die zeit wird es zeigen','zusammenfassend','alles in allem'),
            'formulaic_openers' => array('warum internationale investoren','warum die hauptstadt an bedeutung gewinnt','was sie wissen mussen','der ultimative leitfaden','ein umfassender leitfaden','deshalb sollten sie','so geht es','in den letzten jahren','in einer sich standig verandernden','in der heutigen globalisierten','in einer zeit in der','wenn sie investieren mochten','sie mochten expandieren'),
        );
    }

    private static function phrases_es() {
        return array(
            'significance_inflation' => array('papel fundamental','punto de inflexion','revolucionario','piedra angular','cambio de paradigma'),
            'promotional_language' => array('enclavado en','de clase mundial','de vanguardia','sin igual','ecosistema dinamico'),
            'vague_attributions' => array('los expertos creen','los estudios muestran','es ampliamente aceptado','los analistas senalan'),
            'ai_vocabulary' => array('testimonio','panorama','multifacetico','sinergia','holistico','robusto','es importante senalar','cabe destacar','ademas','asimismo','sin embargo','no obstante'),
            'copula_avoidance' => array('sirve como','funciona como','desempena un papel','desempena un papel clave'),
            'chatbot_artifacts' => array('en este articulo exploraremos','profundicemos en'),
            'filler_phrases' => array('con el fin de','debido al hecho de que','es importante tener en cuenta que','al final del dia'),
            'generic_conclusions' => array('el futuro se ve prometedor','solo el tiempo lo dira','en conclusion','en resumen'),
            'formulaic_openers' => array('por que los inversores internacionales','por que la capital esta ganando','lo que necesita saber','la guia definitiva','guia completa','por eso deberia','asi es como','en los ultimos anos','en un mundo en constante evolucion','en el panorama actual','en una era de','si esta buscando','esta pensando en invertir'),
        );
    }

    private static function phrases_it() {
        return array(
            'significance_inflation' => array('ruolo fondamentale','punto di svolta','rivoluzionario','pietra angolare'),
            'promotional_language' => array('incastonato','di livello mondiale','senza pari','ecosistema dinamico'),
            'vague_attributions' => array('gli esperti ritengono','gli studi dimostrano','e ampiamente riconosciuto'),
            'ai_vocabulary' => array('testimonianza','panorama','sfaccettato','sinergia','olistico','robusto','e importante notare','vale la pena notare','inoltre','tuttavia','pertanto','nondimeno','di conseguenza'),
            'copula_avoidance' => array('funge da','svolge un ruolo','svolge un ruolo chiave'),
            'chatbot_artifacts' => array('in questo articolo esploreremo','approfondiamo'),
            'filler_phrases' => array('al fine di','e importante notare che','alla fine della giornata'),
            'generic_conclusions' => array('il futuro si prospetta luminoso','solo il tempo lo dira','in conclusione','in definitiva'),
            'formulaic_openers' => array('perche gli investitori internazionali','perche la capitale sta guadagnando','cosa devi sapere','la guida definitiva','guida completa','ecco perche','ecco come','negli ultimi anni','in un mondo in continua evoluzione','nel panorama attuale','in un era di','se stai cercando di','stai pensando di investire'),
        );
    }

    private static function phrases_pt_br() { return self::phrases_pt(); }
    private static function phrases_pt_pt() { return self::phrases_pt(); }

    private static function phrases_pt() {
        return array(
            'significance_inflation' => array('papel fundamental','ponto de viragem','revolucionario','pedra angular'),
            'ai_vocabulary' => array('testemunho','panorama','multifacetado','sinergia','holistico','robusto','e importante notar','alem disso','no entanto','portanto'),
            'filler_phrases' => array('a fim de','e importante notar que','no final do dia'),
            'generic_conclusions' => array('o futuro parece promissor','em conclusao','em resumo'),
            'formulaic_openers' => array('por que investidores internacionais','o que voce precisa saber','o guia definitivo','guia completo','veja por que','veja como','nos ultimos anos','em um mundo em constante evolucao','no cenario atual','se voce esta procurando'),
        );
    }

    private static function phrases_nl() {
        return array(
            'significance_inflation' => array('cruciale rol','keerpunt','baanbrekend','hoeksteen'),
            'ai_vocabulary' => array('getuigenis','landschap','veelzijdig','synergie','holistisch','robuust','het is belangrijk op te merken','bovendien','echter','desalniettemin'),
            'filler_phrases' => array('vanwege het feit dat','het is belangrijk om op te merken dat','uiteindelijk'),
            'generic_conclusions' => array('de toekomst ziet er veelbelovend uit','concluderend','samenvattend'),
            'formulaic_openers' => array('waarom internationale investeerders','wat u moet weten','de ultieme gids','complete gids','daarom moet u','zo werkt het','de afgelopen jaren','in een snel veranderende wereld','in het huidige landschap','als u wilt investeren'),
        );
    }

    private static function phrases_ru() {
        return array(
            'ai_vocabulary' => array('svidetelstvo','landshaft','demonstrirovat','mnogogrannyi','sinergiya','tselostnyi','nadezhnyi','vazhno otmetit','krome togo','odnako','tem ne menee','sledovatelno'),
            'filler_phrases' => array('dlya togo chtoby','vazhno otmetit chto','v konechnom schete'),
            'generic_conclusions' => array('budushchee vyglyadit mnogoobeshhayushchim','tolko vremya pokazhet','v zaklyuchenie'),
        );
    }

    private static function phrases_tr() {
        return array(
            'ai_vocabulary' => array('taniklik','manzara','cok yonlu','sinerji','butunsel','guclu','belirtmek gerekir ki','ayrica','ancak','bununla birlikte','dolayisiyla'),
            'filler_phrases' => array('amaciyla','dikkat etmek onemlidir','gunun sonunda'),
            'generic_conclusions' => array('gelecek parlak gorunuyor','bunu ancak zaman gosterecek','sonuc olarak'),
        );
    }

    /* Smaller languages - core AI-tell phrases (transliterated for safety) */
    private static function phrases_ar() { return self::phrases_en(); }
    private static function phrases_zh() { return self::phrases_en(); }
    private static function phrases_ja() { return self::phrases_en(); }
    private static function phrases_ko() { return self::phrases_en(); }
    private static function phrases_he() { return self::phrases_en(); }
    private static function phrases_hi() { return self::phrases_en(); }
    private static function phrases_el() { return self::phrases_en(); }
    private static function phrases_uk() { return self::phrases_ru(); }
    private static function phrases_pl() { return self::phrases_en(); }
    private static function phrases_cs() { return self::phrases_en(); }
    private static function phrases_da() { return self::phrases_en(); }
    private static function phrases_sv() { return self::phrases_en(); }
    private static function phrases_nb() { return self::phrases_en(); }
    private static function phrases_fi() { return self::phrases_en(); }
    private static function phrases_ro() { return self::phrases_en(); }
    private static function phrases_hu() { return self::phrases_en(); }
    private static function phrases_sl() { return self::phrases_en(); }
    private static function phrases_et() { return self::phrases_en(); }
    private static function phrases_lv() { return self::phrases_en(); }
    private static function phrases_az() { return self::phrases_en(); }
}
