All files / src/components/blogs AIPreStep.tsx

96.39% Statements 107/111
90% Branches 63/70
95.45% Functions 21/22
96.22% Lines 102/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497                                                                2x                 130x     130x     130x 130x 130x 130x     130x 130x 130x 130x     130x     130x 130x   130x 130x   130x     130x 44x   10x 5x 5x 5x 5x   5x 1x 1x 4x 4x 4x                 10x     130x 7x 7x 7x 7x     5x 5x   1x   6x       130x 1x 1x 1x 1x 1x       130x 40x 5x               5x 5x       130x   11x 11x 11x 11x 11x 11x   11x               10x   1x 1x             130x 4x         4x 4x 4x   4x               3x 3x 3x         3x               3x     2x 2x 4x           1x 4x 1x 1x                 2x   2x   4x         130x 26x                         1x 1x 1x                                                         110x 110x 110x   110x                                                                   104x                                                                         10x                                                               6x                     1x                             16x                         23x                                                                   1x                 6x                     1x               1x                            
import { useState, useRef, useEffect, useCallback } from "react";
import {
	Sparkles,
	Loader2,
	ArrowLeft,
	X,
	Zap,
	Search,
	FileText,
	Image,
	BarChart,
	CheckCircle,
	AlertCircle,
} from "lucide-react";
import { Button } from "../ui/button";
import { usePro } from "../../lib/pro-context";
import { aiApi } from "../../lib/api/ai";
import { proApi } from "../../lib/api/pro";
import { blogImagesApi } from "../../lib/api/blog-images";
import { getErrorMessage } from "../../lib/api";
import type { TopicSuggestion, BlogType } from "../../lib/api/blogs";
import type { GenerationJobStatus } from "../../lib/api/ai";
 
interface AIPreStepProps {
	onDraftCreated: (blogId: string) => void;
	onBack: () => void;
}
 
const PIPELINE_STEPS: {
	status: GenerationJobStatus;
	label: string;
	icon: typeof Search;
}[] = [
	{ status: "research", label: "Researching trends...", icon: Search },
	{ status: "outlining", label: "Creating outline...", icon: FileText },
	{ status: "generating", label: "Writing content...", icon: Sparkles },
	{ status: "images", label: "Finding images...", icon: Image },
	{ status: "seo", label: "Optimizing for SEO...", icon: BarChart },
];
 
