Spaces:
Paused
Paused
CBV01
feat: complete package entitlements enforcement, database telemetry tracking, coupon reversion, and verification desk redesign
aa58c7d Download frontend/src/components/SpintaxModal.tsx from adekolateam/arkitel: direct link, hf CLI and curl.
- Browser
- Download file 41.5 kB
-
https://huggingface.co/spaces/adekolateam/arkitel/resolve/main/frontend/src/components/SpintaxModal.tsx
- Command line
-
hf download hf://spaces/adekolateam/arkitel/frontend/src/components/SpintaxModal.tsx
-
curl -L -o SpintaxModal.tsx https://huggingface.co/spaces/adekolateam/arkitel/resolve/main/frontend/src/components/SpintaxModal.tsx
41.5 kB
| "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<string, string[]> = { | |
| // 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(/(?<!\})\}(?![\s.,!?;:)}\]\n\r])(?!\})/g, '} '); | |
| formatted = formatted.replace(/(?<![\s\n\r{(])(?<!\{)\{(?!\{)/g, ' {'); | |
| formatted = formatted.replace(/\}\}([a-zA-Z0-9])/g, '}} $1'); | |
| formatted = formatted.replace(/([a-zA-Z0-9])\{\{/g, '$1 {{'); | |
| // Fix punctuation followed immediately by capital letter or { without space | |
| formatted = formatted.replace(/([.!?])([A-Z{])/g, '$1 $2'); | |
| formatted = formatted.replace(/([,:])([a-zA-Z{])/g, '$1 $2'); | |
| return formatted; | |
| } | |
| // Intelligently formats messages into clean, readable paragraphs with double line breaks | |
| export function formatMessageParagraphsAndSpacing(raw: string): string { | |
| if (!raw || !raw.trim()) return ''; | |
| let text = raw.trim(); | |
| // 1. Fix stuck spintax braces & variables | |
| text = formatSpacingAndBraces(text); | |
| // 2. Normalize single carriage returns to standard newlines | |
| text = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); | |
| // 3. Intelligently add paragraph breaks if the text is compressed or lacking clear paragraphs | |
| const hasExistingParagraphs = text.includes('\n\n'); | |
| if (!hasExistingParagraphs) { | |
| // A. Separate greeting/opener into its own initial paragraph: | |
| // Matches: "Hello {{First Name}},", "{Hello|Hi|Hey} {{First Name}},", "Hey everyone!", etc. | |
| text = text.replace( | |
| /^(\s*(?:\b(?:Hello|Hi|Hey|Greetings|Welcome|Hey there|Good day|Good morning)\b|\{[^{}]+\}|\{\{[^}]+\}\})[^\n.!?:]*?[.,!?:])(\s+)/i, | |
| '$1\n\n' | |
| ); | |
| // B. Break after questions (natural conversational hook transition) | |
| text = text.replace(/(\?)\s+([A-Z{])/g, '$1\n\n$2'); | |
| // C. If colon is followed by bullet/emoji, break onto newline | |
| text = text.replace(/:\s*([✅🔥📺👉💎✔️⚡🚀🎬⚽📱•\-])/g, ':\n$1'); | |
| // D. Put emoji-based bullet points or highlights on their own lines: | |
| text = text.replace(/([.!?])\s+([✅🔥📺👉💎✔️⚡🚀🎬⚽📱•\-])/g, '$1\n\n$2'); | |
| text = text.replace(/([^\n])\s+([✅🔥📺👉💎✔️⚡🚀🎬⚽📱•\-])\s+/g, '$1\n$2 '); | |
| // E. Put prominent headings on their own lines: | |
| text = text.replace(/([.!?])\s+(\{?[A-Z0-9\s&]{4,30}\}?:\s*)/g, '$1\n\n$2\n'); | |
| // F. Separate Call-to-Action (CTA) / Closer into its own paragraph at the end: | |
| const ctaPattern = /(\s+)(?=(\{[^{}]*?(?:reply|send|type|message|dm|contact|click|visit|join|grab)[^{}]*?\}|\b(?:reply|send|type|message|drop a dm|contact us|reach out|click below|click here|dm me|dm us|message us|join now|visit link)\b))/gi; | |
| const matches = Array.from(text.matchAll(ctaPattern)); | |
| if (matches.length > 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(`(?<!\\{)(?<!\\|)\\b${phrase.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b(?!\\|)(?!\\})`, 'gi'); | |
| output = output.replace(pattern, (matched) => { | |
| 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<number | null>(null); | |
| const [previews, setPreviews] = useState<string[]>([]); | |
| 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<string>('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 ( | |
| <div className="fixed inset-0 bg-background/80 backdrop-blur-3xl z-[250] flex items-center justify-center p-4 animate-in fade-in duration-200"> | |
| <div className="bg-card border border-border/90 rounded-[28px] w-full max-w-2xl shadow-2xl overflow-hidden flex flex-col max-h-[92vh] animate-in zoom-in-95 duration-200"> | |
| {/* Header */} | |
| <div className="p-5 px-6 border-b border-border/60 flex items-center justify-between bg-foreground/[0.02]"> | |
| <div className="flex items-center gap-3"> | |
| <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center text-white shadow-lg shadow-indigo-500/20"> | |
| <Sparkles size={18} /> | |
| </div> | |
| <div> | |
| <h3 className="font-bold text-base text-foreground tracking-tight flex items-center gap-2"> | |
| Spintax Message Engine | |
| <span className="text-[10px] font-black uppercase tracking-wider px-2 py-0.5 rounded-full bg-indigo-500/10 text-indigo-400 border border-indigo-500/20"> | |
| Anti-Spam | |
| </span> | |
| {configuredModel && ( | |
| <span className="text-[10px] font-mono font-bold px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 flex items-center gap-1"> | |
| <Cpu size={10} /> | |
| {configuredModel} | |
| </span> | |
| )} | |
| </h3> | |
| <p className="text-xs text-foreground/50 font-medium"> | |
| Transform your message into dynamic variations with clean paragraphs and spacing to avoid Telegram spam detection. | |
| </p> | |
| </div> | |
| </div> | |
| <button | |
| onClick={onClose} | |
| className="p-2 rounded-xl text-foreground/40 hover:text-foreground hover:bg-foreground/5 transition-colors cursor-pointer" | |
| > | |
| <X size={18} /> | |
| </button> | |
| </div> | |
| {/* Body */} | |
| <div className="p-6 overflow-y-auto space-y-5 custom-scrollbar flex-1"> | |
| {/* Toolbar with High Density Metrics & Options */} | |
| <div className="flex flex-wrap items-center justify-between gap-2.5 bg-foreground/[0.03] p-2.5 rounded-2xl border border-border/60"> | |
| <div className="flex items-center gap-2 flex-wrap"> | |
| <button | |
| type="button" | |
| onClick={handleAutoSpintax} | |
| disabled={isAiLoading || !text.trim()} | |
| className="px-3.5 py-1.5 rounded-xl bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 disabled:opacity-50 text-white text-xs font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95 cursor-pointer" | |
| title="Enrich message variations with your configured OpenRouter model with clean paragraph structure" | |
| > | |
| {isAiLoading ? ( | |
| <> | |
| <Loader2 size={13} className="animate-spin" /> | |
| <span>AI Deep-Spinning...</span> | |
| </> | |
| ) : ( | |
| <> | |
| <Wand2 size={13} /> | |
| <span>AI Deep-Spin (85%+)</span> | |
| </> | |
| )} | |
| </button> | |
| <button | |
| type="button" | |
| onClick={handleInstantSpin} | |
| disabled={!text.trim()} | |
| className="px-3 py-1.5 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground/80 hover:text-foreground text-xs font-bold border border-border/70 transition-all flex items-center gap-1.5 active:scale-95 cursor-pointer" | |
| title="Instantly spin common phrases, headlines, headings, and keywords locally" | |
| > | |
| <RefreshCw size={12} className="text-indigo-400" /> | |
| <span>Instant Spin</span> | |
| </button> | |
| <button | |
| type="button" | |
| onClick={handleFormatParagraphs} | |
| disabled={!text.trim()} | |
| className="px-3 py-1.5 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground/80 hover:text-foreground text-xs font-bold border border-border/70 transition-all flex items-center gap-1.5 active:scale-95 cursor-pointer" | |
| title="Intelligently format into clean paragraphs with double line breaks and proper spacing" | |
| > | |
| <AlignLeft size={12} className="text-indigo-400" /> | |
| <span>Format Paragraphs</span> | |
| </button> | |
| {aiNote ? ( | |
| <div className="flex flex-wrap items-center gap-2"> | |
| <span className={`text-[11px] font-semibold px-2 animate-in fade-in ${aiNote.toLowerCase().includes('upgrade') || aiNote.toLowerCase().includes('locked') ? 'text-amber-400' : 'text-emerald-400'}`}> | |
| {aiNote} | |
| </span> | |
| {aiNote.toLowerCase().includes('upgrade') && ( | |
| <button | |
| type="button" | |
| onClick={() => { | |
| onClose(); | |
| window.dispatchEvent(new CustomEvent('open_upgrade_modal')); | |
| }} | |
| className="px-2.5 py-1 rounded-lg bg-indigo-500 hover:bg-indigo-400 text-white font-bold text-[10px] shadow-sm transition-all cursor-pointer" | |
| > | |
| Upgrade Plan | |
| </button> | |
| )} | |
| </div> | |
| ) : null} | |
| </div> | |
| {/* Live Spintax Density Badge */} | |
| {(() => { | |
| const density = calculateSpintaxDensity(text); | |
| const uniqueness = Math.min(99, Math.round(density * 1.05)); | |
| return ( | |
| <div className="flex items-center gap-1.5"> | |
| <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full border flex items-center gap-1 ${ | |
| density >= 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' | |
| }`}> | |
| <Sparkles size={10} /> | |
| <span>{density}% Anti-Ban Density</span> | |
| {density > 0 && <span className="font-mono text-[9px] opacity-80">(~{uniqueness}% Unique)</span>} | |
| </span> | |
| </div> | |
| ); | |
| })()} | |
| </div> | |
| {/* Editor Area */} | |
| <div className="space-y-1.5"> | |
| <div className="flex justify-between items-center px-1"> | |
| <label className="text-[11px] font-bold text-foreground/40 uppercase tracking-wider"> | |
| Spintax Message Text | |
| </label> | |
| <div className="flex items-center gap-2"> | |
| {validation.isValid ? ( | |
| <span className="inline-flex items-center gap-1 text-[10px] font-bold text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded-md border border-emerald-500/20"> | |
| <CheckCircle2 size={11} /> Braces Balanced | |
| </span> | |
| ) : ( | |
| <span className="inline-flex items-center gap-1 text-[10px] font-bold text-rose-400 bg-rose-500/10 px-2 py-0.5 rounded-md border border-rose-500/20"> | |
| <AlertCircle size={11} /> {validation.error} | |
| </span> | |
| )} | |
| </div> | |
| </div> | |
| <textarea | |
| rows={7} | |
| value={text} | |
| onChange={(e) => setText(e.target.value)} | |
| placeholder="Enter or paste message here. E.g. {Hello|Hi|Hey} {{First Name}}, {check out|take a look at} our {exclusive|top-tier} services!" | |
| className="w-full bg-input border border-border/80 rounded-2xl p-3.5 text-xs text-foreground placeholder:text-foreground/30 focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all leading-relaxed font-mono whitespace-pre-wrap" | |
| /> | |
| <p className="text-[10px] text-foreground/40 px-1"> | |
| Paragraphs (double line breaks), bullet points, and spacing are automatically preserved when rotating variations. | |
| </p> | |
| </div> | |
| {/* Live Preview Samples */} | |
| {previews.length > 0 && ( | |
| <div className="space-y-2.5"> | |
| <div className="flex items-center justify-between px-1"> | |
| <span className="text-[11px] font-bold text-foreground/40 uppercase tracking-wider flex items-center gap-1.5"> | |
| <Layers size={12} className="text-indigo-400" /> | |
| Live Resolved Variations ({previews.length} samples) | |
| </span> | |
| <button | |
| type="button" | |
| onClick={() => generateSamplePreviews(text)} | |
| className="text-[10px] font-bold text-indigo-400 hover:text-indigo-300 flex items-center gap-1 transition-colors cursor-pointer" | |
| > | |
| <RefreshCw size={10} /> Reroll Previews | |
| </button> | |
| </div> | |
| <div className="space-y-3"> | |
| {previews.map((preview, i) => ( | |
| <div | |
| key={i} | |
| className="p-3.5 bg-foreground/[0.02] hover:bg-foreground/[0.035] border border-border/60 hover:border-indigo-500/30 rounded-xl text-xs text-foreground/85 leading-relaxed font-sans transition-all group" | |
| > | |
| <div className="flex items-center justify-between mb-2 pb-1.5 border-b border-border/40"> | |
| <div className="flex items-center gap-2"> | |
| <span className="text-[9px] font-black uppercase tracking-wider text-indigo-400 bg-indigo-500/10 px-2 py-0.5 rounded-md border border-indigo-500/20"> | |
| Variation {i + 1} | |
| </span> | |
| <span className="text-[10px] text-foreground/40 font-mono"> | |
| {preview.split(/\s+/).filter(Boolean).length} words • {preview.split('\n').filter(Boolean).length} lines | |
| </span> | |
| </div> | |
| <div className="flex items-center gap-1.5"> | |
| <button | |
| type="button" | |
| onClick={() => { | |
| navigator.clipboard.writeText(preview); | |
| setCopiedVariationIdx(i); | |
| setTimeout(() => setCopiedVariationIdx(null), 2000); | |
| }} | |
| className="px-2 py-0.5 rounded-md text-[10px] font-semibold bg-foreground/5 hover:bg-foreground/10 text-foreground/60 transition-colors flex items-center gap-1 cursor-pointer" | |
| title="Copy this variation" | |
| > | |
| {copiedVariationIdx === i ? <Check size={11} className="text-emerald-400" /> : <Copy size={11} />} | |
| <span>{copiedVariationIdx === i ? 'Copied' : 'Copy'}</span> | |
| </button> | |
| <button | |
| type="button" | |
| onClick={() => { | |
| onApply(preview); | |
| onClose(); | |
| }} | |
| className="px-2 py-0.5 rounded-md text-[10px] font-semibold bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 transition-colors flex items-center gap-1 cursor-pointer" | |
| title="Insert this resolved variation directly into campaign message" | |
| > | |
| <span>Use This</span> | |
| </button> | |
| </div> | |
| </div> | |
| <div className="whitespace-pre-wrap break-words text-foreground/85 leading-relaxed font-sans text-xs select-text"> | |
| {preview || <span className="italic text-foreground/30">Empty</span>} | |
| </div> | |
| </div> | |
| ))} | |
| </div> | |
| </div> | |
| )} | |
| </div> | |
| {/* Footer */} | |
| <div className="p-4 px-6 bg-foreground/[0.02] border-t border-border/60 flex items-center justify-between gap-3"> | |
| <button | |
| type="button" | |
| onClick={handleCopy} | |
| className="px-4 py-2.5 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground/70 text-xs font-semibold transition-all flex items-center gap-1.5" | |
| > | |
| {copied ? <Check size={14} className="text-emerald-400" /> : <Copy size={14} />} | |
| {copied ? 'Copied' : 'Copy Text'} | |
| </button> | |
| <div className="flex items-center gap-2"> | |
| <button | |
| type="button" | |
| onClick={onClose} | |
| className="px-4 py-2.5 rounded-xl bg-foreground/5 hover:bg-foreground/10 text-foreground/60 text-xs font-semibold transition-all" | |
| > | |
| Cancel | |
| </button> | |
| <button | |
| type="button" | |
| onClick={handleInsert} | |
| disabled={!validation.isValid || !text.trim()} | |
| className="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-xs font-bold transition-all shadow-md shadow-indigo-500/20 active:scale-95 flex items-center gap-1.5" | |
| > | |
| <Check size={14} /> Insert into Message | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| } | |