CBV01 commited on
Commit
b6d629c
·
1 Parent(s): b50b6c9

feat: purge AI thinking from keyword suggestions, wire AI model to Spintax, and add 5-variation AI Assistant modal

Browse files
backend/main.py CHANGED
@@ -3829,51 +3829,107 @@ async def admin_get_users(admin_id: str = Depends(get_current_admin)):
3829
 
3830
  _openrouter_models_cache = {"models": [], "timestamp": 0}
3831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3832
  def extract_keywords_from_ai_text(text: Optional[str]) -> List[str]:
3833
- """Robust parser for AI responses: handles JSON arrays, code fences, trailing commas, and list items."""
3834
  if not text or not isinstance(text, str):
3835
  return []
3836
 
3837
- # 1. Strip markdown code fences (```json ... ``` or ``` ... ```)
3838
- cleaned = re.sub(r'```(?:json)?', '', text).strip()
 
 
3839
  cleaned = cleaned.rstrip('`').strip()
3840
-
3841
- # 2. Try regex extraction of JSON array [ ... ]
3842
- match = re.search(r'\[[\s\S]*\]', cleaned)
3843
- if match:
3844
- array_str = match.group(0).strip()
3845
- try:
3846
- parsed = json.loads(array_str)
3847
- if isinstance(parsed, list):
3848
- return [str(x).strip() for x in parsed if x and str(x).strip()]
3849
- except Exception:
3850
- # Try cleaning trailing commas e.g. ["item1", "item2", ] -> ["item1", "item2" ]
3851
  try:
3852
- fixed = re.sub(r',\s*\]', ']', array_str)
3853
- parsed = json.loads(fixed)
3854
- if isinstance(parsed, list):
3855
- return [str(x).strip() for x in parsed if x and str(x).strip()]
 
 
 
 
 
3856
  except Exception:
3857
- pass
3858
-
3859
- # Extract double-quoted or single-quoted strings from the array slice
3860
- quoted = re.findall(r'"([^"\\]*(?:\\.[^"\\]*)*)"', array_str)
3861
- if quoted:
3862
- return [q.replace(r'\"', '"').strip() for q in quoted if q.strip()]
 
 
 
 
 
 
 
 
3863
 
3864
- # 3. Fallback: Parse line-by-line (e.g. numbered items '1. keyword' or bulleted '- keyword')
 
 
 
 
 
 
 
 
 
 
 
3865
  lines = cleaned.splitlines()
3866
  fallback_items: List[str] = []
3867
  for line in lines:
3868
- line = line.strip()
3869
- if not line:
3870
- continue
3871
- # Remove leading numbers, dots, hyphens, bullets
3872
- clean_line = re.sub(r'^(?:\d+[\.\)]|\-|\*|\•)\s*', '', line).strip()
3873
- clean_line = clean_line.strip('"\'`,')
3874
- if len(clean_line) >= 2 and not clean_line.startswith(('{', '}', '[', ']')):
3875
- fallback_items.append(clean_line)
3876
-
3877
  return fallback_items
3878
 
3879
  @app.get("/api/ai/openrouter-models")
