arkitel / frontend /src /components /TemplateAiAssistantModal.tsx
CBV01
Fix campaign card status colors, AI copy generation parsing, sample benchmark directive, and neat paragraph formatting
ecc25e4
Raw History Blame Contribute Delete
26 kB
"use client";
import React, { useState, useEffect } from 'react';
import {
Sparkles,
X,
Check,
Copy,
AlertCircle,
Loader2,
Cpu,
ArrowRight,
Wand2,
MessageSquare,
Shuffle
} from 'lucide-react';
import { apiFetch } from '@/lib/auth';
import { evaluateSpintax } from './SpintaxModal';
interface TemplateAiAssistantModalProps {
isOpen: boolean;
onClose: () => void;
onSelectVariation: (content: string, suggestedTitle?: string) => void;
}
const INSPIRATION_PROMPTS = [
{
label: "IPTV Channel Promo",
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."
},
{
label: "Crypto VIP Alpha",
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."
},
{
label: "B2B Outreach / Services",
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."
},
{
label: "E-Commerce Deals",
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."
}
];
const VARIATION_ANGLES = [
"Direct Value & Free Trial",
"Curiosity & Exclusive VIP Hook",
"Social Proof & Problem-Solver",
"Conversational Soft Question",
"High Urgency & Limited-Time Perk"
];
export function TemplateAiAssistantModal({ isOpen, onClose, onSelectVariation }: TemplateAiAssistantModalProps) {
const [prompt, setPrompt] = useState('');
const [sampleText, setSampleText] = useState('');
const [showSampleInput, setShowSampleInput] = useState(false);
const [includeSpintax, setIncludeSpintax] = useState(true);
const [length, setLength] = useState<'short' | 'moderate' | 'lengthy'>('moderate');
const [isGenerating, setIsGenerating] = useState(false);
const [variations, setVariations] = useState<string[]>([]);
const [error, setError] = useState('');
const [copiedIdx, setCopiedIdx] = useState<number | null>(null);
const [samplePreviews, setSamplePreviews] = useState<Record<number, string>>({});
const [configuredModel, setConfiguredModel] = useState('');
useEffect(() => {
if (isOpen) {
setError('');
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]);
if (!isOpen) return null;
const handleGenerate = async () => {
if (!prompt.trim()) {
setError('Please explain what message or offer you want to generate.');
return;
}
let key = '';
let model = 'meta-llama/llama-3.3-70b-instruct';
try {
key = localStorage.getItem('arkitel_ai_key') || '';
model = localStorage.getItem('arkitel_ai_model') || 'meta-llama/llama-3.3-70b-instruct';
} catch {}
if (!key) {
setError('No OpenRouter AI key found. Please open Scraper > AI Provider to save your OpenRouter key first.');
return;
}
setIsGenerating(true);
setError('');
try {
const res = await apiFetch('/api/ai/generate-template-variations', {
method: 'POST',
body: JSON.stringify({
prompt: prompt.trim(),
sample_text: sampleText.trim() || undefined,
api_key: key,
model: model,
include_spintax: includeSpintax,
count: 5,
length: length
})
});
const data = await res.json();
if (res.ok && Array.isArray(data.variations) && data.variations.length > 0) {
setVariations(data.variations);
setSamplePreviews({});
} else {
const detailMsg = typeof data.detail === 'string'
? data.detail
: Array.isArray(data.detail)
? data.detail.map((d: any) => d.msg || JSON.stringify(d)).join(', ')
: 'Failed to generate message variations. Please try another prompt.';
setError(detailMsg);
}
} catch (e: any) {
setError(e.message || 'Error communicating with AI assistant.');
} finally {
setIsGenerating(false);
}
};
const handleCopy = (text: string, idx: number) => {
navigator.clipboard.writeText(text);
setCopiedIdx(idx);
setTimeout(() => setCopiedIdx(null), 2000);
};
const handleTogglePreviewSpin = (idx: number, spintaxText: string) => {
setSamplePreviews(prev => ({
...prev,
[idx]: evaluateSpintax(spintaxText)
}));
};
return (
<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">
<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">
{/* Header */}
<div className="p-4 sm: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-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">
<Sparkles size={19} className="text-amber-300" />
</div>
<div>
<h3 className="font-bold text-base text-foreground tracking-tight flex items-center gap-2">
AI Copywriter & Template Generator
{configuredModel && (
<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">
<Cpu size={10} />
{configuredModel}
</span>
)}
</h3>
<p className="text-xs text-foreground/50 font-medium">
Describe your offer, niche, or channel to instantly generate 5 high-converting message variations.
</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-5 sm:p-6 overflow-y-auto space-y-5 custom-scrollbar flex-1">
{/* Input Section */}
<div className="space-y-3 p-4 rounded-2xl bg-foreground/[0.02] border border-border/70">
<div className="flex items-center justify-between gap-2 flex-wrap">
<label className="text-xs font-bold text-foreground/75 uppercase tracking-wider flex items-center gap-1.5">
<MessageSquare size={13} className="text-indigo-400" />
What would you like the AI to write?
</label>
<div className="flex items-center gap-3 flex-wrap">
{/* Word Volume / Length Selector */}
<div className="flex items-center gap-1 bg-foreground/5 p-0.5 rounded-lg border border-border/60">
<span className="text-[9px] font-bold text-foreground/40 px-1.5 uppercase tracking-wider">Volume:</span>
{(['short', 'moderate', 'lengthy'] as const).map((v) => (
<button
key={v}
type="button"
onClick={() => setLength(v)}
className={`px-2 py-0.5 rounded-md text-[10px] font-bold capitalize transition-all cursor-pointer ${
length === v
? 'bg-indigo-600 text-white shadow-xs shadow-indigo-600/30'
: 'text-foreground/50 hover:text-foreground hover:bg-foreground/5'
}`}
>
{v === 'short' ? '⚡ Short' : v === 'moderate' ? '📝 Moderate' : '📜 Lengthy'}
</button>
))}
</div>
<label className="flex items-center gap-1.5 text-xs font-semibold text-foreground/70 cursor-pointer select-none">
<input
type="checkbox"
checked={includeSpintax}
onChange={(e) => setIncludeSpintax(e.target.checked)}
className="rounded border-border text-indigo-600 focus:ring-indigo-500 cursor-pointer"
/>
<span className="text-[11px]">Spintax</span>
</label>
</div>
</div>
<textarea
rows={3}
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
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..."
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"
/>
{/* Quick Prompts & Drop Sample */}
<div className="flex items-center justify-between gap-2 flex-wrap pt-0.5">
<div className="flex items-center gap-1.5 flex-wrap">
<span className="text-[10px] text-foreground/40 font-bold uppercase tracking-wider mr-1">Inspiration:</span>
{INSPIRATION_PROMPTS.map((item, idx) => (
<button
key={idx}
type="button"
onClick={() => setPrompt(item.prompt)}
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"
>
{item.label}
</button>
))}
</div>
<button
type="button"
onClick={() => setShowSampleInput(!showSampleInput)}
className={`px-2.5 py-1 rounded-lg text-[10px] font-bold border transition-all flex items-center gap-1.5 cursor-pointer ml-auto ${
showSampleInput || sampleText.trim()
? 'bg-amber-500/15 text-amber-300 border-amber-500/35 shadow-xs'
: 'bg-foreground/5 hover:bg-foreground/10 text-foreground/60 border-border/60'
}`}
title="Drop or paste sample copy for the AI to emulate style, layout, and length"
>
<span>{showSampleInput ? 'Hide Sample' : '+ Drop Sample'}</span>
{sampleText.trim() && <span className="w-1.5 h-1.5 rounded-full bg-amber-400 animate-pulse" />}
</button>
</div>
{/* Drop Sample Reference Box */}
{showSampleInput && (
<div className="space-y-1.5 p-3 rounded-xl bg-amber-500/[0.04] border border-amber-500/25 animate-in fade-in slide-in-from-top-1 duration-200">
<div className="flex items-center justify-between">
<span className="text-[10px] font-bold text-amber-400 uppercase tracking-wider flex items-center gap-1">
Style & Structure Benchmark (Optional)
</span>
{sampleText && (
<button
type="button"
onClick={() => setSampleText('')}
className="text-[10px] text-foreground/40 hover:text-foreground/80 font-medium cursor-pointer"
>
Clear Sample
</button>
)}
</div>
<p className="text-[10px] text-foreground/50 leading-tight">
The AI uses this purely as a layout, tone, bullet density, and length reference. It writes 100% original copy for your offer and will <strong>not copy</strong> the sample wording.
</p>
<textarea
rows={3}
value={sampleText}
onChange={(e) => setSampleText(e.target.value)}
placeholder="Paste reference message or competitor copy here to benchmark tone, formatting, and length..."
className="w-full bg-input border border-border/70 text-foreground rounded-lg p-2.5 text-xs focus:ring-1 focus:ring-amber-500/30 outline-none transition-all placeholder:text-foreground/35 font-medium leading-relaxed resize-none"
/>
</div>
)}
{error && (
<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">
<AlertCircle size={14} className="shrink-0" />
<span>{error}</span>
</div>
)}
<div className="flex justify-end pt-1">
<button
type="button"
onClick={handleGenerate}
disabled={isGenerating || !prompt.trim()}
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"
>
{isGenerating ? (
<>
<Loader2 size={14} className="animate-spin" />
<span>Crafting 5 High-Converting Variations...</span>
</>
) : (
<>
<Wand2 size={14} />
<span>Generate 5 Variations</span>
</>
)}
</button>
</div>
</div>
{/* Variations Output Section */}
{variations.length > 0 && (
<div className="space-y-4">
<div className="flex items-center justify-between px-1">
<div className="text-xs font-bold text-foreground/80 uppercase tracking-wider flex items-center gap-2">
<span>5 AI Generated Variations</span>
<span className="text-[10px] font-normal lowercase text-foreground/40 font-mono">
(click &quot;Use This Variation&quot; to apply)
</span>
</div>
<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">
Ready to Deploy
</span>
</div>
<div className="grid grid-cols-1 gap-3.5">
{variations.map((vText, idx) => {
const angleName = VARIATION_ANGLES[idx] || `Angle #${idx + 1}`;
const hasSpintax = vText.includes('{') && vText.includes('|');
const previewText = samplePreviews[idx];
return (
<div
key={idx}
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"
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<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">
{idx + 1}
</span>
<span className="text-xs font-bold text-foreground">
{angleName}
</span>
{hasSpintax && (
<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">
Spintax Ready
</span>
)}
</div>
<div className="flex items-center gap-1.5">
{hasSpintax && (
<button
type="button"
onClick={() => handleTogglePreviewSpin(idx, vText)}
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"
title="Preview resolved random variation"
>
<Shuffle size={10} />
<span>{previewText ? "Re-spin" : "Preview"}</span>
</button>
)}
<button
type="button"
onClick={() => handleCopy(vText, idx)}
className="p-1.5 rounded-lg text-foreground/40 hover:text-foreground hover:bg-foreground/5 transition-colors cursor-pointer"
title="Copy variation"
>
{copiedIdx === idx ? <Check size={13} className="text-emerald-400" /> : <Copy size={13} />}
</button>
<button
type="button"
onClick={() => {
onSelectVariation(vText, angleName);
onClose();
}}
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"
>
<span>Use This Variation</span>
<ArrowRight size={12} />
</button>
</div>
</div>
{/* Preview mode for Spintax */}
{previewText ? (
<div className="p-3.5 rounded-xl bg-purple-500/5 border border-purple-500/20 text-xs text-foreground/90 font-mono leading-relaxed whitespace-pre-wrap break-words">
<div className="text-[9px] font-bold text-purple-400 uppercase tracking-wider mb-1 flex items-center gap-1">
<Shuffle size={9} /> Resolved Output Sample:
</div>
{previewText}
</div>
) : null}
{/* Raw Text View */}
<div className="p-3.5 rounded-xl bg-card border border-border/70 text-[12px] text-foreground/90 font-sans leading-relaxed whitespace-pre-wrap break-words max-h-60 overflow-y-auto custom-scrollbar select-text">
{vText}
</div>
</div>
);
})}
</div>
</div>
)}
</div>
{/* Footer */}
<div className="p-4 px-6 border-t border-border/60 flex justify-between items-center bg-foreground/[0.02]">
<span className="text-[11px] text-foreground/40 font-mono">
{configuredModel ? `Powered by OpenRouter • ${configuredModel}` : "Configured via Scraper AI Provider"}
</span>
<button
type="button"
onClick={onClose}
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"
>
Close
</button>
</div>
</div>
</div>
);
}