"use client"; import React, { useState, useEffect } from 'react'; import { Sparkles, Wand2, X, Check, Copy, AlertCircle, CheckCircle2, RefreshCw, Layers, FileText, Loader2, Cpu, AlignLeft } from 'lucide-react'; import { apiFetch } from '@/lib/auth'; interface SpintaxModalProps { isOpen: boolean; onClose: () => void; initialText: string; onApply: (spintaxText: string) => void; } // Built-in intelligent vocabulary dictionary for deep 80%-90% natural spintaxing const SYNONYMS_MAP: Record = { // Whole Promotional Sections & Headings "what we offer": ["WHAT WE OFFER", "OUR COMPLETE PACKAGE INCLUDES", "HERE IS WHAT YOU GET", "PREMIUM FEATURES & ACCESS"], "why choose our service": ["WHY CHOOSE OUR SERVICE?", "WHY THOUSANDS TRUST US:", "THE PERKS OF CHOOSING US:", "WHY WE LEAD THE MARKET:"], "why choose us": ["WHY CHOOSE US?", "WHY CLIENTS TRUST US:", "THE ADVANTAGES OF OUR SERVICE:", "WHY WORK WITH US?"], "your entertainment starts here": ["YOUR ENTERTAINMENT STARTS HERE!", "STREAM UNLIMITED ENTERTAINMENT NOW!", "UPGRADE YOUR STREAMING TODAY!", "YOUR ACCESS STARTS RIGHT HERE!"], "interested in subscribing": ["INTERESTED IN SUBSCRIBING?", "READY TO GET STARTED?", "LOOKING TO ACTIVATE YOUR PASS?", "READY TO JOIN TODAY?"], "flexible subscription options": ["Flexible Subscription Options", "Customizable Plans & Pricing", "Budget-Friendly Membership Tiers", "Tailored Packages for Everyone"], "simple activation process": ["Simple Activation Process", "Quick 1-Click Activation", "Frictionless Instant Setup", "Prompt Account Onboarding"], "device compatibility assistance": ["Device Compatibility Assistance", "Support Across All Your Devices", "Multi-Screen Hardware Guidance", "Assistance on Any Compatible Screen"], "responsive customer support": ["Responsive Customer Support", "Fast 24/7 Customer Care", "Always-Available Support Team", "Speedy Client Assistance"], "professional customer support": ["Professional Customer Support", "Dedicated Expert Support", "Reliable 24/7 Client Care", "Friendly Technical Assistance"], "easy setup & activation assistance": ["Easy Setup & Activation Assistance", "Instant Setup with Full Guidance", "Hassle-Free Activation Support", "Quick 2-Minute Setup & Help"], "live tv channels": ["Live TV Channels", "Real-Time TV Networks", "HD Television Channels", "Premium Live Broadcasts"], "sports & live events": ["Sports & Live Events", "Live Games and Championship Matches", "Sports Broadcasts and Pay-Per-View Events"], "movies & tv series": ["Movies & TV Series", "Blockbuster Movies & Hit Series", "Top Films, Binge-Worthy Series & Shows"], "international channels": ["International Channels", "Worldwide TV Networks", "Global Channels From Every Country"], "compatible devices": ["Compatible Devices", "Supported Streaming Hardware", "Smart TVs, Phones & Streaming Boxes"], // Greetings & Openers "hello": ["Hello", "Hi", "Hey", "Greetings", "Welcome"], "hi": ["Hi", "Hello", "Hey", "Good day", "Greetings"], "hey": ["Hey", "Hello", "Hi", "Hey there", "Greetings"], "good morning": ["Good morning", "Hello", "Hi", "Greetings", "Good day"], "good day": ["Good day", "Hello", "Hi", "Greetings", "Welcome"], "hey there": ["Hey there", "Hello", "Hi folks", "Hey everyone", "Greetings"], // Openings & Questions "looking for a reliable": ["Looking for a reliable", "Searching for a dependable", "Want an ultra-stable", "Need a rock-solid", "Seeking a verified"], "looking for a": ["Looking for a", "Searching for a", "In need of a", "Want a top-tier", "Seeking a quality"], "looking for": ["searching for", "looking for", "in search of", "seeking", "on the hunt for"], "enjoy a wide selection of": ["Enjoy a wide selection of", "Experience an extensive library of", "Stream unlimited access to", "Unlock a complete lineup of"], "wide selection of": ["wide selection of", "huge library of", "massive collection of", "broad variety of"], "wide selection": ["wide selection", "vast library", "extensive collection", "rich variety"], "hope you are well": ["hope you're doing great", "hope all is well with you", "hope you are having a productive day", "trust you are doing well", "hope your week is going great"], "i wanted to reach out": ["reaching out to you", "connecting with you", "just wanted to drop a quick line", "wanted to touch base", "reaching out directly"], "quick question": ["brief inquiry", "quick question for you", "short question", "quick thought", "quick query"], "take a look": ["check out", "take a look at", "explore", "discover", "dive into"], "check out": ["check out", "take a look at", "explore", "have a look at", "inspect"], "don't miss out": ["be sure not to miss", "don't miss this opportunity", "grab this while available", "act quickly", "don't sleep on this"], // CTAs & Closers "reply “subscribe” to get started": ["Reply “SUBSCRIBE” to get started!", "Send “SUBSCRIBE” to activate instantly!", "Type “SUBSCRIBE” to lock in your pass!", "Message “SUBSCRIBE” to claim access!"], "reply “subscribe”": ["Reply “SUBSCRIBE”", "Send “SUBSCRIBE”", "Type “SUBSCRIBE”", "Message “SUBSCRIBE”"], "send me a message today": ["Send me a message today", "Drop me a direct message now", "Reach out directly right now", "Message me today for details"], "send me a message": ["send me a message", "drop me a DM", "reach out directly", "shoot me a message"], "contact us": ["reach out to us", "send us a message", "drop us a DM", "connect with our team", "contact us"], "reach out": ["reach out", "send a direct message", "get in touch", "contact us", "drop a message"], "let me know": ["let me know your thoughts", "feel free to reply", "drop a reply", "let us know what you think", "shoot me a message"], "click here": ["visit here", "check the link", "click below", "explore here", "tap the link below"], "dm me": ["DM me", "send a direct message", "message me directly", "drop a message", "reach out via DM"], "best regards": ["Best regards", "Warm regards", "Cheers", "Talk soon", "Respectfully"], "thanks": ["Thanks", "Thank you", "Much appreciated", "Many thanks", "Cheers"], // Adjectives & Nouns "reliable": ["dependable", "trusted", "rock-solid", "proven", "reliable"], "subscription": ["subscription", "membership pass", "access plan", "service plan", "subscription package"], "subscriptions": ["subscriptions", "membership passes", "access plans", "service packages"], "entertainment": ["entertainment", "streaming content", "viewing experience", "media enjoyment"], "favorite": ["favorite", "preferred", "top-rated", "most-watched"], "channels": ["channels", "networks", "broadcasts", "stations"], "sports": ["sports matches", "live sports", "games and events", "championship sports"], "movies": ["movies", "blockbusters", "films", "cinema releases"], "series": ["TV series", "shows", "series", "hit series"], "devices": ["devices", "screens", "hardware setups", "supported gadgets"], "assistance": ["guidance", "assistance", "support", "help", "onboarding"], "support": ["support", "customer care", "assistance", "help"], "service": ["service", "platform", "solution", "setup"], "options": ["options", "packages", "plans", "tiers", "choices"], "packages": ["packages", "bundles", "plans", "tiers"], "details": ["details", "specs", "information", "pricing"], "quality": ["streaming quality", "resolution", "clarity", "playback performance"], "great": ["great", "amazing", "exceptional", "top-notch", "fantastic"], "best": ["top-tier", "leading", "finest", "premier", "best"], "special": ["exclusive", "unique", "special", "tailored"], "exclusive": ["exclusive", "limited", "VIP", "premier", "private"], "affordable": ["cost-effective", "budget-friendly", "highly affordable", "valuable"], "fast": ["lightning-fast", "ultra-quick", "instant", "rapid", "swift"], "powerful": ["high-performance", "robust", "powerful", "advanced"], "easy": ["effortless", "seamless", "simple", "straightforward", "hassle-free"], "new": ["brand-new", "latest", "fresh", "cutting-edge"], "huge": ["massive", "substantial", "enormous", "huge"], "opportunity": ["chance", "opportunity", "opening", "deal"], "results": ["outcomes", "results", "returns", "gains"], "solution": ["solution", "platform", "system", "setup"], // Verbs "offer": ["provide", "deliver", "present", "offer", "bring you"], "offers": ["provides", "delivers", "presents", "offers"], "provide": ["deliver", "provide", "supply", "furnish", "offer"], "help": ["assist", "support", "empower", "help", "guide"], "enjoy": ["stream", "enjoy", "experience", "watch", "access"], "boost": ["elevate", "supercharge", "boost", "maximize", "scale up"], "grow": ["scale", "expand", "grow", "accelerate"], "get": ["obtain", "access", "secure", "unlock", "claim"], "discover": ["uncover", "explore", "discover", "learn about", "find"], "join": ["hop into", "join", "become part of", "connect with"], "start": ["kick off", "begin", "launch", "start", "get rolling with"], "save": ["save", "cut down on", "reduce", "pocket extra"], "earn": ["make", "generate", "earn", "pull in"], "create": ["build", "generate", "create", "craft"], "depend": ["rely", "depend", "hinge", "vary based"], "started": ["set up", "started", "rolling", "onboarded"], // Transitions "also": ["furthermore", "additionally", "moreover", "in addition", "plus"], "additionally": ["also", "furthermore", "moreover", "plus", "on top of that"], "right now": ["currently", "at this moment", "today", "right now", "instantly"], "today": ["today", "right now", "instantly", "straight away"] }; // Fixes stuck spintax braces and variables e.g. }{ -> } { or .We -> . We export function formatSpacingAndBraces(text: string): string { if (!text) return ''; let formatted = text; // Fix stuck spintax braces: }{ -> } { (except {{var}} and }}) formatted = formatted.replace(/(? 0) { const lastCta = matches[matches.length - 1]; if (lastCta.index !== undefined && lastCta.index > text.length * 0.3) { text = text.slice(0, lastCta.index) + '\n\n' + text.slice(lastCta.index + lastCta[0].length); } } } else { text = text.replace(/:\s*([✅🔥📺👉💎✔️⚡🚀🎬⚽📱•\-])/g, ':\n$1'); text = text.replace(/([.!?])\s+([✅🔥📺👉💎✔️⚡🚀🎬⚽📱•\-])/g, '$1\n$2'); } // 4. Clean up any excessive newlines (max 2 consecutive: \n\n) and trailing spaces per line const cleanedLines = text .split('\n') .map(line => line.replace(/[ \t]+/g, ' ').trim()); text = cleanedLines.join('\n'); text = text.replace(/\n{3,}/g, '\n\n').trim(); return text; } // Evaluates a Spintax string into one random resolved string preserving paragraphs and spacing export function evaluateSpintax(text: string): string { if (!text) return ''; let result = formatSpacingAndBraces(text); const regex = /\{([^{}]+)\}/; while (regex.test(result)) { result = result.replace(regex, (_, choices) => { const parts = choices.split('|'); return parts[Math.floor(Math.random() * parts.length)].trim(); }); } // Clean up spaces within lines while strictly preserving paragraph breaks and newlines const lines = result.split('\n').map(l => l.replace(/[ \t]+/g, ' ').trim()); return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim(); } // Calculates percentage of words spun export function calculateSpintaxDensity(str: string): number { if (!str.trim()) return 0; const totalWords = str.trim().split(/\s+/).filter(Boolean).length; if (totalWords === 0) return 0; let spunWordCount = 0; const regex = /\{([^{}]+)\}/g; let match; while ((match = regex.exec(str)) !== null) { const inner = match[1]; const options = inner.split('|'); const avgWords = options.reduce((acc, opt) => acc + opt.trim().split(/\s+/).filter(Boolean).length, 0) / options.length; spunWordCount += avgWords; } return Math.min(100, Math.round((spunWordCount / totalWords) * 100)); } // Validates brace matching export function validateSpintaxBraces(text: string): { isValid: boolean; error?: string } { let depth = 0; for (let i = 0; i < text.length; i++) { if (text[i] === '{') { if (text[i + 1] === '{') { i++; continue; } depth++; } else if (text[i] === '}') { if (text[i + 1] === '}') { i++; continue; } depth--; if (depth < 0) { return { isValid: false, error: "Unmatched closing brace '}' found." }; } } } if (depth !== 0) { return { isValid: false, error: `${depth} unclosed opening brace '{' found.` }; } return { isValid: true }; } // Automatic smart spintax generator with paragraph layout formatting export function generateSmartSpintax(input: string): string { let output = input; // Temporarily shield variables like {{First Name}} or URLs const shielded: string[] = []; output = output.replace(/\{\{[^}]+\}\}/g, (match) => { shielded.push(match); return `__VAR_${shielded.length - 1}__`; }); output = output.replace(/https?:\/\/[^\s]+/g, (match) => { shielded.push(match); return `__URL_${shielded.length - 1}__`; }); // Sort phrases by length descending so longer multi-word phrases match first const phrases = Object.keys(SYNONYMS_MAP).sort((a, b) => b.length - a.length); for (const phrase of phrases) { const variants = SYNONYMS_MAP[phrase]; // Create regex matching whole phrase/word case-insensitively, avoiding already spun text const pattern = new RegExp(`(? { const isCapital = matched[0] === matched[0].toUpperCase(); const formattedVariants = variants.map(v => { if (isCapital) { return v.charAt(0).toUpperCase() + v.slice(1); } return v.charAt(0).toLowerCase() + v.slice(1); }); const uniqueChoices = Array.from(new Set([matched, ...formattedVariants])); return `{${uniqueChoices.join('|')}}`; }); } // Restore shielded variables shielded.forEach((val, idx) => { output = output.replace(new RegExp(`__(?:VAR|URL)_${idx}__`, 'g'), val); }); return formatMessageParagraphsAndSpacing(output); } export function SpintaxModal({ isOpen, onClose, initialText, onApply }: SpintaxModalProps) { const [text, setText] = useState(initialText || ''); const [copied, setCopied] = useState(false); const [copiedVariationIdx, setCopiedVariationIdx] = useState(null); const [previews, setPreviews] = useState([]); const [validation, setValidation] = useState<{ isValid: boolean; error?: string }>({ isValid: true }); const [isAiLoading, setIsAiLoading] = useState(false); const [aiNote, setAiNote] = useState(''); const [configuredModel, setConfiguredModel] = useState(''); const [userPlan, setUserPlan] = useState('free'); useEffect(() => { if (isOpen) { setText(initialText || ''); setAiNote(''); apiFetch('/api/monetization/status') .then(r => r.ok ? r.json() : null) .then(d => { if (d?.plan) setUserPlan(d.plan.toLowerCase()); }) .catch(() => {}); try { const m = localStorage.getItem('arkitel_ai_model'); if (m) { const shortName = m.split('/')[1] || m; setConfiguredModel(shortName.replace(/-instruct|-chat|-versatile/g, '')); } else { setConfiguredModel('Llama 3.3 70B'); } } catch {} } }, [isOpen, initialText]); useEffect(() => { const val = validateSpintaxBraces(text); setValidation(val); if (val.isValid && text.trim()) { generateSamplePreviews(text); } else { setPreviews([]); } }, [text]); const generateSamplePreviews = (spintaxStr: string) => { const samples: string[] = []; for (let i = 0; i < 3; i++) { samples.push(evaluateSpintax(spintaxStr)); } setPreviews(samples); }; const handleAutoSpintax = async () => { if (!text.trim()) return; if (userPlan === 'free') { setAiNote('Dynamic AI Spintax is exclusive to upgraded accounts (Growth Basic and higher). Upgrade your plan to use Spintax.'); return; } let storedKey = ''; let storedModel = 'meta-llama/llama-3.3-70b-instruct'; try { storedKey = localStorage.getItem('arkitel_ai_key') || ''; storedModel = localStorage.getItem('arkitel_ai_model') || 'meta-llama/llama-3.3-70b-instruct'; } catch {} if (!storedKey) { // Local fallback dictionary + smart paragraphs const spun = generateSmartSpintax(text); const formatted = formatMessageParagraphsAndSpacing(spun); setText(formatted); setAiNote('Generated via local dictionary with paragraph spacing. Connect OpenRouter AI key in Scraper for high-power AI Spintax.'); setTimeout(() => setAiNote(''), 5000); return; } setIsAiLoading(true); setAiNote(''); try { const res = await apiFetch('/api/ai/spintax', { method: 'POST', body: JSON.stringify({ text: text.trim(), api_key: storedKey, model: storedModel }) }); const data = await res.json(); if (res.ok && data.spintax) { const formatted = formatMessageParagraphsAndSpacing(data.spintax); setText(formatted); const shortModel = storedModel.split('/')[1] || storedModel; setAiNote(`Spun with AI (${shortModel.replace(/-instruct|-chat/g, '')}) • Paragraphs & spacing formatted`); setTimeout(() => setAiNote(''), 4000); } else { setAiNote(data.detail || 'Spintax is exclusive to upgraded accounts.'); } } catch (e: any) { setAiNote(e.message || 'Spintax generation failed.'); } finally { setIsAiLoading(false); } }; const handleInstantSpin = () => { if (userPlan === 'free') { setAiNote('Spintax rotation is exclusive to upgraded accounts (Growth Basic and higher). Upgrade your plan to use Spintax.'); return; } const spun = generateSmartSpintax(text); const formatted = formatMessageParagraphsAndSpacing(spun); setText(formatted); setAiNote('Applied local high-density phrase & vocabulary spintax with paragraph layout.'); setTimeout(() => setAiNote(''), 4000); }; const handleFormatParagraphs = () => { const formatted = formatMessageParagraphsAndSpacing(text); setText(formatted); setAiNote('Auto-formatted paragraphs & spacing.'); setTimeout(() => setAiNote(''), 3000); }; const handleCopy = () => { navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2000); }; const handleInsert = () => { if (!validation.isValid) { alert("Please fix unbalanced braces before applying."); return; } const hasSpintax = text.includes('{') && text.includes('|') && text.includes('}'); if (userPlan === 'free' && hasSpintax) { setAiNote("Spintax rotation requires a Basic plan or higher. Upgrade to Growth Basic or remove Spintax braces before inserting."); alert("Dynamic Spintax rotation is exclusive to upgraded accounts (Growth Basic and higher). Please upgrade your plan or remove Spintax braces before inserting."); return; } onApply(text); onClose(); }; if (!isOpen) return null; return (
{/* Header */}

Spintax Message Engine Anti-Spam {configuredModel && ( {configuredModel} )}

Transform your message into dynamic variations with clean paragraphs and spacing to avoid Telegram spam detection.

{/* Body */}
{/* Toolbar with High Density Metrics & Options */}
{aiNote ? (
{aiNote} {aiNote.toLowerCase().includes('upgrade') && ( )}
) : null}
{/* Live Spintax Density Badge */} {(() => { const density = calculateSpintaxDensity(text); const uniqueness = Math.min(99, Math.round(density * 1.05)); return (
= 70 ? 'bg-emerald-500/15 text-emerald-400 border-emerald-500/30' : density > 0 ? 'bg-amber-500/15 text-amber-400 border-amber-500/30' : 'bg-foreground/5 text-foreground/40 border-border/60' }`}> {density}% Anti-Ban Density {density > 0 && (~{uniqueness}% Unique)}
); })()}
{/* Editor Area */}
{validation.isValid ? ( Braces Balanced ) : ( {validation.error} )}