File size: 11,038 Bytes
f201243 c5771b6 f201243 da4a2eb f201243 c5771b6 8ffe335 f201243 c5771b6 f201243 c5771b6 f201243 c5771b6 f201243 c5771b6 f201243 f103b85 f201243 addcf34 c5771b6 f201243 c5771b6 da4a2eb c5771b6 f201243 8ffe335 f201243 b3adf58 f201243 addcf34 c5771b6 addcf34 c5771b6 addcf34 d4a4da7 c5771b6 d4a4da7 c5771b6 d4a4da7 c5771b6 d4a4da7 c5771b6 d4a4da7 c5771b6 f201243 9de719c f201243 addcf34 f201243 da4a2eb f201243 |
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 |
"use client";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { generateAdSchema } from "@/lib/utils/validators";
import { Input } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { Button } from "@/components/ui/Button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/Card";
import { IMAGE_MODELS, getModelCost, formatCost } from "@/lib/constants/models";
import type { Niche } from "@/types/api";
import { Loader2, TrendingUp, Check } from "lucide-react";
import apiClient from "@/lib/api/client";
import { InfoButton } from "@/components/ui/InfoButton";
interface GenerationFormProps {
onSubmit: (data: {
niche: Niche;
num_images: number;
image_model?: string | null;
target_audience?: string | null;
offer?: string | null;
use_trending?: boolean;
trending_context?: string | null;
}) => Promise<void>;
isLoading: boolean;
}
interface TrendItem {
title: string;
description: string;
url?: string;
keyword?: string;
relevance_score?: number;
}
export const GenerationForm: React.FC<GenerationFormProps> = ({
onSubmit,
isLoading,
}) => {
const [trends, setTrends] = useState<TrendItem[]>([]);
const [selectedTrend, setSelectedTrend] = useState<TrendItem | null>(null);
const [isFetchingTrends, setIsFetchingTrends] = useState(false);
const [trendsError, setTrendsError] = useState<string | null>(null);
const {
register,
handleSubmit,
formState: { errors },
watch,
setValue,
} = useForm({
resolver: zodResolver(generateAdSchema),
defaultValues: {
niche: "home_insurance" as const,
num_images: 1,
image_model: null,
target_audience: "",
offer: "",
use_trending: false,
trending_context: "",
},
});
const numImages = watch("num_images");
const currentNiche = watch("niche");
const useTrending = watch("use_trending");
const selectedModel = watch("image_model");
// Fetch trends when toggle is enabled
const handleFetchTrends = async () => {
setIsFetchingTrends(true);
setTrendsError(null);
setTrends([]);
setSelectedTrend(null);
try {
const response = await apiClient.get(`/api/trends/${currentNiche}`);
const data = response.data;
if (data.trends && data.trends.length > 0) {
setTrends(data.trends);
} else {
setTrendsError("No relevant trends found for this niche");
}
} catch (error: any) {
setTrendsError(error.message || "Failed to fetch trends");
} finally {
setIsFetchingTrends(false);
}
};
// Handle trend selection
const handleSelectTrend = (trend: TrendItem) => {
setSelectedTrend(trend);
// Set the trending context with title and description
const trendContext = `${trend.title} - ${trend.description}`;
setValue("trending_context", trendContext);
};
// Reset trends when toggle is turned off
React.useEffect(() => {
if (!useTrending) {
setTrends([]);
setSelectedTrend(null);
setTrendsError(null);
}
}, [useTrending]);
return (
<Card variant="glass">
<CardHeader>
<div className="flex items-center gap-2">
<CardTitle>Generate Ad</CardTitle>
<InfoButton
title="Standard Generation Flow"
content="This flow generates ads using randomized strategies from predefined angles and concepts. It's the fastest way to create ads with minimal configuration. The system automatically selects the best combinations based on your niche, target audience, and offer."
position="bottom"
/>
</div>
<CardDescription>
Create a new ad creative using randomized strategies
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
<Select
label="Niche"
options={[
{ value: "home_insurance", label: "Home Insurance" },
{ value: "glp1", label: "GLP-1" },
{ value: "auto_insurance", label: "Auto Insurance" },
]}
error={errors.niche?.message}
{...register("niche")}
/>
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">
Target Audience <span className="text-gray-400 font-normal">(Optional)</span>
</label>
<input
type="text"
className="w-full px-4 py-3 rounded-xl border-2 border-gray-300 bg-white/80 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-250"
placeholder="e.g., US people over 50+ age"
{...register("target_audience")}
/>
{errors.target_audience && (
<p className="text-red-500 text-xs mt-1">{errors.target_audience.message}</p>
)}
</div>
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">
Offer <span className="text-gray-400 font-normal">(Optional)</span>
</label>
<input
type="text"
className="w-full px-4 py-3 rounded-xl border-2 border-gray-300 bg-white/80 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-250"
placeholder="e.g., Don't overpay your insurance"
{...register("offer")}
/>
{errors.offer && (
<p className="text-red-500 text-xs mt-1">{errors.offer.message}</p>
)}
</div>
{/* Trending Topics – AI occasions + niche news; used in ad copy generation */}
<div className="border-t border-gray-200 pt-4">
<div className="flex items-center justify-between mb-3">
<div>
<label className="block text-sm font-semibold text-gray-700">
Use Trending Topics 🔥
</label>
<p className="text-xs text-gray-500 mt-1">
Tie your ad to current occasions and niche news for timeliness
</p>
</div>
<label className="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
className="sr-only peer"
{...register("use_trending")}
/>
<div className="w-11 h-6 bg-gray-200 rounded-full peer peer-checked:bg-blue-500 peer-focus:ring-2 peer-focus:ring-blue-300 transition-colors"></div>
</label>
</div>
{useTrending && (
<div className="mt-3 space-y-3 rounded-xl border border-gray-200 bg-gray-50/80 p-3">
<Button
type="button"
variant="secondary"
size="sm"
onClick={handleFetchTrends}
disabled={isFetchingTrends}
className="gap-2"
>
{isFetchingTrends ? <Loader2 className="h-4 w-4 animate-spin" /> : <TrendingUp className="h-4 w-4" />}
{isFetchingTrends ? "Fetching…" : "Fetch current trends"}
</Button>
{trendsError && <p className="text-sm text-red-600">{trendsError}</p>}
{trends.length > 0 && (
<div className="space-y-2">
<p className="text-xs font-medium text-gray-600">Pick one (optional – otherwise we use the top trend):</p>
<div className="max-h-40 overflow-y-auto space-y-1.5">
{trends.map((trend) => (
<button
key={trend.title}
type="button"
onClick={() => handleSelectTrend(trend)}
className={`w-full text-left px-3 py-2 rounded-lg border text-sm transition-colors ${
selectedTrend?.title === trend.title
? "border-blue-500 bg-blue-50 text-blue-800"
: "border-gray-200 bg-white hover:bg-gray-100"
}`}
>
<span className="font-medium">{trend.title}</span>
{selectedTrend?.title === trend.title && <Check className="inline h-4 w-4 ml-1 text-blue-600" />}
<p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{trend.description}</p>
</button>
))}
</div>
</div>
)}
</div>
)}
</div>
<Select
label="Image Model"
options={IMAGE_MODELS.map(model => ({ value: model.value, label: model.label }))}
error={errors.image_model?.message}
{...register("image_model")}
/>
<div>
<label className="block text-sm font-semibold text-gray-700 mb-2">
Number of Ad Images: <span className="text-blue-600 font-bold">{numImages}</span>
</label>
<input
type="range"
min="1"
max="10"
step="1"
className="w-full accent-blue-500"
{...register("num_images", { valueAsNumber: true })}
/>
<div className="flex justify-between text-xs text-gray-500 mt-1 font-medium">
<span>1</span>
<span>10</span>
</div>
<p className="text-xs text-gray-500 mt-1">
Generate multiple images for the same ad copy using the same method
</p>
{errors.num_images && (
<p className="mt-1 text-sm text-red-600">
{errors.num_images.message}
</p>
)}
</div>
{/* Cost Estimator */}
<div className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-4">
<p className="text-sm font-semibold text-gray-800">
💰 <strong>Estimated Cost:</strong> {formatCost(getModelCost(selectedModel || "", numImages))}
</p>
<p className="text-xs text-gray-600 mt-1">
{numImages} image{numImages > 1 ? 's' : ''} × {IMAGE_MODELS.find(m => m.value === (selectedModel || ""))?.label.split(' - ')[0] || "Default model"}
</p>
</div>
<Button
type="submit"
variant="primary"
size="lg"
isLoading={isLoading}
className="w-full"
>
Generate Ad
</Button>
</form>
</CardContent>
</Card>
);
};
|