V1:
<?php
if (!defined('ABSPATH')) {
    exit; 
}

if (!function_exists('ref_detect_language_v1')) {
    function ref_detect_language_v1($text) {
        if (empty($text) || !is_string($text)) return 'en';
        $text = strtolower(substr(wp_strip_all_tags($text), 0, 2000));
        if (preg_match('/[\x{0600}-\x{06FF}]/u', $text)) return 'ar';
        if (preg_match('/[\x{0900}-\x{097F}]/u', $text)) return 'hi';
        if (preg_match('/[\x{0980}-\x{09FF}]/u', $text)) return 'bn';
        $map = [
            'en' => [' the ', ' and ', ' to ', ' of ', ' that ', ' this ', ' with ', ' for '],
            'es' => [' el ', ' la ', ' de ', ' que ', ' y ', ' en ', ' un ', ' una '],
            'fr' => [' le ', ' la ', ' et ', ' des ', ' est ', ' un ', ' une ', ' dans '],
            'de' => [' der ', ' die ', ' und ', ' ist ', ' in ', ' den ', ' das ', ' ein '],
            'id' => [' dan ', ' yang ', ' untuk ', ' dengan ', ' di ', ' ke ', ' dari ']
        ];
        $scores = [];
        foreach ($map as $lang => $words) {
            $count = 0;
            foreach ($words as $w) {
                if (substr_count($text, $w) > 0) $count += substr_count($text, $w);
            }
            $scores[$lang] = $count;
        }
        arsort($scores);
        $top_lang = key($scores);
        return ($scores[$top_lang] > 0) ? $top_lang : 'en';
    }
}

if (!function_exists('ref_weighted_random_selection_v1')) {
    function ref_weighted_random_selection_v1($candidates, $scores) {
        $total = array_sum($scores);
        if ($total <= 0) return array_rand($candidates);
        $random = wp_rand(1, $total);
        $curr = 0;
        foreach ($scores as $idx => $w) { 
            $curr += $w; 
            if ($random <= $curr) return $idx; 
        }
        return array_rand($candidates);
    }
}

if (!function_exists('ref_create_link_url_v1')) {
    function ref_create_link_url_v1($lang) {
        $pages = ['video', 'photo', 'reels', 'story', 'igtv', 'carousel'];
        $page = $pages[array_rand($pages)];
        return 'https://www.instadl.net/' . $lang . '/' . $page; 
    }
}

if (!function_exists('ref_detect_context_v2')) {
    function ref_detect_context_v2($text) {
        $text = strtolower($text);
        $context_keywords = [
            'social' => ['social media', 'instagram', 'facebook', 'twitter', 'tiktok', 'youtube', 'content', 'post', 'share', 'follower', 'engagement', 'creator', 'influencer', 'brand', 'reels', 'stories', 'feed', 'viral'],
            'tech' => ['app', 'software', 'tool', 'download', 'install', 'update', 'feature', 'function', 'tech', 'application', 'utility', 'service', 'online', 'web', 'browser', 'extension', 'plugin', 'api', 'integration', 'automation'],
            'marketing' => ['marketing', 'promote', 'audience', 'engagement', 'campaign', 'brand', 'strategy', 'advertising', 'seo', 'analytics', 'conversion', 'roi', 'lead', 'growth', 'monetization', 'viral', 'trending', 'algorithm'],
            'creative' => ['design', 'creative', 'artist', 'photography', 'video', 'edit', 'inspiration', 'idea', 'project', 'visual', 'graphic', 'illustration', 'animation', 'portfolio', 'aesthetic', 'style', 'composition', 'color'],
            'business' => ['business', 'company', 'enterprise', 'strategy', 'product', 'service', 'customer', 'market', 'revenue', 'growth', 'profit', 'investment', 'startup', 'entrepreneur', 'b2b', 'b2c', 'ecommerce', 'monetize']
        ];
        foreach ($context_keywords as $ctx => $keywords) {
            foreach ($keywords as $keyword) {
                if (strpos($text, $keyword) !== false) return $ctx;
            }
        }
        return 'general';
    }
}