export function AIPreStep({ onDraftCreated, onBack }: AIPreStepProps) {
	const { proId } = usePro();
 
	// Mode: "form" (manual) or "oneclick" (pipeline)
	const [mode, setMode] = useState<"form" | "oneclick">("form");
 
	// Form state
	const [title, setTitle] = useState("");
	const [blogType, setBlogType] = useState<BlogType>("general");
	const [outline, setOutline] = useState("");
	const [primaryKeyword, setPrimaryKeyword] = useState("");
 
	// Suggestions
	const [suggestions, setSuggestions] = useState<TopicSuggestion[]>([]);
	const [showSuggestions, setShowSuggestions] = useState(false);
	const [loadingSuggestions, setLoadingSuggestions] = useState(false);
	const suggestionsRef = useRef<HTMLDivElement>(null);
 
	// Manual draft generation
	const [generatingDraft, setGeneratingDraft] = useState(false);
 
	// One-click pipeline state
	const [jobId, setJobId] = useState<string | null>(null);
	const [pipelineStatus, setPipelineStatus] =
		useState<GenerationJobStatus | null>(null);
	const [pipelineStep, setPipelineStep] = useState(0);
	const [pipelineError, setPipelineError] = useState<string | null>(null);
 
	const [error, setError] = useState<string | null>(null);
 
	// Poll pipeline job status
	useEffect(() => {
		if (!jobId) return;
 
		const interval = setInterval(async () => {
			try {
				const job = await aiApi.getJobStatus(jobId);
				setPipelineStatus(job.status);
				setPipelineStep(job.currentStep);
 
				if (job.status === "complete" && job.blogId) {
					clearInterval(interval);
					onDraftCreated(job.blogId);
				E} else if (job.status === "failed") {
					clearInterval(interval);
					setPipelineError(
						job.errorLog || "Blog generation failed. Please try again.",
					);
				}
			} catch {
				// Polling error — continue trying
			}
		}, 3000);
 
		return () => clearInterval(interval);
	}, [jobId, onDraftCreated]);
 
	const handleGetSuggestions = async () => {
		try {
			setLoadingSuggestions(true);
			setError(null);
			const result = await aiApi.suggestTopics(proId as string, {
				count: 5,
			});
			setSuggestions(result.suggestions);
			setShowSuggestions(true);
		} catch (err) {
			setError(getErrorMessage(err));
		} finally {
			setLoadingSuggestions(false);
		}
	};
 
	const handleUseSuggestion = (suggestion: TopicSuggestion) => {
		setTitle(suggestion.title);
		setBlogType(suggestion.blog_type);
		setOutline(suggestion.outline);
		setPrimaryKeyword(suggestion.primary_keyword);
		setShowSuggestions(false);
	};
 
	// Close popup on click outside
	useEffect(() => {
		if (!showSuggestions) return;
		const handleClickOutside = (e: MouseEvent) => {
			if (
				suggestionsRef.current &&
				!suggestionsRef.current.contains(e.target as Node)
			) {
				setShowSuggestions(false);
			}
		};
		document.addEventListener("mousedown", handleClickOutside);
		return () => document.removeEventListener("mousedown", handleClickOutside);
	}, [showSuggestions]);
 
	// One-click generation
	const handleOneClickGenerate = useCallback(
		async (suggestion?: TopicSuggestion) => {
			try {
				setMode("oneclick");
				setError(null);
				setPipelineError(null);
				setPipelineStatus("research");
				setPipelineStep(0);
 
				const result = await aiApi.generateFull({
					proId: proId as string,
					title: suggestion?.title || title || undefined,
					blogType: suggestion?.blog_type || blogType,
					primaryKeyword:
						suggestion?.primary_keyword || primaryKeyword || undefined,
				});
 
				setJobId(result.jobId);
			} catch (err) {
				setMode("form");
				setError(getErrorMessage(err));
			}
		},
		[proId, title, blogType, primaryKeyword],
	);
 
	// Manual draft generation (existing flow)
	const handleGenerateDraft = async () => {
		Iif (!title.trim()) {
			setError("Title is required");
			return;
		}
 
		try {
			setGeneratingDraft(true);
			setError(null);
 
			const result = await aiApi.generateDraft({
				title,
				primaryKeyword,
				blogType,
				outline,
				wordCount: 800,
			});
 
			const { marked } = await import("marked");
			const htmlContent = await marked.parse(result.content);
			const slug = title
				.toLowerCase()
				.replace(/[^a-z0-9]+/g, "-")
				.replace(/^-|-$/g, "");
 
			const blog = await proApi.createMyBlog(proId as string, {
				title,
				slug,
				content: htmlContent,
				blogType,
				primaryKeyword: primaryKeyword || undefined,
			});
 
			if (!blog.data) throw new Error("Failed to create blog");
 
			// Try to find a cover image from Pexels
			try {
				const searchQuery = primaryKeyword || title;
				const pexelsResult = await blogImagesApi.searchPexels(
					proId as string,
					searchQuery,
					1,
					5,
				);
				const photos = pexelsResult.data?.photos;
				if (photos && photos.length > 0) {
					const coverPhoto = photos[0];
					await proApi.updateMyBlog(proId as string, blog.data.id, {
						featuredImageUrl: coverPhoto.src.large,
						featuredImageAlt: coverPhoto.alt || title,
					});
				}
			} catch {
				// Cover image is optional — don't block draft creation
			}
 
			onDraftCreated(blog.data.id);
		} catch (err) {
			setError(getErrorMessage(err));
		} finally {
			setGeneratingDraft(false);
		}
	};
 
	// Pipeline progress overlay
	if (mode === "oneclick" && (jobId || pipelineStatus)) {
		return (
			<div className="max-w-xl mx-auto px-4 sm:px-0 py-8 sm:py-12">
				<div className="bg-background-elevated border border-border-default rounded-xl p-6 sm:p-8">
					{pipelineError ? (
						<>
							<div className="flex items-center gap-3 mb-4">
								<AlertCircle className="h-8 w-8 text-notification-error-text" />
								<h2 className="text-xl font-bold text-foreground-default">Generation Failed</h2>
							</div>
							<p className="text-foreground-muted mb-6">{pipelineError}</p>
							<div className="flex gap-3">
								<Button
									onClick={() => {
										setMode("form");
										setJobId(null);
										setPipelineError(null);
									}}
								>
									Try Again
								</Button>
								<Button variant="outline" onClick={onBack}>
									Go Back
								</Button>
							</div>
						</>
					) : (
						<>
							<div className="text-center mb-8">
								<Sparkles className="h-10 w-10 text-primary-500 mx-auto mb-3 animate-pulse" />
								<h2 className="text-xl font-bold mb-1 text-foreground-default">
									Generating Your Blog
								</h2>
								<p className="text-foreground-muted text-sm">
									{title
										? `"${title}"`
										: "Creating your blog post with AI..."}
								</p>
								<p className="text-foreground-subtle text-xs mt-2">
									Please stay on the page as we generate the blog
								</p>
							</div>
 
							<div className="space-y-3">
								{PIPELINE_STEPS.map((step, i) => {
									const StepIcon = step.icon;
									const isActive = step.status === pipelineStatus;
									const isComplete = pipelineStep > i + 1;
 
									return (
										<div
											key={step.status}
											className={`flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${
												isActive
													? "bg-primary-50 dark:bg-primary-900/30 border border-primary-200 dark:border-primary-700"
													: isComplete
														? "bg-success-light dark:bg-green-900/30 border border-success/20"
														: "opacity-40"
											}`}
										>
											{isComplete ? (
												<CheckCircle className="h-5 w-5 text-success flex-shrink-0" />
											) : isActive ? (
												<Loader2 className="h-5 w-5 text-primary-500 animate-spin flex-shrink-0" />
											) : (
												<StepIcon className="h-5 w-5 text-foreground-subtle flex-shrink-0" />
											)}
											<span
												className={`text-sm ${isActive ? "font-medium text-primary-600 dark:text-primary-400" : isComplete ? "text-success" : ""}`}
											>
												{step.label}
											</span>
										</div>
									);
								})}
							</div>
						</>
					)}
				</div>
			</div>
		);
	}
 
	return (
		<div className="max-w-3xl mx-auto space-y-6 px-4 sm:px-0 py-4 sm:py-0">
			<Button variant="ghost" onClick={onBack} className="mb-2 hidden sm:inline-flex">
				<ArrowLeft className="h-4 w-4 mr-1" />
				Back
			</Button>
 
			<div className="hidden sm:block">
				<h2 className="text-2xl font-bold mb-1">Start with AI</h2>
				<p className="text-foreground-muted">
					Generate a complete blog post with AI research, images, and SEO
					optimization.
				</p>
			</div>
 
			{error && (
				<div className="text-notification-error-text bg-notification-error-bg border border-notification-error-border rounded-lg p-4">
					{error}
				</div>
			)}
 
			{/* One-Click Generation Card */}
			<div className="bg-background-elevated border border-primary-500/30 rounded-xl p-6">
				<div className="flex items-start gap-4">
					<div className="flex-shrink-0 w-10 h-10 rounded-lg bg-primary-500/15 flex items-center justify-center">
						<Zap className="h-5 w-5 text-primary-500" />
					</div>
					<div className="flex-1">
						<h3 className="font-semibold text-lg mb-1">
							One-Click Blog Generation
						</h3>
						<p className="text-sm text-foreground-muted mb-4">
							AI will research trends, create an outline, write visual content
							with images, and optimize for SEO — all automatically.
						</p>
						<div className="flex flex-col sm:flex-row gap-3">
							<Button
								onClick={() => handleOneClickGenerate()}
							>
								<Zap className="h-4 w-4 mr-1" />
								Generate Full Blog
							</Button>
							<Button
								variant="outline"
								onClick={handleGetSuggestions}
								disabled={loadingSuggestions}
							>
								{loadingSuggestions ? (
									<Loader2 className="h-4 w-4 animate-spin mr-1" />
								) : (
									<Sparkles className="h-4 w-4 mr-1" />
								)}
								Get Topic Ideas
							</Button>
						</div>
					</div>
				</div>
			</div>
 
			{/* Topic Form */}
			<div className="space-y-4 bg-background-elevated border border-border-default rounded-lg p-6">
				<label className="block">
					<span className="block text-sm font-medium mb-1">
						Blog Title <span className="text-error">*</span>
					</span>
					<input
						type="text"
						data-testid="topic-input"
						value={title}
						onChange={(e) => setTitle(e.target.value)}
						placeholder="e.g., How to Choose the Perfect Color Palette"
						className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2"
					/>
				</label>
 
				<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
					<label className="block">
						<span className="block text-sm font-medium mb-1">Blog Type</span>
						<select
							value={blogType}
							onChange={(e) => setBlogType(e.target.value as BlogType)}
							className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2"
						>
							<option value="general">General</option>
							<option value="project_spotlight">Project Spotlight</option>
							<option value="hybrid">Hybrid</option>
						</select>
					</label>
					<label className="block">
						<span className="block text-sm font-medium mb-1">
							Primary Keyword
						</span>
						<input
							type="text"
							value={primaryKeyword}
							onChange={(e) => setPrimaryKeyword(e.target.value)}
							placeholder="e.g., interior design tips"
							className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2"
						/>
					</label>
				</div>
 
				<label className="block">
					<span className="block text-sm font-medium mb-1">
						Outline (optional — for manual draft)
					</span>
					<textarea
						value={outline}
						onChange={(e) => setOutline(e.target.value)}
						placeholder="Brief outline of key points..."
						rows={4}
						className="w-full rounded-md border border-border-default bg-background-elevated px-3 py-2"
					/>
				</label>
 
				<div className="flex gap-3">
					<Button
						onClick={handleGenerateDraft}
						disabled={generatingDraft || !title.trim()}
						variant="outline"
					>
						{generatingDraft ? (
							<Loader2 className="h-4 w-4 animate-spin mr-1" />
						) : (
							<FileText className="h-4 w-4 mr-1" />
						)}
						Quick Draft (No Images)
					</Button>
				</div>
			</div>
 
			{/* Suggestions Popup */}
			{showSuggestions && suggestions.length > 0 && (
				<div className="fixed inset-0 z-50 flex items-center justify-center bg-overlay-dark">
					<div
						ref={suggestionsRef}
						className="bg-background-elevated border border-border-default rounded-xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-y-auto mx-4"
					>
						<div className="flex items-center justify-between p-4 border-b border-border-default sticky top-0 bg-background-elevated z-10">
							<h3 className="text-lg font-semibold">AI Suggestions</h3>
							<button
								type="button"
								onClick={() => setShowSuggestions(false)}
								className="p-1 hover:bg-background-muted rounded-md"
								aria-label="Close suggestions"
							>
								<X className="h-5 w-5" />
							</button>
						</div>
						<div className="p-4 space-y-3">
							{suggestions.map((suggestion) => (
								<div
									key={suggestion.title}
									className="border border-border-default rounded-lg p-4 hover:border-primary-500/40 hover:bg-primary-500/5 transition-colors"
								>
									<h4 className="font-semibold mb-1">{suggestion.title}</h4>
									<p className="text-sm text-foreground-muted whitespace-pre-line mb-3">
										{suggestion.outline}
									</p>
									<div className="flex gap-2">
										<Button
											size="sm"
											onClick={() => handleOneClickGenerate(suggestion)}
										>
											<Zap className="h-3 w-3 mr-1" />
											Generate Full Blog
										</Button>
										<Button
											size="sm"
											variant="outline"
											onClick={() => handleUseSuggestion(suggestion)}
										>
											Use as Draft
										</Button>
									</div>
								</div>
							))}
						</div>
					</div>
				</div>
			)}
		</div>
	);
}