@@ -4014,15 +4070,14 @@ async def suggest_ai_keywords(req: AISuggestRequest, user_id: str = Depends(get_
4014
 
4015
  async with httpx.AsyncClient(timeout=60.0) as client:
4016
  prompt = (
4017
- f"You are a Telegram search & community intelligence specialist. "
4018
- f"Generate exactly {target_count} unique, highly targeted, natural Telegram search keywords, "
4019
- f"community titles, phrases, and buyer/discussion terms for the niche: '{seed}'.\n"
4020
- f"Rules:\n"
4021
- f"1. Every single item MUST be completely unique and distinct. Absolute zero duplication or repetition.\n"
4022
- f"2. Every item must be a realistic term active Telegram groups, channels, and communities actually use in titles/usernames.\n"
4023
- f"3. Cover varied perspectives: popular discussion queries, group names, channels, locations/sub-niches, and services.\n"
4024
- f"4. Return ONLY a valid JSON array of strings, for example: [\"keyword 1\", \"keyword 2\", ...].\n"
4025
- f"5. Do NOT include any markdown code blocks, explanation, or preamble. Return raw JSON array only."
4026
  )
4027
 
4028
  try:
@@ -4031,7 +4086,8 @@ async def suggest_ai_keywords(req: AISuggestRequest, user_id: str = Depends(get_
4031
  "messages": [
4032
  {"role": "user", "content": prompt}
4033
  ],
4034
- "max_tokens": 4000
 
4035
  }
4036
  # Only pass temperature for non-reasoning models
4037
  if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
@@ -4089,12 +4145,12 @@ async def suggest_ai_keywords(req: AISuggestRequest, user_id: str = Depends(get_
4089
  clean_keywords: List[str] = []
4090
  seen = set()
4091
  for k in (ai_keywords or []):
4092
- if isinstance(k, str) and k.strip():
4093
- ks = k.strip().strip('"\'')
4094
- norm = ks.lower()
4095
- if norm not in seen and len(ks) >= 2:
4096
  seen.add(norm)
4097
- clean_keywords.append(ks)
4098
 
4099
  if not clean_keywords:
4100
  raise HTTPException(status_code=400, detail="AI returned an empty keyword list. Please try a different seed or model.")
@@ -4107,6 +4163,203 @@ async def suggest_ai_keywords(req: AISuggestRequest, user_id: str = Depends(get_
4107
  "model": selected_model
4108
  }
4109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4110
  @app.delete("/api/admin/users/{user_id}")
4111
  async def admin_delete_user(user_id: str, admin_id: str = Depends(get_current_admin)):
4112
  """Deletes a user and all their associated data from the system."""
 
3829
 
3830
  _openrouter_models_cache = {"models": [], "timestamp": 0}
3831
 
3832
+ META_FILTER_PHRASES = (
3833
+ "the user", "rule", "markdown", "preamble", "json array", "prompt", "telegram search",
3834
+ "duplication", "repetition", "i should", "way more than", "count them all", "constraint",
3835
+ "near-duplicate", "sub-niche", "discussion query", "here are", "example:", "buyer/discussion",
3836
+ "realistic term", "community title", "string or bytes", "output only", "unique and distinct",
3837
+ "absolute zero", "varies significantly", "structure significantly", "if i count"
3838
+ )
3839
+
3840
+ def _clean_keyword_item(text: str) -> str:
3841
+ """Cleans a single keyword string of quotes, numbering, bullets, and -unique tags."""
3842
+ if not text:
3843
+ return ""
3844
+ t = str(text).strip().strip('"\'`')
3845
+ # Remove leading numbering or bullets e.g. "1. ", "- ", "* "
3846
+ t = re.sub(r'^(?:\d+[\.\)]|\-|\*|\•)\s*', '', t).strip()
3847
+ # Remove trailing/leading '-unique', '- unique', 'unique:', '(unique)'
3848
+ t = re.sub(r'(?i)\s*[-_—]\s*unique\b', '', t)
3849
+ t = re.sub(r'(?i)\bunique\s*[-_—:]\s*', '', t)
3850
+ t = re.sub(r'(?i)\s*\(\s*unique\s*\)', '', t)
3851
+ return t.strip().strip('"\'`')
3852
+
3853
+ def _is_valid_keyword(text: str) -> bool:
3854
+ """Verifies that the string is a genuine, high-quality search keyword and not thought process/rules."""
3855
+ if not text or not isinstance(text, str):
3856
+ return False
3857
+ t = text.strip()
3858
+ if len(t) < 2 or len(t) > 65:
3859
+ return False
3860
+ if "\n" in t or "\r" in t:
3861
+ return False
3862
+ t_lower = t.lower()
3863
+ for phrase in META_FILTER_PHRASES:
3864
+ if phrase in t_lower:
3865
+ return False
3866
+ if t.startswith(("{", "}", "[", "]", "```", "#", "http://", "https://")):
3867
+ return False
3868
+ return True
3869
+
3870
  def extract_keywords_from_ai_text(text: Optional[str]) -> List[str]:
3871
+ """Robust parser that guarantees clean, usable Telegram keywords without thinking monologues or prompt repetition."""
3872
  if not text or not isinstance(text, str):
3873
  return []
3874
 
3875
+ # 1. Strip <think>...</think> and <thought>...</thought> tags completely
3876
+ cleaned = re.sub(r'<think>[\s\S]*?</think>', '', text, flags=re.IGNORECASE)
3877
+ cleaned = re.sub(r'<thought>[\s\S]*?</thought>', '', cleaned, flags=re.IGNORECASE)
3878
+ cleaned = re.sub(r'```(?:json)?', '', cleaned).strip()
3879
  cleaned = cleaned.rstrip('`').strip()
3880
+
3881
+ # 2. Extract JSON arrays. Search candidate [...] blocks starting from the last one (final answer)
3882
+ start_indices = [i for i, ch in enumerate(cleaned) if ch == '[']
3883
+ for start in reversed(start_indices):
3884
+ end = cleaned.rfind(']', start)
3885
+ if end != -1:
3886
+ slice_str = cleaned[start:end + 1].strip()
3887
+ # Try direct JSON parsing
 
 
 
3888
  try:
3889
+ parsed = json.loads(slice_str)
3890
+ if isinstance(parsed, list) and len(parsed) > 0:
3891
+ results = []
3892
+ for item in parsed:
3893
+ cleaned_item = _clean_keyword_item(str(item))
3894
+ if _is_valid_keyword(cleaned_item):
3895
+ results.append(cleaned_item)
3896
+ if len(results) >= 5:
3897
+ return results
3898
  except Exception:
3899
+ # Try fixing trailing commas e.g. ["item1", "item2", ]
3900
+ try:
3901
+ fixed = re.sub(r',\s*\]', ']', slice_str)
3902
+ parsed = json.loads(fixed)
3903
+ if isinstance(parsed, list) and len(parsed) > 0:
3904
+ results = []
3905
+ for item in parsed:
3906
+ cleaned_item = _clean_keyword_item(str(item))
3907
+ if _is_valid_keyword(cleaned_item):
3908
+ results.append(cleaned_item)
3909
+ if len(results) >= 5:
3910
+ return results
3911
+ except Exception:
3912
+ pass
3913
 
3914
+ # Extract quoted strings inside the bracketed slice
3915
+ quoted = re.findall(r'"([^"\\]*(?:\\.[^"\\]*)*)"', slice_str)
3916
+ if quoted:
3917
+ results = []
3918
+ for q in quoted:
3919
+ cleaned_q = _clean_keyword_item(q.replace(r'\"', '"'))
3920
+ if _is_valid_keyword(cleaned_q):
3921
+ results.append(cleaned_q)
3922
+ if len(results) >= 5:
3923
+ return results
3924
+
3925
+ # 3. Fallback: Parse line-by-line only if no JSON array was found, strictly filtering out meta lines
3926
  lines = cleaned.splitlines()
3927
  fallback_items: List[str] = []
3928
  for line in lines:
3929
+ cleaned_item = _clean_keyword_item(line)
3930
+ if _is_valid_keyword(cleaned_item):
3931
+ fallback_items.append(cleaned_item)
3932
+
 
 
 
 
 
3933
  return fallback_items
3934
 
3935
  @app.get("/api/ai/openrouter-models")
 
4070
 
4071
  async with httpx.AsyncClient(timeout=60.0) as client:
4072
  prompt = (
4073
+ f"You are a Telegram search & community intelligence specialist.\n"
4074
+ f"Generate exactly {target_count} unique, high-traffic, natural Telegram search keywords and channel queries for the niche: '{seed}'.\n\n"
4075
+ f"STRICT FORMAT RULES:\n"
4076
+ f"1. Return ONLY a single raw JSON array of clean keyword strings: [\"keyword 1\", \"keyword 2\", ...].\n"
4077
+ f"2. Every item must be 2 to 45 characters long, representing realistic search queries active users type on Telegram.\n"
4078
+ f"3. Do NOT include ANY thought process, reasoning, explanations, numbering, rules, or text outside the JSON array.\n"
4079
+ f"4. Do NOT append '-unique' or any metadata tags to the keywords.\n"
4080
+ f"5. Start your output directly with '[' and end with ']'."
 
4081
  )
4082
 
4083
  try:
 
4086
  "messages": [
4087
  {"role": "user", "content": prompt}
4088
  ],
4089
+ "max_tokens": 4000,
4090
+ "include_reasoning": False
4091
  }
4092
  # Only pass temperature for non-reasoning models
4093
  if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
 
4145
  clean_keywords: List[str] = []
4146
  seen = set()
4147
  for k in (ai_keywords or []):
4148
+ cleaned_k = _clean_keyword_item(k)
4149
+ if _is_valid_keyword(cleaned_k):
4150
+ norm = cleaned_k.lower()
4151
+ if norm not in seen:
4152
  seen.add(norm)
4153
+ clean_keywords.append(cleaned_k)
4154
 
4155
  if not clean_keywords:
4156
  raise HTTPException(status_code=400, detail="AI returned an empty keyword list. Please try a different seed or model.")
 
4163
  "model": selected_model
4164
  }
4165
 
4166
+ class AISpintaxRequest(BaseModel):
4167
+ text: str
4168
+ api_key: Optional[str] = None
4169
+ model: Optional[str] = None
4170
+
4171
+ @app.post("/api/ai/spintax")
4172
+ async def generate_ai_spintax(req: AISpintaxRequest, user_id: str = Depends(get_current_user_id)):
4173
+ """Transforms standard text into natural, anti-ban Spintax using the configured AI model."""
4174
+ input_text = (req.text or "").strip()
4175
+ if not input_text:
4176
+ raise HTTPException(status_code=400, detail="Text to spintax is required.")
4177
+
4178
+ key = (req.api_key or "").strip()
4179
+ selected_model = (req.model or "").strip() or "meta-llama/llama-3.3-70b-instruct"
4180
+
4181
+ if not key:
4182
+ raise HTTPException(
4183
+ status_code=400,
4184
+ detail="No OpenRouter API key provided. Please connect your AI Key in Scraper > AI Provider."
4185
+ )
4186
+
4187
+ prompt = (
4188
+ f"You are a Telegram outreach copy specialist and Spintax expert.\n"
4189
+ f"Convert the following text into professional, natural, high-variation Spintax format using {{option 1|option 2|option 3}} syntax.\n\n"
4190
+ f"Rules:\n"
4191
+ f"1. Add natural Spintax variations to greetings, calls-to-action, adjectives, and transition phrases.\n"
4192
+ f"2. Keep all tags like {{{{First Name}}}}, {{{{Group Name}}}}, {{{{Username}}}}, links, handles, or emojis intact!\n"
4193
+ f"3. Ensure all braces {{ }} and pipes | are 100% balanced and valid.\n"
4194
+ f"4. Do NOT output any markdown code blocks, explanation, or preamble. Return ONLY the raw spintaxed message.\n\n"
4195
+ f"Original Text:\n{input_text}"
4196
+ )
4197
+
4198
+ async with httpx.AsyncClient(timeout=45.0) as client:
4199
+ try:
4200
+ payload: Dict[str, Any] = {
4201
+ "model": selected_model,
4202
+ "messages": [{"role": "user", "content": prompt}],
4203
+ "max_tokens": 2500,
4204
+ "include_reasoning": False
4205
+ }
4206
+ if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
4207
+ payload["temperature"] = 0.7
4208
+
4209
+ res = await client.post(
4210
+ "https://openrouter.ai/api/v1/chat/completions",
4211
+ headers={
4212
+ "Authorization": f"Bearer {key}",
4213
+ "Content-Type": "application/json",
4214
+ "HTTP-Referer": "https://arkitel.com",
4215
+ "X-Title": "ArkiTel"
4216
+ },
4217
+ json=payload
4218
+ )
4219
+ if res.status_code == 200:
4220
+ data = res.json()
4221
+ choices = data.get("choices") or []
4222
+ if choices:
4223
+ msg = choices[0].get("message") or {}
4224
+ raw_spun = msg.get("content") or ""
4225
+ # Strip any think tags or code blocks
4226
+ raw_spun = re.sub(r'<think>[\s\S]*?</think>', '', raw_spun, flags=re.IGNORECASE)
4227
+ raw_spun = re.sub(r'```(?:spintax|text)?', '', raw_spun).strip('`').strip()
4228
+ if raw_spun:
4229
+ return {"spintax": raw_spun, "model": selected_model}
4230
+ raise HTTPException(status_code=400, detail="AI returned empty spintax text.")
4231
+ else:
4232
+ try:
4233
+ err_msg = res.json().get("error", {}).get("message") or res.text[:120]
4234
+ except Exception:
4235
+ err_msg = res.text[:120]
4236
+ raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error: {err_msg}")
4237
+ except HTTPException:
4238
+ raise
4239
+ except Exception as e:
4240
+ raise HTTPException(status_code=400, detail=f"AI Spintax failed: {str(e)}")
4241
+
4242
+ class AITemplateVariationsRequest(BaseModel):
4243
+ prompt: str
4244
+ api_key: Optional[str] = None
4245
+ model: Optional[str] = None
4246
+ include_spintax: Optional[bool] = True
4247
+ count: Optional[int] = 5
4248
+
4249
+ @app.post("/api/ai/generate-template-variations")
4250
+ async def generate_template_variations(req: AITemplateVariationsRequest, user_id: str = Depends(get_current_user_id)):
4251
+ """Generates 5 distinct high-converting Telegram template variations based on the user's instructions."""
4252
+ user_prompt = (req.prompt or "").strip()
4253
+ if not user_prompt:
4254
+ raise HTTPException(status_code=400, detail="Prompt/description is required.")
4255
+
4256
+ key = (req.api_key or "").strip()
4257
+ selected_model = (req.model or "").strip() or "meta-llama/llama-3.3-70b-instruct"
4258
+ target_count = max(3, min(10, req.count or 5))
4259
+ use_spintax = req.include_spintax if req.include_spintax is not None else True
4260
+
4261
+ if not key:
4262
+ raise HTTPException(
4263
+ status_code=400,
4264
+ detail="No OpenRouter API key provided. Please connect your AI Key in Scraper > AI Provider."
4265
+ )
4266
+
4267
+ spintax_rule = (
4268
+ "Incorporate natural Spintax variations {Option 1|Option 2|Option 3} in greetings, CTAs, and key phrases so each message can rotate dynamically."
4269
+ if use_spintax else "Write clean, direct copy without spintax."
4270
+ )
4271
+
4272
+ sys_prompt = (
4273
+ f"You are a master Telegram direct-outreach copywriter and conversion strategist.\n"
4274
+ f"A user wants to promote their channel, group, product, or service. Here is their description / offer:\n"
4275
+ f"'''\n{user_prompt}\n'''\n\n"
4276
+ f"Task:\n"
4277
+ f"Generate exactly {target_count} unique, high-converting Telegram message variations.\n"
4278
+ f"Cover diverse marketing angles:\n"
4279
+ f"- Variation 1: Direct Value & Clear Offer\n"
4280
+ f"- Variation 2: Curiosity & VIP / Exclusive Access\n"
4281
+ f"- Variation 3: Social Proof & Problem/Solution\n"
4282
+ f"- Variation 4: Quick Conversational Question / Soft Hook\n"
4283
+ f"- Variation 5: High Urgency & Time-Sensitive Perk\n\n"
4284
+ f"Rules:\n"
4285
+ f"1. {spintax_rule}\n"
4286
+ f"2. You can use supported personalization variables like {{{{First Name}}}} or {{{{Group Name}}}} where helpful.\n"
4287
+ f"3. Include call-to-actions, links or channel placeholders mentioned in user's prompt.\n"
4288
+ f"4. Return ONLY a valid JSON array of {target_count} strings: [\"Message 1...\", \"Message 2...\", ...].\n"
4289
+ f"5. Do NOT include markdown code fences, thought process, or explanations. Return pure JSON array only."
4290
+ )
4291
+
4292
+ async with httpx.AsyncClient(timeout=60.0) as client:
4293
+ try:
4294
+ payload: Dict[str, Any] = {
4295
+ "model": selected_model,
4296
+ "messages": [{"role": "user", "content": sys_prompt}],
4297
+ "max_tokens": 4000,
4298
+ "include_reasoning": False
4299
+ }
4300
+ if not any(om in selected_model.lower() for om in ("o1-", "o3-", "o1", "o3", "reasoner")):
4301
+ payload["temperature"] = 0.75
4302
+
4303
+ res = await client.post(
4304
+ "https://openrouter.ai/api/v1/chat/completions",
4305
+ headers={
4306
+ "Authorization": f"Bearer {key}",
4307
+ "Content-Type": "application/json",
4308
+ "HTTP-Referer": "https://arkitel.com",
4309
+ "X-Title": "ArkiTel"
4310
+ },
4311
+ json=payload
4312
+ )
4313
+ if res.status_code == 200:
4314
+ data = res.json()
4315
+ choices = data.get("choices") or []
4316
+ if choices:
4317
+ msg = choices[0].get("message") or {}
4318
+ raw_text = msg.get("content") or ""
4319
+ cleaned = re.sub(r'<think>[\s\S]*?</think>', '', raw_text, flags=re.IGNORECASE)
4320
+ cleaned = re.sub(r'```(?:json)?', '', cleaned).strip('`').strip()
4321
+
4322
+ # Parse JSON array
4323
+ start = cleaned.find('[')
4324
+ end = cleaned.rfind(']')
4325
+ variations = []
4326
+ if start != -1 and end != -1:
4327
+ try:
4328
+ parsed = json.loads(cleaned[start:end+1])
4329
+ if isinstance(parsed, list):
4330
+ variations = [str(x).strip() for x in parsed if str(x).strip()]
4331
+ except Exception:
4332
+ try:
4333
+ fixed = re.sub(r',\s*\]', ']', cleaned[start:end+1])
4334
+ parsed = json.loads(fixed)
4335
+ if isinstance(parsed, list):
4336
+ variations = [str(x).strip() for x in parsed if str(x).strip()]
4337
+ except Exception:
4338
+ pass
4339
+
4340
+ if not variations:
4341
+ blocks = re.split(r'\n(?=(?:Variation|\d+[\.\)]))\s*', cleaned)
4342
+ variations = [re.sub(r'^(?:Variation\s*\d+:?|\d+[\.\)])\s*', '', b).strip().strip('"\'') for b in blocks if len(b.strip()) > 20]
4343
+
4344
+ if variations:
4345
+ return {
4346
+ "variations": variations[:target_count],
4347
+ "total": len(variations[:target_count]),
4348
+ "model": selected_model
4349
+ }
4350
+
4351
+ raise HTTPException(status_code=400, detail="Could not parse message variations from AI response.")
4352
+ else:
4353
+ try:
4354
+ err_msg = res.json().get("error", {}).get("message") or res.text[:120]
4355
+ except Exception:
4356
+ err_msg = res.text[:120]
4357
+ raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error ({res.status_code}): {err_msg}")
4358
+ except HTTPException:
4359
+ raise
4360
+ except Exception as e:
4361
+ raise HTTPException(status_code=400, detail=f"AI generation failed: {str(e)}")
4362
+
4363
  @app.delete("/api/admin/users/{user_id}")
4364
  async def admin_delete_user(user_id: str, admin_id: str = Depends(get_current_admin)):
4365
  """Deletes a user and all their associated data from the system."""
frontend/src/app/campaigns/page.tsx CHANGED
@@ -33,6 +33,7 @@ import {
33
  import { apiFetch } from '@/lib/auth';
34
  import { Preloader } from '@/components/Preloader';
35
  import { SpintaxModal } from '@/components/SpintaxModal';
 
36
 
37
  export default function CampaignsPage() {
38
  const [isCreating, setIsCreating] = useState(false);
@@ -66,6 +67,7 @@ export default function CampaignsPage() {
66
  const [editingId, setEditingId] = useState<number | null>(null);
67
  const [creationError, setCreationError] = useState("");
68
  const [isSpintaxModalOpen, setIsSpintaxModalOpen] = useState(false);
 
69
 
70
  const [loadingTasks, setLoadingTasks] = useState(true);
71
  const [currentPage, setCurrentPage] = useState(1);
@@ -961,7 +963,15 @@ export default function CampaignsPage() {
961
  <label className="text-[11px] font-bold text-foreground/40 uppercase tracking-wider">
962
  Message Payload & Caption
963
  </label>
964
- <div className="flex items-center gap-2">
 
 
 
 
 
 
 
 
965
  <button
966
  type="button"
967
  onClick={() => setIsSpintaxModalOpen(true)}
@@ -1218,6 +1228,13 @@ export default function CampaignsPage() {
1218
  initialText={campaignData.message}
1219
  onApply={(spun) => setCampaignData(prev => ({ ...prev, message: spun }))}
1220
  />
 
 
 
 
 
 
 
1221
  </div>
1222
  );
1223
  }
 
33
  import { apiFetch } from '@/lib/auth';
34
  import { Preloader } from '@/components/Preloader';
35
  import { SpintaxModal } from '@/components/SpintaxModal';
36
+ import { TemplateAiAssistantModal } from '@/components/TemplateAiAssistantModal';
37
 
38
  export default function CampaignsPage() {
39
  const [isCreating, setIsCreating] = useState(false);
 
67
  const [editingId, setEditingId] = useState<number | null>(null);
68
  const [creationError, setCreationError] = useState("");
69
  const [isSpintaxModalOpen, setIsSpintaxModalOpen] = useState(false);
70
+ const [isAiAssistantOpen, setIsAiAssistantOpen] = useState(false);
71
 
72
  const [loadingTasks, setLoadingTasks] = useState(true);
73
  const [currentPage, setCurrentPage] = useState(1);
 
963
  <label className="text-[11px] font-bold text-foreground/40 uppercase tracking-wider">
964
  Message Payload & Caption
965
  </label>
966
+ <div className="flex items-center gap-1.5">
967
+ <button
968
+ type="button"
969
+ onClick={() => setIsAiAssistantOpen(true)}
970
+ className="px-2.5 py-1 rounded-md text-[10px] font-bold bg-gradient-to-r from-amber-500/15 to-orange-500/15 text-amber-300 border border-amber-500/30 hover:border-amber-400 hover:from-amber-500/25 hover:to-orange-500/25 transition-all flex items-center gap-1 cursor-pointer active:scale-95 shadow-sm shadow-amber-500/10"
971
+ title="Generate 5 high-converting message variations with AI"
972
+ >
973
+ <Sparkles size={11} className="text-amber-400" /> AI Assistant
974
+ </button>
975
  <button
976
  type="button"
977
  onClick={() => setIsSpintaxModalOpen(true)}
 
1228
  initialText={campaignData.message}
1229
  onApply={(spun) => setCampaignData(prev => ({ ...prev, message: spun }))}
1230
  />
1231
+
1232
+ {/* AI Assistant Modal */}
1233
+ <TemplateAiAssistantModal
1234
+ isOpen={isAiAssistantOpen}
1235
+ onClose={() => setIsAiAssistantOpen(false)}
1236
+ onSelectVariation={(content) => setCampaignData(prev => ({ ...prev, message: content }))}
1237
+ />
1238
  </div>
1239
  );
1240
  }
frontend/src/app/templates/page.tsx CHANGED
@@ -22,6 +22,7 @@ import {
22
  } from 'lucide-react';
23
  import { apiFetch } from '@/lib/auth';
24
  import { SpintaxModal } from '@/components/SpintaxModal';
 
25
 
26
  interface Template {
27
  id: number;
@@ -46,6 +47,7 @@ export default function TemplatesPage() {
46
  media_url: ''
47
  });
48
  const [isSpintaxModalOpen, setIsSpintaxModalOpen] = useState(false);
 
49
  const [mediaFile, setMediaFile] = useState<File | null>(null);
50
  const [mediaPreview, setMediaPreview] = useState<string>('');
51
  const [isUploading, setIsUploading] = useState(false);
@@ -502,14 +504,24 @@ export default function TemplatesPage() {
502
  <label className="text-[11px] font-bold text-foreground/40 uppercase tracking-wider ml-0.5">
503
  Message Content & Media Caption
504
  </label>
505
- <button
506
- type="button"
507
- onClick={() => setIsSpintaxModalOpen(true)}
508
- className="px-2.5 py-1 rounded-md text-[10px] font-bold bg-indigo-500/10 text-indigo-400 border border-indigo-500/25 hover:bg-indigo-500/20 transition-all flex items-center gap-1 cursor-pointer active:scale-95"
509
- title="Launch Spintax Message Assistant"
510
- >
511
- <Sparkles size={11} /> Spintax Message
512
- </button>
 
 
 
 
 
 
 
 
 
 
513
  </div>
514
  <textarea
515
  required
@@ -585,6 +597,19 @@ export default function TemplatesPage() {
585
  initialText={formData.content}
586
  onApply={(spun) => setFormData(prev => ({ ...prev, content: spun }))}
587
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
588
  </div>
589
  );
590
  }
 
22
  } from 'lucide-react';
23
  import { apiFetch } from '@/lib/auth';
24
  import { SpintaxModal } from '@/components/SpintaxModal';
25
+ import { TemplateAiAssistantModal } from '@/components/TemplateAiAssistantModal';
26
 
27
  interface Template {
28
  id: number;
 
47
  media_url: ''
48
  });
49
  const [isSpintaxModalOpen, setIsSpintaxModalOpen] = useState(false);
50
+ const [isAiAssistantOpen, setIsAiAssistantOpen] = useState(false);
51
  const [mediaFile, setMediaFile] = useState<File | null>(null);
52
  const [mediaPreview, setMediaPreview] = useState<string>('');
53
  const [isUploading, setIsUploading] = useState(false);
 
504
  <label className="text-[11px] font-bold text-foreground/40 uppercase tracking-wider ml-0.5">
505
  Message Content & Media Caption
506
  </label>
507
+ <div className="flex items-center gap-1.5">
508
+ <button
509
+ type="button"
510
+ onClick={() => setIsAiAssistantOpen(true)}
511
+ className="px-2.5 py-1 rounded-md text-[10px] font-bold bg-gradient-to-r from-amber-500/15 to-orange-500/15 text-amber-300 border border-amber-500/30 hover:border-amber-400 hover:from-amber-500/25 hover:to-orange-500/25 transition-all flex items-center gap-1 cursor-pointer active:scale-95 shadow-sm shadow-amber-500/10"
512
+ title="Generate 5 high-converting message variations with AI"
513
+ >
514
+ <Sparkles size={11} className="text-amber-400" /> AI Assistant
515
+ </button>
516
+ <button
517
+ type="button"
518
+ onClick={() => setIsSpintaxModalOpen(true)}
519
+ className="px-2.5 py-1 rounded-md text-[10px] font-bold bg-indigo-500/10 text-indigo-400 border border-indigo-500/25 hover:bg-indigo-500/20 transition-all flex items-center gap-1 cursor-pointer active:scale-95"
520
+ title="Launch Spintax Message Assistant"
521
+ >
522
+ <Sparkles size={11} /> Spintax Message
523
+ </button>
524
+ </div>
525
  </div>
526
  <textarea
527
  required
 
597
  initialText={formData.content}
598
  onApply={(spun) => setFormData(prev => ({ ...prev, content: spun }))}
599
  />
600
+
601
+ {/* AI Assistant Modal */}
602
+ <TemplateAiAssistantModal
603
+ isOpen={isAiAssistantOpen}
604
+ onClose={() => setIsAiAssistantOpen(false)}
605
+ onSelectVariation={(content, suggestedTitle) => {
606
+ setFormData(prev => ({
607
+ ...prev,
608
+ content,
609
+ name: prev.name.trim() ? prev.name : (suggestedTitle || prev.name)
610
+ }));
611
+ }}
612
+ />
613
  </div>
614
  );
615
  }
frontend/src/components/SpintaxModal.tsx CHANGED
@@ -11,8 +11,11 @@ import {
11
  CheckCircle2,
12
  RefreshCw,
13
  Layers,
14
- FileText
 
 
15
  } from 'lucide-react';
 
16
 
17
  interface SpintaxModalProps {
18
  isOpen: boolean;
@@ -163,10 +166,23 @@ export function SpintaxModal({ isOpen, onClose, initialText, onApply }: SpintaxM
163
  const [copied, setCopied] = useState(false);
164
  const [previews, setPreviews] = useState<string[]>([]);
165
  const [validation, setValidation] = useState<{ isValid: boolean; error?: string }>({ isValid: true });
 
 
 
166
 
167
  useEffect(() => {
168
  if (isOpen) {
169
  setText(initialText || '');
 
 
 
 
 
 
 
 
 
 
170
  }
171
  }, [isOpen, initialText]);
172
 
@@ -188,10 +204,56 @@ export function SpintaxModal({ isOpen, onClose, initialText, onApply }: SpintaxM
188
  setPreviews(samples);
189
  };
190
 
191
- const handleAutoSpintax = () => {
192
  if (!text.trim()) return;
193
- const spun = generateSmartSpintax(text);
194
- setText(spun);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  };
196
 
197
  const handleCopy = () => {
@@ -226,9 +288,15 @@ export function SpintaxModal({ isOpen, onClose, initialText, onApply }: SpintaxM
226
  <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">
227
  Anti-Spam
228
  </span>
 
 
 
 
 
 
229
  </h3>
230
  <p className="text-xs text-foreground/50 font-medium">
231
- Transform your message into dynamic variations to avoid Telegram spam detection.
232
  </p>
233
  </div>
234
  </div>
@@ -244,17 +312,35 @@ export function SpintaxModal({ isOpen, onClose, initialText, onApply }: SpintaxM
244
  <div className="p-6 overflow-y-auto space-y-5 custom-scrollbar flex-1">
245
  {/* Toolbar */}
246
  <div className="flex flex-wrap items-center justify-between gap-2 bg-foreground/[0.03] p-2 rounded-2xl border border-border/60">
247
- <div className="flex items-center gap-1.5">
248
  <button
249
  type="button"
250
  onClick={handleAutoSpintax}
251
- className="px-3.5 py-1.5 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold transition-all shadow-sm flex items-center gap-1.5 active:scale-95"
 
 
252
  >
253
- <Wand2 size={13} /> Auto Spintax
 
 
 
 
 
 
 
 
 
 
254
  </button>
255
- <span className="text-[11px] text-foreground/40 font-medium px-2 hidden sm:inline">
256
- Automatically adds variations to greetings, adjectives & calls-to-action
257
- </span>
 
 
 
 
 
 
258
  </div>
259
  <div className="flex items-center gap-1.5">
260
  <button
 
11
  CheckCircle2,
12
  RefreshCw,
13
  Layers,
14
+ FileText,
15
+ Loader2,
16
+ Cpu
17
  } from 'lucide-react';
18
+ import { apiFetch } from '@/lib/auth';
19
 
20
  interface SpintaxModalProps {
21
  isOpen: boolean;
 
166
  const [copied, setCopied] = useState(false);
167
  const [previews, setPreviews] = useState<string[]>([]);
168
  const [validation, setValidation] = useState<{ isValid: boolean; error?: string }>({ isValid: true });
169
+ const [isAiLoading, setIsAiLoading] = useState(false);
170
+ const [aiNote, setAiNote] = useState('');
171
+ const [configuredModel, setConfiguredModel] = useState('');
172
 
173
  useEffect(() => {
174
  if (isOpen) {
175
  setText(initialText || '');
176
+ setAiNote('');
177
+ try {
178
+ const m = localStorage.getItem('arkitel_ai_model');
179
+ if (m) {
180
+ const shortName = m.split('/')[1] || m;
181
+ setConfiguredModel(shortName.replace(/-instruct|-chat|-versatile/g, ''));
182
+ } else {
183
+ setConfiguredModel('Llama 3.3 70B');
184
+ }
185
+ } catch {}
186
  }
187
  }, [isOpen, initialText]);
188
 
 
204
  setPreviews(samples);
205
  };
206
 
207
+ const handleAutoSpintax = async () => {
208
  if (!text.trim()) return;
209
+
210
+ let storedKey = '';
211
+ let storedModel = 'meta-llama/llama-3.3-70b-instruct';
212
+ try {
213
+ storedKey = localStorage.getItem('arkitel_ai_key') || '';
214
+ storedModel = localStorage.getItem('arkitel_ai_model') || 'meta-llama/llama-3.3-70b-instruct';
215
+ } catch {}
216
+
217
+ if (!storedKey) {
218
+ // Local fallback dictionary
219
+ const spun = generateSmartSpintax(text);
220
+ setText(spun);
221
+ setAiNote('Generated via local dictionary. Connect your OpenRouter AI key in Scraper for high-power AI Spintax.');
222
+ setTimeout(() => setAiNote(''), 5000);
223
+ return;
224
+ }
225
+
226
+ setIsAiLoading(true);
227
+ setAiNote('');
228
+ try {
229
+ const res = await apiFetch('/api/ai/spintax', {
230
+ method: 'POST',
231
+ body: JSON.stringify({
232
+ text: text.trim(),
233
+ api_key: storedKey,
234
+ model: storedModel
235
+ })
236
+ });
237
+ const data = await res.json();
238
+ if (res.ok && data.spintax) {
239
+ setText(data.spintax);
240
+ const shortModel = storedModel.split('/')[1] || storedModel;
241
+ setAiNote(`Spun with AI (${shortModel.replace(/-instruct|-chat/g, '')})`);
242
+ setTimeout(() => setAiNote(''), 4000);
243
+ } else {
244
+ const spun = generateSmartSpintax(text);
245
+ setText(spun);
246
+ setAiNote(data.detail || 'Used local Spintax dictionary.');
247
+ setTimeout(() => setAiNote(''), 4000);
248
+ }
249
+ } catch (e: any) {
250
+ const spun = generateSmartSpintax(text);
251
+ setText(spun);
252
+ setAiNote('Used local Spintax dictionary.');
253
+ setTimeout(() => setAiNote(''), 3000);
254
+ } finally {
255
+ setIsAiLoading(false);
256
+ }
257
  };
258
 
259
  const handleCopy = () => {
 
288
  <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">
289
  Anti-Spam
290
  </span>
291
+ {configuredModel && (
292
+ <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">
293
+ <Cpu size={10} />
294
+ {configuredModel}
295
+ </span>
296
+ )}
297
  </h3>
298
  <p className="text-xs text-foreground/50 font-medium">
299
+ Transform your message into dynamic variations using your configured AI model to avoid Telegram spam detection.
300
  </p>
301
  </div>
302
  </div>
 
312
  <div className="p-6 overflow-y-auto space-y-5 custom-scrollbar flex-1">
313
  {/* Toolbar */}
314
  <div className="flex flex-wrap items-center justify-between gap-2 bg-foreground/[0.03] p-2 rounded-2xl border border-border/60">
315
+ <div className="flex items-center gap-1.5 flex-wrap">
316
  <button
317
  type="button"
318
  onClick={handleAutoSpintax}
319
+ disabled={isAiLoading || !text.trim()}
320
+ 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"
321
+ title="Enrich message variations with your configured OpenRouter model"
322
  >
323
+ {isAiLoading ? (
324
+ <>
325
+ <Loader2 size={13} className="animate-spin" />
326
+ <span>AI Spinning...</span>
327
+ </>
328
+ ) : (
329
+ <>
330
+ <Wand2 size={13} />
331
+ <span>AI Auto Spintax</span>
332
+ </>
333
+ )}
334
  </button>
335
+ {aiNote ? (
336
+ <span className="text-[11px] text-emerald-400 font-semibold px-2 animate-in fade-in">
337
+ {aiNote}
338
+ </span>
339
+ ) : (
340
+ <span className="text-[11px] text-foreground/40 font-medium px-2 hidden sm:inline">
341
+ Adds rich variations to greetings, adjectives & CTAs via AI
342
+ </span>
343
+ )}
344
  </div>
345
  <div className="flex items-center gap-1.5">
346
  <button
frontend/src/components/TemplateAiAssistantModal.tsx ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import React, { useState, useEffect } from 'react';
4
+ import {
5
+ Sparkles,
6
+ X,
7
+ Check,
8
+ Copy,
9
+ AlertCircle,
10
+ Loader2,
11
+ Cpu,
12
+ ArrowRight,
13
+ Wand2,
14
+ MessageSquare,
15
+ Shuffle
16
+ } from 'lucide-react';
17
+ import { apiFetch } from '@/lib/auth';
18
+ import { evaluateSpintax } from './SpintaxModal';
19
+
20
+ interface TemplateAiAssistantModalProps {
21
+ isOpen: boolean;
22
+ onClose: () => void;
23
+ onSelectVariation: (content: string, suggestedTitle?: string) => void;
24
+ }
25
+
26
+ const INSPIRATION_PROMPTS = [
27
+ {
28
+ label: "IPTV Channel Promo",
29
+ prompt: "I want a high-converting message to promote my premium IPTV channel. Highlight 4K buffer-free sports & cinema channels, offer a 24-hour instant free trial, and include channel link: t.me/yourchannel."
30
+ },
31
+ {
32
+ label: "Crypto VIP Alpha",
33
+ prompt: "Write a high-converting invitation for our exclusive Crypto Signals & Alpha group. Emphasize verified 85% win rate, daily market breakdowns, and limited VIP seats. Channel link: t.me/yourchannel."
34
+ },
35
+ {
36
+ label: "B2B Outreach / Services",
37
+ prompt: "Draft a personalized direct message offering our web design & automation agency services to business owners. Offer a free 15-minute growth audit with no strings attached."
38
+ },
39
+ {
40
+ label: "E-Commerce Deals",
41
+ prompt: "Create an exciting promotion message for our discount deals community. Mention up to 70% off trending gadgets, verified seller discounts, and daily flash sales."
42
+ }
43
+ ];
44
+
45
+ const VARIATION_ANGLES = [
46
+ "Direct Value & Free Trial",
47
+ "Curiosity & Exclusive VIP Hook",
48
+ "Social Proof & Problem-Solver",
49
+ "Conversational Soft Question",
50
+ "High Urgency & Limited-Time Perk"
51
+ ];
52
+
53
+ export function TemplateAiAssistantModal({ isOpen, onClose, onSelectVariation }: TemplateAiAssistantModalProps) {
54
+ const [prompt, setPrompt] = useState('');
55
+ const [includeSpintax, setIncludeSpintax] = useState(true);
56
+ const [isGenerating, setIsGenerating] = useState(false);
57
+ const [variations, setVariations] = useState<string[]>([]);
58
+ const [error, setError] = useState('');
59
+ const [copiedIdx, setCopiedIdx] = useState<number | null>(null);
60
+ const [samplePreviews, setSamplePreviews] = useState<Record<number, string>>({});
61
+ const [configuredModel, setConfiguredModel] = useState('');
62
+
63
+ useEffect(() => {
64
+ if (isOpen) {
65
+ setError('');
66
+ try {
67
+ const m = localStorage.getItem('arkitel_ai_model');
68
+ if (m) {
69
+ const shortName = m.split('/')[1] || m;
70
+ setConfiguredModel(shortName.replace(/-instruct|-chat|-versatile/g, ''));
71
+ } else {
72
+ setConfiguredModel('Llama 3.3 70B');
73
+ }
74
+ } catch {}
75
+ }
76
+ }, [isOpen]);
77
+
78
+ if (!isOpen) return null;
79
+
80
+ const handleGenerate = async () => {
81
+ if (!prompt.trim()) {
82
+ setError('Please explain what message or offer you want to generate.');
83
+ return;
84
+ }
85
+
86
+ let key = '';
87
+ let model = 'meta-llama/llama-3.3-70b-instruct';
88
+ try {
89
+ key = localStorage.getItem('arkitel_ai_key') || '';
90
+ model = localStorage.getItem('arkitel_ai_model') || 'meta-llama/llama-3.3-70b-instruct';
91
+ } catch {}
92
+
93
+ if (!key) {
94
+ setError('No OpenRouter AI key found. Please open Scraper > AI Provider to save your OpenRouter key first.');
95
+ return;
96
+ }
97
+
98
+ setIsGenerating(true);
99
+ setError('');
100
+ try {
101
+ const res = await apiFetch('/api/ai/generate-template-variations', {
102
+ method: 'POST',
103
+ body: JSON.stringify({
104
+ prompt: prompt.trim(),
105
+ api_key: key,
106
+ model: model,
107
+ include_spintax: includeSpintax,
108
+ count: 5
109
+ })
110
+ });
111
+ const data = await res.json();
112
+ if (res.ok && Array.isArray(data.variations) && data.variations.length > 0) {
113
+ setVariations(data.variations);
114
+ setSamplePreviews({});
115
+ } else {
116
+ setError(data.detail || 'Failed to generate message variations. Please try another prompt.');
117
+ }
118
+ } catch (e: any) {
119
+ setError(e.message || 'Error communicating with AI assistant.');
120
+ } finally {
121
+ setIsGenerating(false);
122
+ }
123
+ };
124
+
125
+ const handleCopy = (text: string, idx: number) => {
126
+ navigator.clipboard.writeText(text);
127
+ setCopiedIdx(idx);
128
+ setTimeout(() => setCopiedIdx(null), 2000);
129
+ };
130
+
131
+ const handleTogglePreviewSpin = (idx: number, spintaxText: string) => {
132
+ setSamplePreviews(prev => ({
133
+ ...prev,
134
+ [idx]: evaluateSpintax(spintaxText)
135
+ }));
136
+ };
137
+
138
+ return (
139
+ <div className="fixed inset-0 bg-background/80 backdrop-blur-3xl z-[260] flex items-center justify-center p-3 sm:p-4 animate-in fade-in duration-200">
140
+ <div className="bg-card border border-border/90 rounded-[28px] w-full max-w-3xl shadow-2xl overflow-hidden flex flex-col max-h-[92vh] animate-in zoom-in-95 duration-200">
141
+ {/* Header */}
142
+ <div className="p-4 sm:p-5 px-6 border-b border-border/60 flex items-center justify-between bg-foreground/[0.02]">
143
+ <div className="flex items-center gap-3">
144
+ <div className="w-10 h-10 rounded-2xl bg-gradient-to-br from-purple-600 via-indigo-600 to-cyan-500 flex items-center justify-center text-white shadow-lg shadow-indigo-500/25">
145
+ <Sparkles size={19} className="text-amber-300" />
146
+ </div>
147
+ <div>
148
+ <h3 className="font-bold text-base text-foreground tracking-tight flex items-center gap-2">
149
+ AI Copywriter & Template Generator
150
+ {configuredModel && (
151
+ <span className="text-[10px] font-mono font-bold px-2 py-0.5 rounded-full bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 flex items-center gap-1">
152
+ <Cpu size={10} />
153
+ {configuredModel}
154
+ </span>
155
+ )}
156
+ </h3>
157
+ <p className="text-xs text-foreground/50 font-medium">
158
+ Describe your offer, niche, or channel to instantly generate 5 high-converting message variations.
159
+ </p>
160
+ </div>
161
+ </div>
162
+ <button
163
+ onClick={onClose}
164
+ className="p-2 rounded-xl text-foreground/40 hover:text-foreground hover:bg-foreground/5 transition-colors cursor-pointer"
165
+ >
166
+ <X size={18} />
167
+ </button>
168
+ </div>
169
+
170
+ {/* Body */}
171
+ <div className="p-5 sm:p-6 overflow-y-auto space-y-5 custom-scrollbar flex-1">
172
+ {/* Input Section */}
173
+ <div className="space-y-3 p-4 rounded-2xl bg-foreground/[0.02] border border-border/70">
174
+ <div className="flex items-center justify-between">
175
+ <label className="text-xs font-bold text-foreground/75 uppercase tracking-wider flex items-center gap-1.5">
176
+ <MessageSquare size={13} className="text-indigo-400" />
177
+ What would you like the AI to write?
178
+ </label>
179
+ <label className="flex items-center gap-2 text-xs font-semibold text-foreground/70 cursor-pointer select-none">
180
+ <input
181
+ type="checkbox"
182
+ checked={includeSpintax}
183
+ onChange={(e) => setIncludeSpintax(e.target.checked)}
184
+ className="rounded border-border text-indigo-600 focus:ring-indigo-500 cursor-pointer"
185
+ />
186
+ <span>Anti-Ban Spintax {"{Hi|Hello}"}</span>
187
+ </label>
188
+ </div>
189
+
190
+ <textarea
191
+ rows={3}
192
+ value={prompt}
193
+ onChange={(e) => setPrompt(e.target.value)}
194
+ placeholder="e.g. I want a converting message to promote my IPTV service. Offer a 24h free trial, highlight 4K bufferless sports channels, here is my link: t.me/mychannel..."
195
+ className="w-full bg-input border border-border/80 text-foreground rounded-xl p-3 text-xs focus:ring-2 focus:ring-indigo-500/20 outline-none transition-all placeholder:text-foreground/35 font-medium leading-relaxed resize-none"
196
+ />
197
+
198
+ {/* Quick Prompts */}
199
+ <div className="flex items-center gap-1.5 flex-wrap pt-0.5">
200
+ <span className="text-[10px] text-foreground/40 font-bold uppercase tracking-wider mr-1">Inspiration:</span>
201
+ {INSPIRATION_PROMPTS.map((item, idx) => (
202
+ <button
203
+ key={idx}
204
+ type="button"
205
+ onClick={() => setPrompt(item.prompt)}
206
+ className="px-2.5 py-1 rounded-lg text-[10px] font-semibold bg-foreground/5 hover:bg-indigo-500/10 hover:text-indigo-400 border border-border/60 hover:border-indigo-500/30 text-foreground/70 transition-all cursor-pointer"
207
+ >
208
+ {item.label}
209
+ </button>
210
+ ))}
211
+ </div>
212
+
213
+ {error && (
214
+ <div className="flex items-center gap-2 p-2.5 bg-rose-500/10 border border-rose-500/20 rounded-xl text-rose-400 text-xs font-semibold">
215
+ <AlertCircle size={14} className="shrink-0" />
216
+ <span>{error}</span>
217
+ </div>
218
+ )}
219
+
220
+ <div className="flex justify-end pt-1">
221
+ <button
222
+ type="button"
223
+ onClick={handleGenerate}
224
+ disabled={isGenerating || !prompt.trim()}
225
+ className="px-5 py-2 rounded-xl bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 disabled:opacity-50 text-white text-xs font-bold transition-all shadow-md active:scale-95 flex items-center gap-2 cursor-pointer"
226
+ >
227
+ {isGenerating ? (
228
+ <>
229
+ <Loader2 size={14} className="animate-spin" />
230
+ <span>Crafting 5 High-Converting Variations...</span>
231
+ </>
232
+ ) : (
233
+ <>
234
+ <Wand2 size={14} />
235
+ <span>Generate 5 Variations</span>
236
+ </>
237
+ )}
238
+ </button>
239
+ </div>
240
+ </div>
241
+
242
+ {/* Variations Output Section */}
243
+ {variations.length > 0 && (
244
+ <div className="space-y-4">
245
+ <div className="flex items-center justify-between px-1">
246
+ <div className="text-xs font-bold text-foreground/80 uppercase tracking-wider flex items-center gap-2">
247
+ <span>5 AI Generated Variations</span>
248
+ <span className="text-[10px] font-normal lowercase text-foreground/40 font-mono">
249
+ (click &quot;Use This Variation&quot; to apply)
250
+ </span>
251
+ </div>
252
+ <span className="text-[10px] text-emerald-400 font-bold bg-emerald-500/10 border border-emerald-500/20 px-2 py-0.5 rounded-full">
253
+ Ready to Deploy
254
+ </span>
255
+ </div>
256
+
257
+ <div className="grid grid-cols-1 gap-3.5">
258
+ {variations.map((vText, idx) => {
259
+ const angleName = VARIATION_ANGLES[idx] || `Angle #${idx + 1}`;
260
+ const hasSpintax = vText.includes('{') && vText.includes('|');
261
+ const previewText = samplePreviews[idx];
262
+
263
+ return (
264
+ <div
265
+ key={idx}
266
+ className="p-4 rounded-2xl bg-foreground/[0.015] border border-border/80 hover:border-indigo-500/40 hover:bg-foreground/[0.03] transition-all space-y-3 group"
267
+ >
268
+ <div className="flex items-center justify-between gap-2">
269
+ <div className="flex items-center gap-2">
270
+ <span className="w-5 h-5 rounded-full bg-indigo-500/15 text-indigo-400 text-[10px] font-bold flex items-center justify-center border border-indigo-500/20">
271
+ {idx + 1}
272
+ </span>
273
+ <span className="text-xs font-bold text-foreground">
274
+ {angleName}
275
+ </span>
276
+ {hasSpintax && (
277
+ <span className="text-[9px] uppercase tracking-wider px-1.5 py-0.5 rounded bg-purple-500/10 text-purple-400 border border-purple-500/20 font-bold">
278
+ Spintax Ready
279
+ </span>
280
+ )}
281
+ </div>
282
+
283
+ <div className="flex items-center gap-1.5">
284
+ {hasSpintax && (
285
+ <button
286
+ type="button"
287
+ onClick={() => handleTogglePreviewSpin(idx, vText)}
288
+ className="px-2 py-1 rounded-lg text-[10px] font-semibold bg-foreground/5 hover:bg-foreground/10 text-foreground/60 transition-colors flex items-center gap-1 cursor-pointer"
289
+ title="Preview resolved random variation"
290
+ >
291
+ <Shuffle size={10} />
292
+ <span>{previewText ? "Re-spin" : "Preview"}</span>
293
+ </button>
294
+ )}
295
+ <button
296
+ type="button"
297
+ onClick={() => handleCopy(vText, idx)}
298
+ className="p-1.5 rounded-lg text-foreground/40 hover:text-foreground hover:bg-foreground/5 transition-colors cursor-pointer"
299
+ title="Copy variation"
300
+ >
301
+ {copiedIdx === idx ? <Check size={13} className="text-emerald-400" /> : <Copy size={13} />}
302
+ </button>
303
+ <button
304
+ type="button"
305
+ onClick={() => {
306
+ onSelectVariation(vText, angleName);
307
+ onClose();
308
+ }}
309
+ className="px-3 py-1 rounded-xl bg-indigo-600 hover:bg-indigo-500 text-white text-xs font-bold transition-all shadow-sm flex items-center gap-1.5 cursor-pointer active:scale-95"
310
+ >
311
+ <span>Use This Variation</span>
312
+ <ArrowRight size={12} />
313
+ </button>
314
+ </div>
315
+ </div>
316
+
317
+ {/* Preview mode for Spintax */}
318
+ {previewText ? (
319
+ <div className="p-3 rounded-xl bg-purple-500/5 border border-purple-500/20 text-xs text-foreground/90 font-mono leading-relaxed whitespace-pre-wrap">
320
+ <div className="text-[9px] font-bold text-purple-400 uppercase tracking-wider mb-1 flex items-center gap-1">
321
+ <Shuffle size={9} /> Resolved Output Sample:
322
+ </div>
323
+ {previewText}
324
+ </div>
325
+ ) : null}
326
+
327
+ {/* Raw Text View */}
328
+ <div className="p-3 rounded-xl bg-card border border-border/60 text-xs text-foreground/80 font-mono leading-relaxed whitespace-pre-wrap max-h-36 overflow-y-auto custom-scrollbar select-text">
329
+ {vText}
330
+ </div>
331
+ </div>
332
+ );
333
+ })}
334
+ </div>
335
+ </div>
336
+ )}
337
+ </div>
338
+
339
+ {/* Footer */}
340
+ <div className="p-4 px-6 border-t border-border/60 flex justify-between items-center bg-foreground/[0.02]">
341
+ <span className="text-[11px] text-foreground/40 font-mono">
342
+ {configuredModel ? `Powered by OpenRouter • ${configuredModel}` : "Configured via Scraper AI Provider"}
343
+ </span>
344
+ <button
345
+ type="button"
346
+ onClick={onClose}
347
+ className="px-4 py-1.5 text-xs text-foreground/60 hover:text-foreground font-semibold rounded-lg hover:bg-foreground/5 transition-all cursor-pointer"
348
+ >
349
+ Close
350
+ </button>
351
+ </div>
352
+ </div>
353
+ </div>
354
+ );
355
+ }