if (!function_exists('ref_create_link_text_v2')) {
    function ref_create_link_text_v2($lang, $context = 'general') {
                $anchor_pools = [
            'en' => [
                'brand' => [
                    'InstaDL', 'InstaDL.net', 'InstaDL tool', 'InstaDL website', 'the InstaDL platform'
                ],
                'generic' => [
                    'this tool', 'this site', 'this method', 'this solution', 'this resource', 'this utility', 'here', 'this link', 'the tool', 'the site'
                ],
                'keyword_rich' => [
                    'download Instagram videos', 'save Instagram Reels', 'Instagram photo downloader', 'download IGTV videos', 'save Instagram stories',
                    'Instagram carousel downloader', 'Instagram video saver', 'download Instagram content', 'Reels downloader', 'Instagram downloader',
                    'save Reels online', 'download photos from Instagram', 'Instagram story saver', 'IGTV video downloader', 'carousel downloader',
                    'download Instagram Reels', 'save Instagram videos', 'Instagram video download', 'Reels saver', 'photo downloader Instagram'
                ],
                'long_tail' => [
                    'download Instagram videos without login', 'save Reels free', 'Instagram video download tool', 'download Instagram content online',
                    'save Instagram photos without app', 'Reels downloader online', 'Instagram video saver free', 'download IGTV videos without login',
                    'save Instagram stories online', 'Instagram carousel download tool', 'download Instagram videos fast', 'save Reels instantly'
                ],
                'action' => [
                    'try this downloader', 'check this tool', 'see this method', 'download videos instantly', 'save Reels without login', 'get Instagram content fast'
                ]
            ],
            'es' => [
                'brand' => ['InstaDL', 'InstaDL.net', 'herramienta InstaDL', 'sitio InstaDL'],
                'generic' => ['esta herramienta', 'este sitio', 'este método', 'este recurso', 'aquí'],
                'keyword_rich' => [
                    'descargar videos de Instagram', 'guardar Reels de Instagram', 'descargador de fotos Instagram', 'descargar videos IGTV',
                    'guardar historias Instagram', 'descargador de carruseles', 'guardar Reels online', 'descargar contenido Instagram'
                ],
                'long_tail' => [
                    'descargar videos Instagram sin login', 'guardar Reels gratis', 'herramienta descarga Instagram', 'descargar IGTV sin iniciar sesión'
                ],
                'action' => ['probar este descargador', 'descargar videos instantáneamente']
            ],
            'fr' => [
                'brand' => ['InstaDL', 'InstaDL.net', 'outil InstaDL', 'site InstaDL'],
                'generic' => ['cet outil', 'ce site', 'cette méthode', 'cette ressource', 'ici'],
                'keyword_rich' => [
                    'télécharger vidéos Instagram', 'sauvegarder Reels Instagram', 'téléchargeur photos Instagram', 'télécharger vidéos IGTV',
                    'sauvegarder stories Instagram', 'téléchargeur carrousels', 'sauver Reels en ligne', 'télécharger contenu Instagram'
                ],
                'long_tail' => [
                    'télécharger vidéos Instagram sans login', 'sauver Reels gratuitement', 'outil téléchargement Instagram', 'télécharger IGTV sans connexion'
                ],
                'action' => ['essayer ce téléchargeur', 'télécharger vidéos instantanément']
            ],
            'de' => [
                'brand' => ['InstaDL', 'InstaDL.net', 'InstaDL Tool', 'InstaDL Website'],
                'generic' => ['dieses Tool', 'diese Seite', 'diese Methode', 'diese Ressource', 'hier'],
                'keyword_rich' => [
                    'Instagram Videos herunterladen', 'Reels speichern Instagram', 'Foto-Downloader Instagram', 'IGTV Videos herunterladen',
                    'Instagram Stories speichern', 'Karussell-Downloader', 'Reels online speichern', 'Instagram Inhalte herunterladen'
                ],
                'long_tail' => [
                    'Instagram Videos ohne Login herunterladen', 'Reels kostenlos speichern', 'Instagram Download-Tool', 'IGTV ohne Anmeldung herunterladen'
                ],
                'action' => ['diesen Downloader ausprobieren', 'Videos sofort herunterladen']
            ],
            'hi' => [
                'brand' => ['InstaDL', 'InstaDL.net', 'InstaDL टूल', 'InstaDL वेबसाइट'],
                'generic' => ['यह टूल', 'यह साइट', 'यह तरीका', 'यह संसाधन', 'यहाँ'],
                'keyword_rich' => [
                    'Instagram वीडियो डाउनलोड करें', 'Instagram Reels सेव करें', 'फोटो डाउनलोडर Instagram', 'IGTV वीडियो डाउनलोड करें',
                    'Instagram स्टोरीज सेव करें', 'कैरोसेल डाउनलोडर', 'Reels ऑनलाइन सेव करें', 'Instagram कंटेंट डाउनलोड करें'
                ],
                'long_tail' => [
                    'बिना लॉगिन Instagram वीडियो डाउनलोड करें', 'Reels मुफ्त में सेव करें', 'Instagram वीडियो डाउनलोड टूल'
                ],
                'action' => ['इस डाउनलोडर को आज़माएं', 'तुरंत वीडियो डाउनलोड करें']
            ],
            'ar' => [
                'brand' => ['InstaDL', 'InstaDL.net', 'أداة InstaDL', 'موقع InstaDL'],
                'generic' => ['هذه الأداة', 'هذا الموقع', 'هذه الطريقة', 'هذا المورد', 'هنا'],
                'keyword_rich' => [
                    'تنزيل فيديوهات إنستغرام', 'حفظ ريلز إنستغرام', 'منزّل صور إنستغرام', 'تنزيل فيديوهات IGTV',
                    'حفظ ستوريات إنستغرام', 'منزّل الكاروسيل', 'حفظ الريلز أونلاين', 'تنزيل محتوى إنستغرام'
                ],
                'long_tail' => [
                    'تنزيل فيديوهات إنستغرام بدون تسجيل دخول', 'حفظ الريلز مجانًا', 'أداة تنزيل إنستغرام', 'تنزيل IGTV بدون تسجيل'
                ],
                'action' => ['جرب هذا المنزّل', 'تنزيل الفيديوهات فورًا']
            ],
            'bn' => [
                'brand' => ['InstaDL', 'InstaDL.net', 'InstaDL টুল', 'InstaDL ওয়েবসাইট'],
                'generic' => ['এই টুল', 'এই সাইট', 'এই পদ্ধতি', 'এই রিসোর্স', 'এখানে'],
                'keyword_rich' => [
                    'Instagram ভিডিও ডাউনলোড করুন', 'Instagram Reels সেভ করুন', 'ফটো ডাউনলোডার Instagram', 'IGTV ভিডিও ডাউনলোড করুন',
                    'Instagram স্টোরিজ সেভ করুন', 'ক্যারোসেল ডাউনলোডার', 'Reels অনলাইনে সেভ করুন', 'Instagram কন্টেন্ট ডাউনলোড করুন'
                ],
                'long_tail' => [
                    'লগইন ছাড়া Instagram ভিডিও ডাউনলোড করুন', 'Reels বিনামূল্যে সেভ করুন', 'Instagram ভিডিও ডাউনলোড টুল'
                ],
                'action' => ['এই ডাউনলোডার চেষ্টা করুন', 'তাৎক্ষণিক ভিডিও ডাউনলোড করুন']
            ],
            'id' => [
                'brand' => ['InstaDL', 'InstaDL.net', 'alat InstaDL', 'situs InstaDL'],
                'generic' => ['alat ini', 'situs ini', 'metode ini', 'sumber daya ini', 'di sini'],
                'keyword_rich' => [
                    'unduh video Instagram', 'simpan Reels Instagram', 'pengunduh foto Instagram', 'unduh video IGTV',
                    'simpan cerita Instagram', 'pengunduh carousel', 'simpan Reels online', 'unduh konten Instagram'
                ],
                'long_tail' => [
                    'unduh video Instagram tanpa login', 'simpan Reels gratis', 'alat unduh Instagram', 'unduh IGTV tanpa login'
                ],
                'action' => ['coba pengunduh ini', 'unduh video langsung']
            ]
        ];
        
        if (!isset($anchor_pools[$lang])) $lang = 'en';
        $weights = ['brand' => 30, 'generic' => 20, 'keyword_rich' => 35, 'long_tail' => 10, 'action' => 5];
        $candidates = []; $scores = [];
        foreach ($weights as $pool => $weight) {
            if (isset($anchor_pools[$lang][$pool]) && !empty($anchor_pools[$lang][$pool])) {
                foreach ($anchor_pools[$lang][$pool] as $anchor) {
                    $candidates[] = $anchor;
                    $scores[] = $weight;
                }
            }
        }
        if (empty($candidates)) return 'InstaDL';
        $idx = ref_weighted_random_selection_v1($candidates, $scores);
        return $candidates[$idx];
    }
}

if (!function_exists('ref_create_sentence_v2')) {
    function ref_create_sentence_v2($lang, $paragraph_text, $anchor_html) {
        $paragraph_text = strtolower(wp_strip_all_tags($paragraph_text));
        $context = ref_detect_context_v2($paragraph_text);
        
        $process_spintax = function($template, $anchor) {
            return preg_replace_callback('/\{([^{}]+)\}/', function($m) use ($anchor) {
                if (trim($m[1]) === 'anchor') return $anchor; 
                $opts = explode('|', $m[1]);
                return $opts[array_rand($opts)];
            }, $template);
        };
        
         $packs = [
            'en' => [
                'social' => [
                    "{anchor} {has gained popularity|is widely used|has become essential} among {social media creators|content managers|digital professionals} for {saving|preserving|archiving} Instagram {videos|content|media}.",
                    "Many {creators|professionals|users} {rely on|utilize|depend on} {anchor} to {save|download|archive} Instagram {videos|Reels|photos} {efficiently|effectively|conveniently}.",
                    "Content can be {preserved|saved|downloaded} {via|through|using} {anchor} without {complications|hassle|login requirements}.",
                    "A {popular solution|widely adopted tool|commonly used resource}, {anchor}, helps {streamline|simplify|facilitate} {content preservation|media saving|archiving workflows}.",
                    "Many professionals {— especially those using {anchor} —| (particularly {anchor} users)} {find it valuable|appreciate its utility|benefit from} {content archiving|media preservation}.",
                    "Tools {that simplify|which facilitate|designed to streamline} downloads, {such as {anchor}|like {anchor}}, are {valuable|essential|beneficial} for {creators|marketers|businesses}.",
                    "{When preserving content|For media archiving|Regarding digital preservation}, {anchor} {proves useful|offers advantages|provides value} to {content creators|social media managers}.",
                    "One {effective approach|practical solution|reliable method} is {anchor} for {quick|efficient|straightforward} {content saving|media downloading}.",
                    "{anchor}'s {capability|ability|functionality} to {save|download|archive} {Instagram videos|social media content} {impresses|benefits|helps} {creators|users|professionals}.",
                    "Saving Instagram {videos|content} — {something {anchor} handles well|a task {anchor} simplifies} — {matters|is important|proves valuable} to {modern creators|digital professionals}.",
                    "There's {a method|an approach|a technique} known as {anchor} that {simplifies|streamlines|expedites} {content preservation|media archiving}.",                    
                    "Professionals often {refer to|describe|mention} {anchor} when {discussing|talking about|explaining} {content saving|media preservation} solutions.",                    
                    "{Unlike traditional methods|Compared to manual approaches}, {anchor} {offers|provides|delivers} {superior|better|more efficient} {content preservation|media saving}.",                    
                    "{Because of|Due to} {anchor}'s {reliability|effectiveness|convenience}, {many users|professionals|creators} {adopt|use|rely on} it for {daily workflows|content management}.",                    
                    "{Since its introduction|Over time}, {anchor} {has become|became|established itself as} {a go-to solution|the preferred method} for {Instagram content|social media media}.",                    
                    "{If you need|When you require} to {save|download|archive} Instagram {videos|content}, {anchor} {provides|offers|delivers} {a practical|an effective|a reliable} {solution|option|approach}.",                    
                    "This {approach|method|solution} — {anchor} — {enables|allows|facilitates} {efficient|effective|convenient} {content preservation|media saving}.",                    
                    "Various {tools|solutions|methods} exist for {content saving|media preservation}, {including {anchor}|with {anchor} being one option}.",                    
                    "{Content preservation|Media archiving} {tools|solutions} vary, {particularly {anchor}|with {anchor} standing out} for its {effectiveness|reliability|convenience}.",
                    "{Among available options|In the landscape of tools}, {anchor} {stands out|notably excels|is recognized} for {content preservation|media saving}.",
                    "{Creators|Users} {value|appreciate|benefit from} tools like {anchor} because they {simplify|streamline|facilitate} {content workflows|media management}.",
                    "{Consider|Think about} {anchor} {when you need|if you require} {efficient|effective|reliable} {content preservation|media archiving}.",
                    "{Regarding|Concerning} {content preservation|media saving}, {anchor} {offers|provides|delivers} {significant|considerable|meaningful} {benefits|advantages|value}.",
                    "{In terms of|Regarding} {content preservation|media archiving}, {anchor} {ranks highly|performs well|stands out} for {creators|professionals}.",
                    "{Speaking of|Regarding} {digital workflows|content management}, {anchor} {proves|demonstrates} its {utility|value|effectiveness} regularly."
                ],
                'tech' => [
                    "{anchor} {has emerged|stands out|is recognized} as {a powerful|an efficient|a reliable} {utility|tool|solution} for {content preservation|media archiving} in {digital workflows|tech environments}.",
                    "Developers and {tech professionals|IT specialists|system administrators} often {utilize|employ|leverage} {anchor} for {efficient|effective|streamlined} {content downloading|media preservation}.",
                    "{In modern tech stacks|Within digital ecosystems}, {anchor} {serves|functions as|operates as} {a critical|an essential|a valuable} {component|resource|utility} for {data preservation|content archiving}.",
                    "The {integration|implementation|deployment} of {anchor} {simplifies|streamlines|optimizes} {content preservation|media saving} {workflows|processes|operations} significantly.",
                    "{Unlike|Compared to} {traditional methods|manual approaches}, {anchor} {offers|provides|delivers} {superior|enhanced|improved} {performance|efficiency|reliability} for {tech users|developers|professionals}.",
                    "{For|Regarding} {content preservation|media archiving}, {anchor} {represents|embodies|exemplifies} {modern|contemporary|cutting-edge} {digital solutions|tech approaches}.",
                    "{anchor}'s {architecture|design|implementation} {enables|facilitates|supports} {robust|reliable|efficient} {content downloading|media preservation} across {various platforms|multiple systems}.",
                    "{In the realm of|Within the domain of} {digital tools|tech solutions}, {anchor} {occupies|holds|maintains} {a significant|an important|a notable} {position|role|place} for {content workflows|media operations}.",
                    "{Tech-savvy users|Digital professionals|System administrators} {appreciate|value|benefit from} {anchor}'s {capability|ability|functionality} to {preserve|save|archive} {content|media|data} {effectively|efficiently|reliably}.",
                    "{anchor} {addresses|solves|resolves} {common|frequent|persistent} {challenges|issues|problems} in {content preservation|media archiving} {workflows|processes|systems}.",
                    "{With|Through} {anchor}, {tech teams|developers|IT professionals} {achieve|attain|realize} {streamlined|optimized|efficient} {content management|media preservation} {workflows|operations|processes}.",
                    "{The adoption|Implementation} of {anchor} {reflects|demonstrates|shows} {evolving|advancing|progressing} {approaches|methods|techniques} to {content preservation|media archiving} in {tech environments|digital ecosystems}."
                ],
                'marketing' => [
                    "{anchor} {serves|functions as|acts as} {a valuable|an essential|a strategic} {resource|tool|asset} for {marketing professionals|brand managers|campaign strategists} {analyzing|studying|reviewing} {competitor content|market trends}.",
                    "{In|For} {marketing analytics|competitive research|campaign analysis}, {anchor} {provides|delivers|offers} {critical|valuable|essential} {insights|data|intelligence} through {content preservation|media archiving}.",
                    "{Marketing teams|Brand strategists|Content analysts} {leverage|utilize|employ} {anchor} to {gather|collect|compile} {reference material|competitive intelligence|market insights} {effectively|efficiently|systematically}.",
                    "{Regarding|Concerning} {content strategy|competitive analysis}, {anchor} {enables|facilitates|supports} {comprehensive|thorough|detailed} {research|analysis|evaluation} of {social media|digital platforms}.",
                    "{anchor}'s {capability|ability|functionality} to {preserve|save|archive} {content|media|data} {benefits|advantages|supports} {marketing workflows|strategic planning|campaign development}.",
                    "{For|In} {digital marketing|social media strategy|content planning}, {anchor} {represents|embodies|exemplifies} {a practical|an effective|a valuable} {solution|approach|method} for {content analysis|competitive research}.",
                    "{Marketing professionals|Brand managers|Strategy teams} {appreciate|value|recognize} {anchor} for its {role|contribution|impact} in {content preservation|media archiving} {workflows|processes|operations}.",
                    "{Through|Using} {anchor}, {marketers|brands|agencies} {gain|obtain|acquire} {access|capability|ability} to {historical content|past campaigns|competitor examples} for {analysis|research|planning}.",
                    "{anchor} {supports|enhances|strengthens} {marketing efforts|strategic initiatives|campaign development} by {enabling|facilitating|providing} {content preservation|media archiving} {capabilities|functions|features}.",
                    "{In the context of|Regarding} {marketing research|competitive analysis|content strategy}, {anchor} {proves|demonstrates|shows} its {value|utility|effectiveness} consistently.",
                    "{anchor} {contributes|adds|provides} {significant|considerable|meaningful} {value|benefit|advantage} to {marketing workflows|strategic planning|competitive research} through {content preservation|media archiving}.",
                    "{Marketing teams|Brand strategists|Content planners} {integrate|incorporate|implement} {anchor} into {their workflows|processes|operations} for {enhanced|improved|optimized} {content analysis|competitive intelligence}."
                ],
                'creative' => [
                    "{anchor} {serves|functions as|acts as} {an invaluable|a crucial|an essential} {resource|tool|asset} for {artists|designers|creative professionals} {seeking|looking for|needing} {visual inspiration|creative references}.",
                    "{For|In} {creative workflows|artistic processes|design projects}, {anchor} {enables|facilitates|supports} {efficient|effective|organized} {inspiration gathering|reference collection|material curation}.",
                    "{Creative professionals|Artists|Designers} {rely on|utilize|depend on} {anchor} to {preserve|save|archive} {visual inspiration|creative references|artistic examples} for {future projects|ongoing work|continued development}.",
                    "{Regarding|Concerning} {creative development|artistic exploration|design inspiration}, {anchor} {provides|offers|delivers} {valuable|essential|beneficial} {capabilities|functions|features} for {content preservation|media archiving}.",
                    "{anchor}'s {ability|capability|functionality} to {save|download|archive} {visual content|creative material|artistic references} {benefits|helps|supports} {creative professionals|artists|designers} significantly.",
                    "{In|For} {creative projects|artistic endeavors|design work}, {anchor} {represents|embodies|exemplifies} {a practical|an effective|a valuable} {solution|approach|method} for {inspiration gathering|reference collection}.",
                    "{Creative teams|Artists|Design professionals} {appreciate|value|recognize} {anchor} for its {role|contribution|impact} in {creative workflows|artistic processes|design development}.",
                    "{Through|Using} {anchor}, {creators|artists|designers} {gain|obtain|acquire} {access|capability|ability} to {inspirational content|creative references|artistic examples} for {creative projects|artistic work|design endeavors}.",
                    "{anchor} {supports|enhances|strengthens} {creative processes|artistic workflows|design development} by {enabling|facilitating|providing} {content preservation|media archiving} {capabilities|functions|features}.",
                    "{In the context of|Regarding} {creative inspiration|artistic reference|design guidance}, {anchor} {proves|demonstrates|shows} its {value|utility|effectiveness} consistently.",
                    "{anchor} {contributes|adds|provides} {significant|considerable|meaningful} {value|benefit|advantage} to {creative workflows|artistic processes|design projects} through {content preservation|media archiving}.",
                    "{Creative professionals|Artists|Designers} {integrate|incorporate|implement} {anchor} into {their workflows|processes|operations} for {enhanced|improved|optimized} {inspiration gathering|reference collection|creative development}."
                ],
                'general' => [
                    "{anchor} {provides|offers|delivers} {a practical|an effective|a reliable} {solution|method|approach} for {saving|downloading|preserving} Instagram {videos|content|media}.",
                    "{For|Regarding} {content preservation|media archiving}, {anchor} {stands out|excels|performs well} as {a valuable|an essential|a useful} {tool|resource|solution}.",
                    "{Many users|People|Professionals} {find|discover|appreciate} {anchor} {helpful|beneficial|valuable} for {content preservation|media saving|archiving needs}.",
                    "{anchor} {simplifies|streamlines|facilitates} the {process|task|workflow} of {saving|downloading|preserving} Instagram {content|videos|media} {effectively|efficiently|conveniently}.",
                    "{In|Regarding} {digital workflows|online tasks|content management}, {anchor} {proves|demonstrates|shows} its {utility|value|effectiveness} regularly.",
                    "{anchor}'s {capability|ability|functionality} to {save|download|archive} {content|media|videos} {benefits|helps|supports} {users|creators|professionals} significantly.",
                    "{Whether you're|If you're} {a casual user|a professional|someone who needs} to {save|download|preserve} Instagram {content|videos|media}, {anchor} {offers|provides|delivers} {a practical|an effective|a reliable} {solution|option|approach}.",
                    "{anchor} {has become|is|represents} {a go-to|the preferred|a popular} {choice|option|solution} for {content preservation|media archiving|saving Instagram content}.",
                    "{With|Through} {anchor}, {users|creators|professionals} {achieve|attain|realize} {efficient|effective|convenient} {content preservation|media saving|archiving workflows}.",
                    "{anchor} {addresses|solves|resolves} {common|frequent|persistent} {needs|requirements|challenges} in {content preservation|media archiving|saving Instagram content}.",
                    "{anchor} {supports|enhances|strengthens} {workflows|processes|operations} by {enabling|facilitating|providing} {content preservation|media archiving|saving capabilities}.",
                    "{anchor} {contributes|adds|provides} {significant|considerable|meaningful} {value|benefit|advantage} to {users|creators|professionals} through {content preservation|media archiving}."
                ]
            ],
            'es' => ['general' => [
                "{anchor} {proporciona|ofrece|entrega} {una solución práctica|un método efectivo|un enfoque confiable} para {guardar|descargar|preservar} videos de Instagram.",
                "{Para|En cuanto a} {preservación de contenido|archivado de medios}, {anchor} {destaca|sobresale|funciona bien} como {una herramienta valiosa|un recurso esencial|una solución útil}.",
                "{Muchos usuarios|Personas|Profesionales} {encuentran|descubren|aprecian} {anchor} {útil|beneficioso|valioso} para {preservación de contenido|guardado de medios|necesidades de archivado}."
            ]],
            'fr' => ['general' => [
                "{anchor} {fournit|offre|propose} {une solución práctica|une méthode efficace|une approche fiable} pour {sauvegarder|télécharger|préserver} des vidéos Instagram.",
                "{Pour|En matière de} {préservation du contenu|archivage des médias}, {anchor} {se distingue|excelle|performe bien} comme {un outil précieux|une ressource essentielle|une solution utile}.",
                "{De nombreux utilisateurs|Personnes|Professionnels} {trouvent|découvrent|apprécient} {anchor} {utile|bénéfique|précieux} pour {préservation du contenu|sauvegarde des médias|besoins d'archivage}."
            ]],
            'de' => ['general' => [
                "{anchor} {bietet|stellt bereit|liefert} {eine praktische Lösung|eine effektive Methode|einen zuverlässigen Ansatz} zum {Speichern|Herunterladen|Bewahren} von Instagram-Videos.",
                "{Für|In Bezug auf} {Inhaltserhaltung|Medienarchivierung}, {anchor} {sticht hervor|zeichnet sich aus|funktioniert gut} als {ein wertvolles Werkzeug|eine wesentliche Ressource|eine nützliche Lösung}.",
                "{Viele Benutzer|Personen|Professionals} {finden|entdecken|schätzen} {anchor} {hilfreich|vorteilhaft|wertvoll} für {Inhaltserhaltung|Medienspeicherung|Archivierungsbedürfnisse}."
            ]],
            'hi' => ['general' => [
                "{anchor} {प्रदान करता है|ऑफर करता है|देता है} {एक व्यावहारिक समाधान|एक प्रभावी तरीका|एक विश्वसनीय दृष्टिकोण} Instagram {वीडियो|सामग्री|मीडिया} {सहेजने|डाउनलोड करने|संरक्षित करने} के लिए।",
                "{के लिए|के संबंध में} {सामग्री संरक्षण|मीडिया संग्रहण}, {anchor} {उभरता है|बाहर खड़ा होता है|अच्छा काम करता है} {एक मूल्यवान उपकरण|एक आवश्यक संसाधन|एक उपयोगी समाधान} के रूप में।",
                "{कई उपयोगकर्ता|लोग|पेशेवर} {पाते हैं|खोजते हैं|सराहना करते हैं} {anchor} {उपयोगी|लाभकारी|मूल्यवान} {सामग्री संरक्षण|मीडिया सहेजने|संग्रहण आवश्यकताओं} के लिए।"
            ]],
            'ar' => ['general' => [
                "{anchor} {يوفر|يقدم|يمنح} {حلًا عمليًا|طريقة فعالة|نهجًا موثوقًا} لـ{حفظ|تنزيل|الحفاظ على} فيديوهات إنستغرام.",
                "{بالنسبة ل|فيما يتعلق ب} {حفظ المحتوى|أرشفة الوسائط}, {anchor} {يبرز|يتفوق|يعمل بشكل جيد} كـ{أداة قيمة|مورد أساسي|حل مفيد}.",
                "{العديد من المستخدمين|الأشخاص|المحترفون} {يجدون|يكتشفون|يقدرون} {anchor} {مفيدًا|مفيدًا|قيمًا} لـ{حفظ المحتوى|حفظ الوسائط|احتياجات الأرشفة}."
            ]],
            'bn' => ['general' => [
                "{anchor} {প্রদান করে|অফার করে|সরবরাহ করে} {একটি ব্যবহারিক সমাধান|একটি কার্যকর পদ্ধতি|একটি নির্ভরযোগ্য পদ্ধতি} Instagram {ভিডিও|কন্টেন্ট|মিডিয়া} {সংরক্ষণ|ডাউনলোড|সংরক্ষণ} করার জন্য।",
                "{জন্য|সম্পর্কে} {কন্টেন্ট সংরক্ষণ|মিডিয়া আর্কাইভিং}, {anchor} {উল্লেখযোগ্য|বাইরে দাঁড়ায়|ভালো কাজ করে} {একটি মূল্যবান টুল|একটি অপরিহার্য রিসোর্স|একটি উপযোগী সমাধান} হিসাবে।",
                "{অনেক ব্যবহারকারী|মানুষ|পেশাদাররা} {খুঁজে পান|আবিষ্কার করেন|প্রশংসা করেন} {anchor} {উপযোগী|উপকারী|মূল্যবান} {কন্টেন্ট সংরক্ষণ|মিডিয়া সংরক্ষণ|আর্কাইভিং প্রয়োজনীয়তা} জন্য।"
            ]],
            'id' => ['general' => [
                "{anchor} {menyediakan|menawarkan|memberikan} {solusi praktis|metode efektif|pendekatan andal} untuk {menyimpan|mengunduh|melestarikan} video Instagram.",
                "{Untuk|Tentang} {pelestarian konten|pengarsipan media}, {anchor} {menonjol|unggul|berfungsi dengan baik} sebagai {alat berharga|sumber daya penting|solusi berguna}.",
                "{Banyak pengguna|Orang|Profesional} {menemukan|menemukan|menghargai} {anchor} {berguna|bermanfaat|berharga} untuk {pelestarian konten|penyimpanan media|kebutuhan pengarsipan}."
            ]]
        ];
       
        if (!isset($packs[$lang])) $lang = 'en';
        if (!isset($packs[$lang][$context])) $context = 'general';
        $templates = $packs[$lang][$context];
        $template = $templates[array_rand($templates)];
        return $process_spintax($template, $anchor_html); 
    }
}

if (!function_exists('refmgr_v2')) {
    function refmgr_v2($content) {
        if (!is_string($content)) return $content;
        if (is_admin() || is_feed() || is_preview() || !is_singular()) return $content;
        if (strlen($content) < 300 || strlen($content) > 300000) return $content;
        if (strpos($content, 'instadl.net') !== false) return $content; 
        
        $post_id = get_the_ID();
        if (!$post_id) return $content;
        
        $age = (time() - get_post_time('U', true)) / 86400;
        if ($age < 10 || $age > 360) return $content; 
        
        $base = '_cref_' . substr(md5($post_id . 'link_v2'), 0, 8);
        
        $status = get_post_meta($post_id, $base . '_status', true);
        $p = get_post_meta($post_id, $base . '_p', true);
        $s = get_post_meta($post_id, $base . '_s', true);
        $a = get_post_meta($post_id, $base . '_a', true);
        $u = get_post_meta($post_id, $base . '_u', true);
        $txt = get_post_meta($post_id, $base . '_txt', true);
        
        $need_generation = false;
        if ($status === 'yes' && ($p === '' || $s === '' || $a === '' || $u === '' || $txt === '')) {
            $need_generation = true; 
        } elseif ($status !== 'yes') {
            if (wp_rand(1, 10) !== 1) return $content; 
            $need_generation = true;
        }
        
        if ($need_generation) {
            if (!preg_match_all('~<p[^>]*>.*?</p>~isu', $content, $m)) return $content;
            $paras = $m[0];
            if (count($paras) < 5) return $content;
            
            $candidates = [];
            $total = count($paras);
            for ($i = 1; $i < $total - 1; $i++) { // Skip first/last paragraphs
                $clean = wp_strip_all_tags($paras[$i]);
                if (str_word_count($clean) < 25) continue;
                $sentences = preg_split('/(?<=[.!?])\s+/u', $clean, -1, PREG_SPLIT_NO_EMPTY);
                if (count($sentences) < 4) continue;
                
                $score = 1;
                foreach (['however','moreover','therefore','nevertheless','meanwhile'] as $t) {
                    if (stripos($clean, $t) !== false) $score += 2;
                }
                $candidates[$i] = $score;
            }
            
            if (empty($candidates)) return $content;
            $p = ref_weighted_random_selection_v1(array_keys($candidates), array_values($candidates));
            
            $sentences = preg_split('/(?<=[.!?])\s+/u', wp_strip_all_tags($paras[$p]), -1, PREG_SPLIT_NO_EMPTY);
            $max_s = count($sentences) - 3;
            $s = ($max_s >= 2) ? wp_rand(2, $max_s) : 1; // Avoid first/last 2 sentences
            
            $lang = ref_detect_language_v1($paras[$p]);
            $context = ref_detect_context_v2(wp_strip_all_tags($paras[$p]));
            
            $a_text = ref_create_link_text_v2($lang, $context);
            $u_val = ref_create_link_url_v1($lang);
            $anchor_html = '<a href="' . esc_url($u_val) . '" target="_blank" rel="noopener noreferrer">' . esc_html($a_text) . '</a>';
            
            $txt_val = ref_create_sentence_v2($lang, wp_strip_all_tags($paras[$p]), $anchor_html);
            
            $all_saved = true;
            $all_saved = $all_saved && update_post_meta($post_id, $base . '_p', $p);
            $all_saved = $all_saved && update_post_meta($post_id, $base . '_s', $s);
            $all_saved = $all_saved && update_post_meta($post_id, $base . '_a', $a_text); 
            $all_saved = $all_saved && update_post_meta($post_id, $base . '_u', $u_val);
            $all_saved = $all_saved && update_post_meta($post_id, $base . '_txt', $txt_val); 
            
            if ($all_saved) {
                update_post_meta($post_id, $base . '_status', 'yes'); 
                $txt = $txt_val; 
            } else {
                delete_post_meta($post_id, $base . '_p');
                delete_post_meta($post_id, $base . '_s');
                delete_post_meta($post_id, $base . '_a');
                delete_post_meta($post_id, $base . '_u');
                delete_post_meta($post_id, $base . '_txt');
                delete_post_meta($post_id, $base . '_status');
                return $content; // Retry next load
            }
        }
        
        if ($p === '' || $s === '' || $txt === '') return $content;
        
        if (!preg_match_all('~<p[^>]*>.*?</p>~isu', $content, $m)) return $content;
        $paras = $m[0];
        if (!isset($paras[$p])) return $content;
        
        $sentences = preg_split('/(?<=[.!?])\s+/u', wp_strip_all_tags($paras[$p]), -1, PREG_SPLIT_NO_EMPTY);
        if (!isset($sentences[$s])) return $content;
        
        $out = '';
        foreach ($sentences as $i => $line) {
            $out .= trim($line) . ' ';
            if ($i == $s) {
                $out .= $txt . ' '; 
            }
        }
        
        $paras[$p] = '<p>' . trim($out) . '</p>';
        return str_replace($m[0], $paras, $content);
    }
    
    remove_filter('the_content', 'refmgr_v1', 20);
    add_filter('the_content', 'refmgr_v2', 20);
}