The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Ads Studio and Ad Multiplier UI; product-link apps open Click to Ad
Claude76f331f25a5d
diff --git a/next.config.ts b/next.config.tsindex 9d0eae36..fb480c94 100644--- a/next.config.ts+++ b/next.config.ts@@ -12,6 +12,8 @@ const nextConfig: NextConfig = {return [{ source: "/characters", destination: "/elements", permanent: true },{ source: "/characters/:id", destination: "/elements/:id", permanent: true },+ // The product-link ad apps open the Click to Ad flow (src/lib/catalog/apps.ts).+ { source: "/apps/:id(app-click-to-ad|app-link-to-video-ad)", destination: "/marketing/click-to-ad", permanent: false },// Studio hubs have one path per mode (src/lib/hubs.ts): old `?mode=` links, and a clip handed// to Upscale or Audio without a mode, open that mode's own page (prerendered with the right studio)....["audio", "video-tools", "upscale"].map((hub) => ({diff --git a/src/app/(studio)/ads/[brandId]/page.tsx b/src/app/(studio)/ads/[brandId]/page.tsxnew file mode 100644index 00000000..db7f8769--- /dev/null+++ b/src/app/(studio)/ads/[brandId]/page.tsx@@ -0,0 +1,18 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { BrandWorkspace } from "@/components/ads/brand-workspace";++export const metadata: Metadata = { title: "Ads Studio" };++async function Workspace({ params }: { params: PageProps<"/ads/[brandId]">["params"] }) {+ const { brandId } = await params;+ return <BrandWorkspace brandId={brandId} />;+}++export default function Page({ params }: PageProps<"/ads/[brandId]">) {+ return (+ <Suspense fallback={null}>+ <Workspace params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/ads/multiplier/page.tsx b/src/app/(studio)/ads/multiplier/page.tsxnew file mode 100644index 00000000..c37a0cd9--- /dev/null+++ b/src/app/(studio)/ads/multiplier/page.tsx@@ -0,0 +1,9 @@+import type { Metadata } from "next";+import { AdMultiplier } from "@/components/ads/multiplier";+import { marketingModelInfo } from "@/components/marketing/model-info";++export const metadata: Metadata = { title: "Ad Multiplier" };++export default function Page() {+ return <AdMultiplier models={marketingModelInfo()} />;+}diff --git a/src/app/(studio)/ads/page.tsx b/src/app/(studio)/ads/page.tsxnew file mode 100644index 00000000..f97a53fe--- /dev/null+++ b/src/app/(studio)/ads/page.tsx@@ -0,0 +1,8 @@+import type { Metadata } from "next";+import { AdsHome } from "@/components/ads/ads-home";++export const metadata: Metadata = { title: "Ads Studio" };++export default function Page() {+ return <AdsHome />;+}diff --git a/src/components/ads/ad-chat.tsx b/src/components/ads/ad-chat.tsxnew file mode 100644index 00000000..9ac86d49--- /dev/null+++ b/src/components/ads/ad-chat.tsx@@ -0,0 +1,216 @@+"use client";++import { ArrowUp, AtSign, Check, Loader2, Sparkles, Trash2 } from "lucide-react";+import { useEffect, useRef, useState, useSyncExternalStore } from "react";+import { toast } from "sonner";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import type { BrandKit, Product } from "@/lib/catalog/marketing";+import { formatCost } from "@/lib/format";+import { cn } from "@/lib/utils";+import { useBrandChat, useEstimate, useStatusFlags, type ChatMessage } from "@/components/marketing/hooks";++const NAME_KEY = "fuobe:first-name";+const CHIPS = ["A lifestyle ad with the product in everyday use", "A clean studio shot with a bold headline", "A playful, colorful ad for social media"];+const PLACEHOLDERS = ["Generate 4 ads for my product…", "Change the background to a holiday setting for our winter sale…", "Make 4 ad variations to A/B test…", "Write 5 versions with different headlines and CTAs…", "Tag your product with @…"];++const nameListeners = new Set<() => void>();+function readName() {+ try {+ return localStorage.getItem(NAME_KEY) ?? "";+ } catch {+ return "";+ }+}+function useFirstName(): [string, (n: string) => void] {+ const name = useSyncExternalStore(+ (cb) => {+ nameListeners.add(cb);+ return () => nameListeners.delete(cb);+ },+ readName,+ () => "",+ );+ return [+ name,+ (n: string) => {+ try {+ localStorage.setItem(NAME_KEY, n.trim());+ } catch {}+ nameListeners.forEach((l) => l());+ },+ ];+}++function Proposal({ msg, brand, products, engine, onConfirmed }: { msg: ChatMessage; brand: BrandKit; products: Product[]; engine: "cloud" | "open"; onConfirmed: (batchId: string) => void }) {+ const { confirm } = useBrandChat(brand.id);+ const { higgsfield } = useStatusFlags();+ const p = msg.proposal!;+ const total = p.items.reduce((n, i) => n + i.count, 0);+ const est = useEstimate<{ costUsd: number | null; demo: boolean }>("/api/ads/estimate", msg.batchId ? null : { brandId: brand.id, engine, items: p.items, direction: p.direction, route: higgsfield && engine === "cloud" ? "higgsfield" : "fuobe" });+ const names = p.items.map((i) => products.find((x) => x.id === i.productId)?.name).filter(Boolean);+ return (+ <div className="mt-2 rounded-xl border bg-background p-3">+ <p className="text-[13px] font-medium">+ {total} ad{total === 1 ? "" : "s"} for {names.join(", ") || brand.name}+ </p>+ {p.direction && <p className="mt-0.5 line-clamp-2 text-[12px] text-muted-foreground">{p.direction}</p>}+ {msg.batchId ? (+ <p className="mt-2 inline-flex items-center gap-1 text-[12px] text-success">+ <Check className="size-3.5" /> On their way to the grid+ </p>+ ) : (+ <button+ type="button"+ onClick={() =>+ confirm.mutate(+ { messageId: msg.id, engine, route: higgsfield && engine === "cloud" ? "higgsfield" : "fuobe" },+ { onSuccess: (r) => (toast.success(`Generating ${total} ads`, { duration: 1500 }), onConfirmed(r.batchId)), onError: (e) => toast.error((e as Error).message) },+ )+ }+ disabled={confirm.isPending}+ className="mt-2 inline-flex h-8 items-center gap-1.5 rounded-full bg-primary px-3 text-[12px] font-medium text-primary-foreground hover:bg-primary/90"+ >+ {confirm.isPending ? <Loader2 className="size-3.5 animate-spin" /> : <Sparkles className="size-3.5" />}+ Create {total} ads{est.data ? ` · ${est.data.demo ? "demo" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`}` : ""}+ </button>+ )}+ </div>+ );+}++/** The brand chat: ask for ads in plain words, @mention products, confirm what it proposes. */+export function AdChat({ brand, products, engine, onBatch, className }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; onBatch: (batchId: string) => void; className?: string }) {+ const { query, say, clear } = useBrandChat(brand.id);+ const [name, setName] = useFirstName();+ const [text, setText] = useState("");+ const [ph, setPh] = useState(0);+ const [mention, setMention] = useState(false);+ const box = useRef<HTMLTextAreaElement>(null);+ const list = useRef<HTMLDivElement>(null);+ const messages = query.data ?? [];+ useEffect(() => {+ const t = setInterval(() => setPh((i) => (i + 1) % PLACEHOLDERS.length), 4000);+ return () => clearInterval(t);+ }, []);+ useEffect(() => {+ list.current?.scrollTo({ top: list.current.scrollHeight, behavior: "smooth" });+ }, [messages.length, say.isPending]);+ const sendText = (t: string) => {+ const v = t.trim();+ if (!v) return;+ setText("");+ say.mutate(v, { onError: (e) => toast.error((e as Error).message) });+ };+ const insert = (p: Product) => {+ setText((t) => `${t}${t && !t.endsWith(" ") ? " " : ""}@${p.name} `);+ setMention(false);+ requestAnimationFrame(() => box.current?.focus());+ };+ return (+ <aside className={cn("flex min-h-0 flex-col rounded-2xl border bg-background", className)} aria-label="Brand chat">+ <div className="flex items-center justify-between gap-2 border-b px-4 py-3">+ <p className="text-[14px] font-semibold">Chat</p>+ {messages.length > 0 && (+ <Tooltip>+ <TooltipTrigger asChild>+ <button type="button" onClick={() => clear.mutate()} className="grid size-7 place-items-center rounded-full text-muted-foreground hover:bg-accent" aria-label="Clear chat">+ <Trash2 className="size-3.5" />+ </button>+ </TooltipTrigger>+ <TooltipContent>Clear chat</TooltipContent>+ </Tooltip>+ )}+ </div>+ <div ref={list} className="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4">+ {!messages.length && (+ <div>+ <p className="font-heading text-[22px] leading-tight">+ {name ? `${name}, what` : "What"} ads should we make for {brand.name}?+ </p>+ {!name && (+ <input+ placeholder="Your first name (optional)"+ aria-label="Your first name"+ onKeyDown={(e) => e.key === "Enter" && setName((e.target as HTMLInputElement).value)}+ onBlur={(e) => e.target.value && setName(e.target.value)}+ className="mt-2 h-8 w-full rounded-lg border bg-background px-2.5 text-[12px] outline-none focus:border-primary"+ />+ )}+ <div className="mt-3 flex flex-col gap-1.5">+ {CHIPS.map((c) => (+ <button key={c} type="button" onClick={() => sendText(c)} className="rounded-xl bg-secondary px-3 py-2 text-left text-[13px] hover:bg-accent">+ {c}+ </button>+ ))}+ </div>+ </div>+ )}+ {messages.map((m) => (+ <div key={m.id} className={cn("flex", m.role === "user" ? "justify-end" : "justify-start")}>+ <div className={cn("max-w-[88%] rounded-2xl px-3 py-2 text-[13px] leading-relaxed", m.role === "user" ? "bg-brand-faint text-foreground" : "bg-muted")}>+ <p className="whitespace-pre-wrap">{m.text}</p>+ {m.role === "assistant" && m.proposal && <Proposal msg={m} brand={brand} products={products} engine={engine} onConfirmed={onBatch} />}+ </div>+ </div>+ ))}+ {say.isPending && (+ <div className="flex justify-start">+ <span className="rounded-2xl bg-muted px-3 py-2 text-[13px]">+ <span className="shimmer-text animate-shimmer-text">Thinking…</span>+ </span>+ </div>+ )}+ </div>+ <div className="border-t p-2.5">+ <div className="rounded-2xl border bg-background p-1.5 focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">+ <textarea+ ref={box}+ value={text}+ onChange={(e) => {+ setText(e.target.value);+ if (e.target.value.endsWith("@")) setMention(true);+ }}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {+ e.preventDefault();+ sendText(text);+ }+ }}+ rows={2}+ placeholder={PLACEHOLDERS[ph]}+ aria-label="Message"+ className="w-full resize-none bg-transparent px-1.5 py-1 text-[13px] outline-none placeholder:text-subtle-foreground"+ />+ <div className="flex items-center justify-between">+ <Popover open={mention} onOpenChange={setMention}>+ <PopoverTrigger asChild>+ <button type="button" className="inline-flex h-7 items-center gap-1 rounded-full px-2 text-[12px] text-muted-foreground hover:bg-accent" aria-label="Mention a product">+ <AtSign className="size-3.5" /> Mention a product+ </button>+ </PopoverTrigger>+ <PopoverContent side="top" align="start" className="w-64 p-1" collisionPadding={12}>+ {products.length ? (+ products.map((p) => (+ <button key={p.id} type="button" onClick={() => insert(p)} className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-[13px] hover:bg-accent">+ <span className="size-6 shrink-0 overflow-hidden rounded bg-muted">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {p.images[0] && <img src={p.images[0]} alt="" className="size-full object-cover" />}+ </span>+ <span className="truncate">{p.name}</span>+ </button>+ ))+ ) : (+ <p className="p-2 text-[12px] text-muted-foreground">No products yet.</p>+ )}+ </PopoverContent>+ </Popover>+ <button type="button" onClick={() => sendText(text)} disabled={!text.trim() || say.isPending} className={cn("grid size-8 place-items-center rounded-full", text.trim() ? "bg-primary text-primary-foreground" : "bg-muted text-subtle-foreground")} aria-label="Send">+ <ArrowUp className="size-4" />+ </button>+ </div>+ </div>+ </div>+ </aside>+ );+}diff --git a/src/components/ads/ads-home.tsx b/src/components/ads/ads-home.tsxnew file mode 100644index 00000000..c9cac6cc--- /dev/null+++ b/src/components/ads/ads-home.tsx@@ -0,0 +1,167 @@+"use client";++import { ArrowRight, Copy, Loader2, MoreHorizontal, Target, Trash2 } from "lucide-react";+import Link from "next/link";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Skeleton } from "@/components/ui/skeleton";+import { BrandStart } from "@/components/brand/brand-dialog";+import { ResearchLabel } from "@/components/brand/research-progress";+import type { BrandKit } from "@/lib/catalog/marketing";+import { timeAgo } from "@/lib/format";+import { cn } from "@/lib/utils";+import { useBrandActions, useBrands } from "@/components/marketing/hooks";+import { MarketingHeader, useMarketingEngine } from "@/components/marketing/shell";++function BrandCard({ brand, onDelete }: { brand: BrandKit; onDelete: () => void }) {+ const accent = brand.colors[0] ?? "#5d4bdb";+ const researching = brand.status === "researching";+ return (+ <div className="group/brand relative animate-fade-up">+ <Link href={`/ads/${brand.id}`} className="block rounded-2xl border bg-background p-3 outline-none transition-shadow hover:shadow-soft focus-visible:ring-2 focus-visible:ring-ring">+ <div className="relative flex aspect-[16/9] items-center justify-center overflow-hidden rounded-xl" style={{ background: `linear-gradient(135deg, ${accent}, ${brand.colors[1] ?? accent})` }}>+ <div className="grid h-16 w-32 place-items-center rounded-xl bg-white/90 p-2 shadow-soft">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {brand.logo ? <img src={brand.logo} alt="" className="max-h-full max-w-full object-contain" /> : <span className="truncate text-[18px] font-semibold text-black">{brand.name}</span>}+ </div>+ {researching && (+ <span className="absolute inset-x-2 bottom-2 flex items-center gap-1.5 rounded-full bg-black/55 px-2.5 py-1 text-[11px] font-medium text-white backdrop-blur">+ <Loader2 className="size-3 animate-spin" /> <ResearchLabel progress={brand.progress} />…+ </span>+ )}+ </div>+ <div className="mt-2.5 min-w-0 px-0.5">+ <h3 className="truncate text-[15px] font-medium">{brand.name}</h3>+ <p className="truncate text-[12px] text-muted-foreground">+ {researching ? "Researching…" : brand.status === "failed" ? "Research incomplete — open to retry" : `${brand.productCount ?? 0} product${brand.productCount === 1 ? "" : "s"} · ${brand.adCount ?? 0} ad${brand.adCount === 1 ? "" : "s"}`} · {timeAgo(brand.updatedAt)}+ </p>+ <div className="mt-1.5 flex gap-1">+ {brand.colors.slice(0, 6).map((c) => (+ <span key={c} className="size-3 rounded-full border" style={{ background: c }} />+ ))}+ </div>+ </div>+ </Link>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button className="absolute top-5 right-5 grid size-8 place-items-center rounded-full bg-black/45 text-white opacity-100 backdrop-blur hover:bg-black/65 focus-visible:opacity-100 data-[state=open]:opacity-100 sm:opacity-0 sm:group-hover/brand:opacity-100" aria-label={`${brand.name} actions`}>+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem asChild>+ <Link href={`/ads/${brand.id}?step=kit`}>Brand settings</Link>+ </DropdownMenuItem>+ <DropdownMenuItem variant="destructive" onClick={onDelete}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++function DeleteBrand({ brand, onClose }: { brand: BrandKit | null; onClose: () => void }) {+ const actions = useBrandActions(brand?.id ?? "");+ return (+ <AlertDialog open={!!brand} onOpenChange={(o) => !o && onClose()}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete {brand?.name}?</AlertDialogTitle>+ <AlertDialogDescription>“{brand?.name}” leaves the shelf with its kit and its products. Ads already made with it stay in your Library.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>No, keep it</AlertDialogCancel>+ <AlertDialogAction+ className="bg-destructive text-white hover:bg-destructive/90"+ onClick={() =>+ actions.remove.mutate(undefined, {+ onSuccess: () => toast("Brand deleted", { duration: 1500 }),+ onError: (e) => toast.error((e as Error).message),+ })+ }+ >+ Yes, delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}++/** Ads Studio home: start from a website (or by hand), and the brand shelf. */+export function AdsHome() {+ const router = useRouter();+ const { engine, setEngine } = useMarketingEngine();+ const brands = useBrands();+ const [deleting, setDeleting] = useState<BrandKit | null>(null);+ return (+ <div className="flex min-h-svh min-w-0 flex-col">+ <MarketingHeader title="Ads Studio" active="ads" engine={engine} onEngine={setEngine} />+ <main className="mx-auto w-full min-w-0 max-w-[1240px] flex-1 px-3 pb-20 sm:px-6">+ <section className="mx-auto max-w-[720px] pt-8 text-center sm:pt-14">+ <h2 className="font-heading text-display text-balance">Create performing static ads</h2>+ <p className="mx-auto mt-2 max-w-lg text-[15px] text-muted-foreground">Enter your website. Your logo, colours, brand voice and selling points load on their own — then on-brand ads for every product, in 1:1, 4:5 and 9:16, with headlines and CTAs.</p>+ <div className="mx-auto mt-6 max-w-[620px] rounded-[20px] border bg-background p-3 text-left shadow-soft sm:rounded-composer sm:p-4">+ <BrandStart onDone={(b) => router.push(`/ads/${b.id}`)} />+ </div>+ </section>++ <section className="mt-14">+ <div className="mb-4 flex items-end justify-between gap-3">+ <h2 className="font-heading text-[24px]">Your brands</h2>+ <span className="text-[12px] text-muted-foreground">Every brand gets its own research, products and ads</span>+ </div>+ {brands.isLoading ? (+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {Array.from({ length: 3 }, (_, i) => (+ <Skeleton key={i} className="aspect-[4/3] rounded-2xl" />+ ))}+ </div>+ ) : brands.data?.length ? (+ <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {brands.data.map((b) => (+ <BrandCard key={b.id} brand={b} onDelete={() => setDeleting(b)} />+ ))}+ </div>+ ) : (+ <div className="rounded-2xl border border-dashed px-6 py-12 text-center">+ <div className="mx-auto grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Target className="size-5" />+ </div>+ <p className="mt-4 text-[15px] font-medium">No brand kit added yet</p>+ <p className="mt-1 text-[13px] text-muted-foreground">Paste a link or create one manually to get started.</p>+ </div>+ )}+ </section>++ <section className="mt-12 grid gap-4 md:grid-cols-2">+ <Link href="/ads/multiplier" className={cn("group flex items-center gap-4 rounded-2xl border bg-background p-4 transition-shadow hover:shadow-soft")}>+ <span className="grid size-11 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">+ <Copy className="size-5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-[14px] font-medium">Try Ad Multiplier</span>+ <span className="block text-[13px] text-muted-foreground">Recreate an ad you like with your products and characters</span>+ </span>+ <ArrowRight className="size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5" />+ </Link>+ <Link href="/marketing/click-to-ad" className="group flex items-center gap-4 rounded-2xl border bg-background p-4 transition-shadow hover:shadow-soft">+ <span className="grid size-11 shrink-0 place-items-center rounded-xl bg-brand-faint text-brand-text">+ <Target className="size-5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-[14px] font-medium">Need a video ad?</span>+ <span className="block text-[13px] text-muted-foreground">Click to Ad turns a product link into a 9:16 ad with voiceover</span>+ </span>+ <ArrowRight className="size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5" />+ </Link>+ </section>+ </main>+ <DeleteBrand brand={deleting} onClose={() => setDeleting(null)} />+ </div>+ );+}diff --git a/src/components/ads/brand-workspace.tsx b/src/components/ads/brand-workspace.tsxnew file mode 100644index 00000000..1ba81ec3--- /dev/null+++ b/src/components/ads/brand-workspace.tsx@@ -0,0 +1,188 @@+"use client";++import { ArrowLeft, Loader2, MessageCircle, Plus, RefreshCw, Target } from "lucide-react";+import Link from "next/link";+import { useSearchParams } from "next/navigation";+import { Suspense, useEffect, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle } from "@/components/ui/sheet";+import { Skeleton } from "@/components/ui/skeleton";+import { BrandKitForm, BrandSummary } from "@/components/brand/brand-kit-form";+import { ResearchProgress } from "@/components/brand/research-progress";+import { cn } from "@/lib/utils";+import { useBrand, useBrandActions, useCreatives } from "@/components/marketing/hooks";+import { MarketingHeader, useMarketingEngine } from "@/components/marketing/shell";+import { AdChat } from "./ad-chat";+import { CreativeGrid } from "./creative-grid";+import { NewAds } from "./new-ads";++type Step = "kit" | "new" | "ads";++const STEPS: { id: Step; label: string }[] = [+ { id: "kit", label: "Brand kit" },+ { id: "new", label: "New ads" },+ { id: "ads", label: "Ads" },+];++function StepFromUrl({ onStep }: { onStep: (s: Step) => void }) {+ const q = useSearchParams();+ const done = useRef(false);+ useEffect(() => {+ if (done.current) return;+ done.current = true;+ const s = q.get("step");+ if (s === "kit" || s === "new" || s === "ads") onStep(s);+ }, [q, onStep]);+ return null;+}++/** One brand in Ads Studio: research → review the kit → products and counts → the grid, with the brand chat. */+export function BrandWorkspace({ brandId }: { brandId: string }) {+ const { engine, setEngine } = useMarketingEngine();+ const view = useBrand(brandId);+ const creatives = useCreatives(brandId);+ const actions = useBrandActions(brandId);+ const [step, setStep] = useState<Step | null>(null);+ const [chat, setChat] = useState(false);+ const brand = view.data?.brand;+ const products = view.data?.products ?? [];+ // First visit after the research: review the kit; with ads already made: the grid.+ const current: Step = step ?? (creatives.data?.length ? "ads" : brand?.status === "ready" && !products.length ? "kit" : creatives.isLoading ? "ads" : "kit");+ const wasResearching = useRef(false);+ useEffect(() => {+ if (brand?.status === "researching") wasResearching.current = true;+ else if (wasResearching.current && brand?.status === "ready") {+ wasResearching.current = false;+ setStep("kit");+ toast.success("Your Brand Kit is ready", { description: "Review it — everything here shapes your ads." });+ }+ }, [brand?.status]);++ if (view.error) {+ return (+ <div className="flex min-h-svh flex-col">+ <MarketingHeader title="Ads Studio" active="ads" />+ <div className="mx-auto max-w-md px-4 pt-[14vh] text-center">+ <h2 className="font-heading text-[26px]">This brand isn't on the shelf</h2>+ <p className="mt-2 text-muted-foreground">It may have been deleted.</p>+ <Button asChild className="mt-6">+ <Link href="/ads">Back to Ads Studio</Link>+ </Button>+ </div>+ </div>+ );+ }++ const chatPanel = brand && <AdChat brand={brand} products={products} engine={engine} onBatch={() => (setStep("ads"), setChat(false))} className="h-full" />;++ return (+ <div className="flex min-h-svh min-w-0 flex-col">+ <MarketingHeader+ title={brand?.name ?? "Ads Studio"}+ active="ads"+ engine={engine}+ onEngine={setEngine}+ right={+ brand?.status === "ready" ? (+ <Button variant="ghost" size="sm" className="xl:hidden" onClick={() => setChat(true)} aria-label="Open the brand chat">+ <MessageCircle /> <span className="hidden sm:inline">Chat</span>+ </Button>+ ) : null+ }+ />+ <Suspense fallback={null}>+ <StepFromUrl onStep={setStep} />+ </Suspense>+ <div className="mx-auto flex w-full min-w-0 max-w-[1440px] flex-1 gap-6 px-3 pt-5 pb-16 sm:px-6">+ <main className="min-w-0 flex-1">+ <Link href="/ads" className="mb-4 inline-flex items-center gap-1 text-[13px] text-muted-foreground hover:text-foreground">+ <ArrowLeft className="size-3.5" /> All brands+ </Link>+ {!brand ? (+ <div className="space-y-3">+ <Skeleton className="h-16 w-72 rounded-xl" />+ <Skeleton className="h-64 rounded-2xl" />+ </div>+ ) : brand.status === "researching" ? (+ <div className="pt-[8vh]">+ <ResearchProgress brand={brand} onCancel={() => actions.cancel.mutate()} canceling={actions.cancel.isPending} />+ </div>+ ) : (+ <>+ <div className="flex flex-wrap items-center justify-between gap-3">+ <BrandSummary brand={brand} />+ <nav aria-label="Steps" className="inline-flex rounded-full bg-muted p-0.5">+ {STEPS.map((s) => (+ <button key={s.id} type="button" aria-current={current === s.id ? "step" : undefined} onClick={() => setStep(s.id)} className={cn("h-8 rounded-full px-3.5 text-[13px] font-medium text-muted-foreground", current === s.id && "bg-background text-foreground shadow-soft")}>+ {s.label}+ {s.id === "ads" && creatives.data?.length ? <span className="ml-1 font-mono text-[11px] text-muted-foreground">{creatives.data.length}</span> : null}+ </button>+ ))}+ </nav>+ </div>+ {(brand.note || brand.error || brand.status === "canceled") && (+ <div className="mt-4 flex flex-wrap items-center justify-between gap-3 rounded-xl bg-highlight/20 px-4 py-3 text-[13px]">+ <span>{brand.error ?? brand.note ?? "Research canceled — the kit keeps what it found."}</span>+ {brand.website && (+ <Button variant="outline" size="sm" onClick={() => actions.retry.mutate(undefined, { onError: (e) => toast.error((e as Error).message) })} disabled={actions.retry.isPending}>+ {actions.retry.isPending ? <Loader2 className="animate-spin" /> : <RefreshCw />} Retry research+ </Button>+ )}+ </div>+ )}+ <div className="mt-5">+ {current === "kit" && (+ <>+ <div className="mb-3 flex flex-wrap items-end justify-between gap-2">+ <div>+ <h2 className="font-heading text-[26px] leading-tight">Review your brand kit</h2>+ <p className="text-[13px] text-muted-foreground">Everything here shapes your ads, so edit anything that's off.</p>+ </div>+ <Button onClick={() => setStep("new")}>+ Continue to products <Plus />+ </Button>+ </div>+ <BrandKitForm key={brand.id} brand={brand} />+ </>+ )}+ {current === "new" && <NewAds brand={brand} products={products} engine={engine} onCreated={() => setStep("ads")} />}+ {current === "ads" &&+ (creatives.isLoading ? (+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ {Array.from({ length: 4 }, (_, i) => (+ <Skeleton key={i} className="aspect-[4/5] rounded-xl" />+ ))}+ </div>+ ) : creatives.data?.length ? (+ <CreativeGrid brand={brand} products={products} creatives={creatives.data} />+ ) : (+ <div className="rounded-2xl border border-dashed px-6 py-14 text-center">+ <div className="mx-auto grid size-12 place-items-center rounded-2xl bg-brand-faint text-brand-text">+ <Target className="size-5" />+ </div>+ <p className="mt-4 font-heading text-[22px]">No ads yet</p>+ <p className="mt-1 text-[13px] text-muted-foreground">Pick products and how many ads to make — or just ask in the chat.</p>+ <Button className="mt-5" onClick={() => setStep("new")}>+ <Plus /> Create ads+ </Button>+ </div>+ ))}+ </div>+ </>+ )}+ </main>+ {brand?.status === "ready" && <div className="sticky top-28 hidden h-[calc(100svh-8rem)] w-[340px] shrink-0 xl:block">{chatPanel}</div>}+ </div>+ <Sheet open={chat} onOpenChange={setChat}>+ <SheetContent side="right" className="w-full gap-0 p-0 sm:max-w-md">+ <SheetHeader className="sr-only">+ <SheetTitle>Brand chat</SheetTitle>+ <SheetDescription>Ask for ads in plain words</SheetDescription>+ </SheetHeader>+ <div className="h-full p-2">{chat && chatPanel}</div>+ </SheetContent>+ </Sheet>+ </div>+ );+}diff --git a/src/components/ads/clip-range.tsx b/src/components/ads/clip-range.tsxnew file mode 100644index 00000000..cb9e20cc--- /dev/null+++ b/src/components/ads/clip-range.tsx@@ -0,0 +1,94 @@+"use client";++import { Play, Scissors } from "lucide-react";+import { useEffect, useRef } from "react";+import { clampClip, initialClip, MULTIPLIER, type ClipRange as Range } from "@/lib/catalog/marketing";+import { cn } from "@/lib/utils";++const r1 = (n: number) => Math.round(n * 10) / 10;+const fmt = (s: number) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;++/**+ * A plain in/out picker for the reference ad: the player, a bar showing the kept part, two time+ * fields and "set from the playhead" buttons. (A drop-in for a fuller trimmer later.)+ */+export function ClipRange({ src, duration, value, onChange, onDuration, className }: { src: string; duration: number | null; value: Range | null; onChange: (r: Range) => void; onDuration: (d: number) => void; className?: string }) {+ const video = useRef<HTMLVideoElement>(null);+ const stopAt = useRef<number | null>(null);+ useEffect(() => {+ const v = video.current;+ if (!v) return;+ const tick = () => {+ if (stopAt.current != null && v.currentTime >= stopAt.current) {+ v.pause();+ stopAt.current = null;+ }+ };+ v.addEventListener("timeupdate", tick);+ return () => v.removeEventListener("timeupdate", tick);+ }, []);+ const d = duration ?? 0;+ const range = value ?? (d ? initialClip(d) : null);+ const length = range ? range.end - range.start : 0;+ const outside = !!range && (length < MULTIPLIER.minSeconds - 0.05 || length > MULTIPLIER.maxSeconds + 0.05);+ const set = (k: "start" | "end", n: number) => range && d && onChange(clampClip({ ...range, [k]: n }, d, k));+ const here = (k: "start" | "end") => video.current && set(k, video.current.currentTime);+ const preview = () => {+ const v = video.current;+ if (!v || !range) return;+ v.currentTime = range.start;+ stopAt.current = range.end;+ void v.play();+ };+ return (+ <div className={cn("min-w-0", className)}>+ <video+ ref={video}+ src={src}+ controls+ playsInline+ preload="metadata"+ onLoadedMetadata={(e) => Number.isFinite(e.currentTarget.duration) && onDuration(e.currentTarget.duration)}+ className="mx-auto max-h-[46vh] w-full rounded-xl bg-black object-contain"+ aria-label="Reference ad"+ />+ {range && d > 0 && (+ <div className="mt-3 space-y-2.5">+ <div className="relative h-2 rounded-full bg-muted" aria-hidden>+ <div className={cn("absolute inset-y-0 rounded-full", outside ? "bg-destructive/60" : "bg-primary")} style={{ left: `${(range.start / d) * 100}%`, width: `${(length / d) * 100}%` }} />+ </div>+ <div className="flex flex-wrap items-end gap-2">+ {(["start", "end"] as const).map((k) => (+ <div key={k} className="flex items-end gap-1">+ <label className="block">+ <span className="mb-1 block text-[11px] font-medium text-muted-foreground">{k === "start" ? "In (s)" : "Out (s)"}</span>+ <input+ type="number"+ min={0}+ max={r1(d)}+ step={0.1}+ value={range[k]}+ onChange={(e) => {+ const n = parseFloat(e.target.value);+ if (Number.isFinite(n)) set(k, n);+ }}+ className="h-8 w-20 rounded-lg border bg-background px-2 font-mono text-[13px] tabular-nums outline-none focus:border-primary"+ />+ </label>+ <button type="button" onClick={() => here(k)} className="inline-flex h-8 items-center gap-1 rounded-lg bg-secondary px-2 text-[12px] font-medium hover:bg-accent" title={`Set the ${k === "start" ? "in" : "out"} point at the playhead`}>+ <Scissors className="size-3" /> {k === "start" ? "Set in here" : "Set out here"}+ </button>+ </div>+ ))}+ <button type="button" onClick={preview} className="inline-flex h-8 items-center gap-1 rounded-lg px-2 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground">+ <Play className="size-3" /> Play the cut+ </button>+ </div>+ <p className={cn("text-[12px]", outside ? "text-destructive" : "text-muted-foreground")} role={outside ? "alert" : undefined}>+ {fmt(range.start)} – {fmt(range.end)} · {length.toFixed(1)} s of {d.toFixed(1)} s{outside ? ` — the reference must be ${MULTIPLIER.minSeconds}–${MULTIPLIER.maxSeconds} s` : ""}+ </p>+ </div>+ )}+ </div>+ );+}diff --git a/src/components/ads/creative-grid.tsx b/src/components/ads/creative-grid.tsxnew file mode 100644index 00000000..474945c7--- /dev/null+++ b/src/components/ads/creative-grid.tsx@@ -0,0 +1,193 @@+"use client";++import { AlertCircle, Download, FolderDown, Loader2, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";+import { useMemo, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { AD_ANGLES, AD_RATIOS, creativeStatusText, type AdCreative, type AdRatio, type BrandKit, type Product } from "@/lib/catalog/marketing";+import { cn } from "@/lib/utils";+import { useCreativeActions } from "@/components/marketing/hooks";+import { AdCanvas } from "./ad-canvas";+import { AdEditor, downloadFormats, renderInput } from "./ad-editor";+import { defaultLayout, exportName, type AdLayout } from "./layout";+import { downloadBlob, exportPng } from "./render";+import { zipFiles } from "./zip";++const layoutOf = (c: AdCreative, ratio: string) => (c.layout as AdLayout | null) ?? defaultLayout(ratio, c.position);++function CreativeCard({ c, brand, ratio, product, n, onEdit }: { c: AdCreative; brand: BrandKit; ratio: AdRatio; product?: Product; n: number; onEdit: () => void }) {+ const { retry, remove } = useCreativeActions(brand.id);+ const ready = c.status === "ready" && !!c.image;+ const failed = c.status === "failed" || c.status === "canceled";+ const angle = AD_ANGLES.find((a) => a.id === c.angle)?.name;+ return (+ <article className="group/ad min-w-0 animate-fade-up">+ <div className="relative">+ {ready || c.headline ? (+ <button type="button" onClick={onEdit} disabled={!ready} className="block w-full overflow-hidden rounded-xl outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label={`Edit ad: ${c.headline || "ad"}`}>+ <AdCanvas lazy label={c.headline || "Ad"} input={renderInput({ ratio, layout: layoutOf(c, ratio), text: c, brand, image: c.image, baked: c.baked })} className="rounded-xl" />+ </button>+ ) : (+ <div className="relative overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio.replace(":", " / ") }} />+ )}+ {!ready && (+ <div className={cn("absolute inset-0 flex flex-col justify-end rounded-xl p-3", failed ? "bg-background/85" : "bg-gradient-to-t from-background/90 via-background/30 to-transparent")}>+ {!failed && <div className="skeleton-sweep absolute inset-0 animate-skeleton rounded-xl" />}+ <div className="relative">+ {failed ? (+ <>+ <p className="flex items-center gap-1.5 text-[13px] font-medium">+ <AlertCircle className="size-3.5 text-destructive" /> {c.status === "canceled" ? "Canceled before it was made" : "Creative generation failed"}+ </p>+ {c.error && <p className="mt-1 line-clamp-3 text-[12px] text-muted-foreground">{c.error}</p>}+ <button+ type="button"+ onClick={() => retry.mutate(c.id, { onError: (e) => toast.error((e as Error).message) })}+ className="mt-2 inline-flex h-7 items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent"+ title="Retry uses credits again"+ >+ {retry.isPending ? <Loader2 className="size-3 animate-spin" /> : <RotateCcw className="size-3" />} Retry+ </button>+ </>+ ) : (+ <p className="shimmer-text animate-shimmer-text text-[13px] font-medium">{creativeStatusText(c.status)}</p>+ )}+ </div>+ </div>+ )}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button className="absolute top-2 right-2 grid size-8 place-items-center rounded-full bg-black/45 text-white opacity-100 backdrop-blur hover:bg-black/65 focus-visible:opacity-100 data-[state=open]:opacity-100 sm:opacity-0 sm:group-hover/ad:opacity-100" aria-label="Ad actions">+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {ready && (+ <>+ <DropdownMenuItem onClick={onEdit}>+ <Pencil /> Edit words and layout+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void downloadFormats({ brand: brand.name, product: product?.name, n }, [renderInput({ ratio, layout: layoutOf(c, ratio), text: c, brand, image: c.image, baked: c.baked })])}>+ <Download /> Download {ratio}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void downloadFormats({ brand: brand.name, product: product?.name, n }, AD_RATIOS.map((r) => renderInput({ ratio: r, layout: layoutOf(c, r), text: c, brand, image: c.image, baked: c.baked })))}>+ <FolderDown /> Download all formats+ </DropdownMenuItem>+ </>+ )}+ {failed && (+ <DropdownMenuItem onClick={() => retry.mutate(c.id)}>+ <RotateCcw /> Retry+ </DropdownMenuItem>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onClick={() => remove.mutate(c.id)}>+ <Trash2 /> Remove from grid+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ <p className="mt-1.5 truncate px-0.5 text-[12px] text-muted-foreground">{[product?.name, angle].filter(Boolean).join(" · ") || "Ad"}</p>+ </article>+ );+}++/** The creative grid: format preview, product filter, split by product, Download all, editor. */+export function CreativeGrid({ brand, products, creatives }: { brand: BrandKit; products: Product[]; creatives: AdCreative[] }) {+ const { update, save } = useCreativeActions(brand.id);+ const [ratio, setRatio] = useState<AdRatio>("4:5");+ const [filter, setFilter] = useState("all");+ const [split, setSplit] = useState(false);+ const [editing, setEditing] = useState<AdCreative | null>(null);+ const [zipping, setZipping] = useState(false);+ const byId = useMemo(() => new Map(products.map((p) => [p.id, p])), [products]);+ const shown = creatives.filter((c) => filter === "all" || c.productId === filter);+ const ready = shown.filter((c) => c.status === "ready" && c.image);+ const pending = creatives.filter((c) => c.status === "writing" || c.status === "queued" || c.status === "rendering").length;+ const number = new Map(creatives.map((c, i) => [c.id, creatives.length - i]));+ const groups = split ? products.filter((p) => shown.some((c) => c.productId === p.id)).map((p) => ({ key: p.id, title: p.name, items: shown.filter((c) => c.productId === p.id) })) : [{ key: "all", title: "", items: shown }];++ const downloadAll = async () => {+ if (!ready.length) return void toast("No finished ads to download yet");+ setZipping(true);+ const id = toast.loading(`Preparing ${ready.length} ad${ready.length === 1 ? "" : "s"}…`);+ try {+ const files = [];+ for (const c of ready) {+ const blob = await exportPng(renderInput({ ratio, layout: layoutOf(c, ratio), text: c, brand, image: c.image, baked: c.baked }));+ files.push({ name: exportName(brand.name, byId.get(c.productId ?? "")?.name, ratio, number.get(c.id) ?? 0), data: new Uint8Array(await blob.arrayBuffer()) });+ }+ downloadBlob(new Blob([zipFiles(files) as BlobPart], { type: "application/zip" }), `${exportName(brand.name, undefined, ratio, ready.length).replace(/\.png$/, "")}-ads.zip`);+ toast.success("Downloaded", { id, duration: 1500 });+ } catch (e) {+ toast.error((e as Error).message, { id });+ } finally {+ setZipping(false);+ }+ };++ return (+ <section aria-label="Ads">+ {pending > 0 && <p className="mb-3 text-[13px] text-muted-foreground">Generating {pending} ad{pending === 1 ? "" : "s"} — they land in the grid as they render.</p>}+ <div className="mb-4 flex flex-wrap items-center gap-2">+ <div role="radiogroup" aria-label="Format" className="inline-flex rounded-full bg-muted p-0.5">+ {AD_RATIOS.map((r) => (+ <button key={r} role="radio" aria-checked={ratio === r} onClick={() => setRatio(r)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", ratio === r && "bg-background text-foreground shadow-soft")}>+ {r}+ </button>+ ))}+ </div>+ <Select value={filter} onValueChange={setFilter}>+ <SelectTrigger className="h-8 w-44" aria-label="Filter by product">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="all">All products</SelectItem>+ {products.map((p) => (+ <SelectItem key={p.id} value={p.id}>+ {p.name}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <label className="flex items-center gap-2 text-[13px] text-muted-foreground">+ <Switch checked={split} onCheckedChange={setSplit} aria-label="Split by products" /> Split by products+ </label>+ <Button variant="outline" size="sm" className="ml-auto" onClick={() => void downloadAll()} disabled={zipping || !ready.length}>+ {zipping ? <Loader2 className="animate-spin" /> : <FolderDown />} Download all+ </Button>+ </div>+ {groups.map((g) => (+ <div key={g.key} className="mb-8">+ {g.title && <h3 className="mb-3 text-[14px] font-semibold">{g.title}</h3>}+ <div className={cn("grid gap-x-3 gap-y-5", ratio === "9:16" ? "grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6" : "grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5")}>+ {g.items.map((c) => (+ <CreativeCard key={c.id} c={c} brand={brand} ratio={ratio} product={byId.get(c.productId ?? "")} n={number.get(c.id) ?? 0} onEdit={() => setEditing(c)} />+ ))}+ </div>+ </div>+ ))}+ {editing && (+ <AdEditor+ open+ onOpenChange={(o) => !o && setEditing(null)}+ title={`${byId.get(editing.productId ?? "")?.name ?? brand.name} · ${AD_ANGLES.find((a) => a.id === editing.angle)?.name ?? "Ad"}`}+ image={editing.image}+ baked={editing.baked}+ ratios={[ratio, ...AD_RATIOS.filter((r) => r !== ratio)]}+ initial={{ headline: editing.headline, body: editing.body, cta: editing.cta, layout: layoutOf(editing, ratio) }}+ brand={brand}+ productName={byId.get(editing.productId ?? "")?.name}+ number={number.get(editing.id)}+ onSaveText={(t) => update.mutate({ id: editing.id, headline: t.headline, body: t.body, cta: t.cta, layout: t.layout }, { onSuccess: () => toast("Saved", { duration: 1200 }), onError: (e) => toast.error((e as Error).message) })}+ onSaveToLibrary={async (url, r) => {+ await save.mutateAsync({ id: editing.id, url, ratio: r });+ }}+ />+ )}+ </section>+ );+}diff --git a/src/components/ads/frames.ts b/src/components/ads/frames.tsnew file mode 100644index 00000000..ffbffbe6--- /dev/null+++ b/src/components/ads/frames.ts@@ -0,0 +1,62 @@+"use client";++import { uploadFile } from "@/lib/api";++/** Resolve on an element event, or reject after `ms` (a clip the browser can't decode never fires). */+function once(el: HTMLMediaElement, event: string, ms = 8000): Promise<void> {+ return new Promise((resolve, reject) => {+ const t = setTimeout(() => (cleanup(), reject(new Error("timeout"))), ms);+ const ok = () => (cleanup(), resolve());+ const bad = () => (cleanup(), reject(new Error("unreadable")));+ const cleanup = () => {+ clearTimeout(t);+ el.removeEventListener(event, ok);+ el.removeEventListener("error", bad);+ };+ el.addEventListener(event, ok, { once: true });+ el.addEventListener("error", bad, { once: true });+ });+}++/** One frame of a (same-origin) clip at `t` seconds, as a JPEG; null when this browser can't read it. */+export async function grabFrame(src: string, t: number): Promise<Blob | null> {+ if (typeof document === "undefined") return null;+ const v = document.createElement("video");+ v.muted = true;+ v.playsInline = true;+ v.preload = "auto";+ v.src = src;+ try {+ await once(v, "loadeddata");+ const at = Math.min(Math.max(0, t), Math.max(0, (v.duration || t) - 0.05));+ if (Math.abs(v.currentTime - at) > 0.01) {+ const seeked = once(v, "seeked");+ v.currentTime = at;+ await seeked;+ }+ if (!v.videoWidth || !v.videoHeight) return null;+ const c = document.createElement("canvas");+ c.width = v.videoWidth;+ c.height = v.videoHeight;+ const ctx = c.getContext("2d");+ if (!ctx) return null;+ ctx.drawImage(v, 0, 0);+ return await new Promise<Blob | null>((r) => c.toBlob(r, "image/jpeg", 0.92));+ } catch {+ return null;+ } finally {+ v.removeAttribute("src");+ v.load();+ }+}++/** Grab a frame and upload it; resolves the /api/files URL, or undefined (the server falls back). */+export async function uploadFrame(src: string, t: number, name: string): Promise<string | undefined> {+ const blob = await grabFrame(src, t);+ if (!blob) return undefined;+ try {+ return (await uploadFile(new File([blob], `${name}.jpg`, { type: "image/jpeg" }))).url;+ } catch {+ return undefined;+ }+}diff --git a/src/components/ads/multiplier.tsx b/src/components/ads/multiplier.tsxnew file mode 100644index 00000000..18b49dad--- /dev/null+++ b/src/components/ads/multiplier.tsx@@ -0,0 +1,465 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { Copy, FileVideo, ImagePlus, Library, Loader2, Minus, Plus, RefreshCw, Sparkles, Upload, X } from "lucide-react";+import { useMemo, useRef, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Switch } from "@/components/ui/switch";+import { areaCls } from "@/components/brand/fields";+import { uploadImages } from "@/components/brand/image-list";+import { fileToSlot, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";+import { initialClip, mentionedImages, MULTIPLIER, MULTIPLIER_MODELS, multiplierResolution, type ClipRange as Range, type MarketingRun, type RunEstimate } from "@/lib/catalog/marketing";+import { formatCost } from "@/lib/format";+import { cn } from "@/lib/utils";+import { addRuns, send, useEstimate, useStatusFlags } from "@/components/marketing/hooks";+import type { ModelInfo } from "@/components/marketing/model-info";+import { RunsList } from "@/components/marketing/runs";+import { EmptyIcon, MarketingHeader, useMarketingEngine } from "@/components/marketing/shell";+import { ClipRange } from "./clip-range";+import { uploadFrame } from "./frames";++type Quality = (typeof MULTIPLIER.qualities)[number];++const Seg = <T extends string>({ value, options, onChange, label }: { value: T; options: { id: T; label: string; title?: string }[]; onChange: (v: T) => void; label: string }) => (+ <div role="radiogroup" aria-label={label} className="inline-flex rounded-full bg-muted p-0.5">+ {options.map((o) => (+ <button key={o.id} type="button" role="radio" aria-checked={value === o.id} title={o.title} onClick={() => onChange(o.id)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", value === o.id && "bg-background text-foreground shadow-soft")}>+ {o.label}+ </button>+ ))}+ </div>+);++/** The reference ad: drop, upload or pick a clip (4–30 s). */+function ReferenceDrop({ onFile, onPick }: { onFile: (f: File) => void; onPick: (v: SlotValue) => void }) {+ const input = useRef<HTMLInputElement>(null);+ const [over, setOver] = useState(false);+ const [lib, setLib] = useState(false);+ return (+ <div+ onDragOver={(e) => (e.preventDefault(), setOver(true))}+ onDragLeave={() => setOver(false)}+ onDrop={(e) => {+ e.preventDefault();+ setOver(false);+ const f = e.dataTransfer.files[0];+ if (f) onFile(f);+ }}+ className={cn("flex aspect-[4/3] flex-col items-center justify-center rounded-2xl border-2 border-dashed border-border-strong p-6 text-center transition-colors sm:aspect-video", over && "border-primary bg-brand-faint")}+ >+ <EmptyIcon icon={FileVideo} />+ <p className="mt-4 text-[15px] font-medium">Upload the ad you want more of</p>+ <p className="mt-1 text-[13px] text-muted-foreground">+ MP4, MOV or WebM · {MULTIPLIER.minSeconds}–{MULTIPLIER.maxSeconds} seconds (trim a longer one here)+ </p>+ <div className="mt-4 flex flex-wrap justify-center gap-2">+ <Button onClick={() => input.current?.click()}>+ <Upload /> Upload video+ </Button>+ <Popover open={lib} onOpenChange={setLib}>+ <PopoverTrigger asChild>+ <Button variant="outline">+ <Library /> From library+ </Button>+ </PopoverTrigger>+ <PopoverContent className="w-80 p-2" collisionPadding={12}>+ <p className="px-1 pb-2 text-[13px] font-medium">Your videos</p>+ {lib && <LibraryGrid kinds={["video"]} onPick={(v) => (onPick(v), setLib(false))} />}+ </PopoverContent>+ </Popover>+ </div>+ <input+ ref={input}+ type="file"+ accept="video/mp4,video/webm,video/quicktime"+ hidden+ onChange={(e) => {+ const f = e.target.files?.[0];+ if (f) onFile(f);+ e.target.value = "";+ }}+ />+ </div>+ );+}++/** Up to 20 pictures, each named @image_N; tap one to mention it in the prompt. */+function MentionImages({ value, onChange, onMention, max }: { value: string[]; onChange: (v: string[]) => void; onMention?: (n: number) => void; max: number }) {+ const input = useRef<HTMLInputElement>(null);+ const [busy, setBusy] = useState(0);+ const [lib, setLib] = useState(false);+ const add = async (files: File[]) => {+ const room = max - value.length;+ if (room <= 0) return void toast(`Up to ${max} images`);+ setBusy(Math.min(room, files.length));+ const urls = await uploadImages(files.slice(0, room));+ setBusy(0);+ if (urls.length) onChange([...value, ...urls].slice(0, max));+ };+ return (+ <div+ className="flex flex-wrap gap-2"+ onDragOver={(e) => e.preventDefault()}+ onDrop={(e) => {+ e.preventDefault();+ void add([...e.dataTransfer.files]);+ }}+ >+ {value.map((src, i) => (+ <div key={src} className="group/img relative size-16 shrink-0 overflow-hidden rounded-xl bg-muted">+ <button type="button" onClick={() => onMention?.(i + 1)} disabled={!onMention} className="block size-full outline-none focus-visible:ring-2 focus-visible:ring-ring" aria-label={onMention ? `Mention @image_${i + 1} in the prompt` : `Image ${i + 1}`}>+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img src={src} alt="" className="size-full object-cover" />+ <span className="absolute inset-x-0 bottom-0 bg-black/55 py-0.5 text-center font-mono text-[10px] text-white">@image_{i + 1}</span>+ </button>+ <button type="button" aria-label={`Remove image ${i + 1}`} onClick={() => onChange(value.filter((x) => x !== src))} className="absolute top-1 right-1 grid size-5 place-items-center rounded-full bg-black/55 text-white opacity-100 focus-visible:opacity-100 sm:opacity-0 sm:group-hover/img:opacity-100">+ <X className="size-3" />+ </button>+ </div>+ ))}+ {Array.from({ length: busy }, (_, i) => (+ <div key={`b${i}`} className="grid size-16 shrink-0 place-items-center rounded-xl bg-muted">+ <Loader2 className="size-4 animate-spin text-muted-foreground" />+ </div>+ ))}+ {value.length + busy < max && (+ <div className="relative flex size-16 shrink-0 flex-col overflow-hidden rounded-xl border border-dashed border-border-strong">+ <button type="button" onClick={() => input.current?.click()} className="flex flex-1 flex-col items-center justify-center gap-0.5 text-[10px] text-muted-foreground hover:bg-brand-faint hover:text-brand-text" aria-label="Add images">+ <ImagePlus className="size-4" />+ Add+ </button>+ <Popover open={lib} onOpenChange={setLib}>+ <PopoverTrigger asChild>+ <button type="button" className="flex h-5 items-center justify-center border-t border-dashed border-border-strong text-muted-foreground hover:bg-brand-faint hover:text-brand-text" aria-label="Choose images from your library">+ <Library className="size-3" />+ </button>+ </PopoverTrigger>+ <PopoverContent className="w-80 p-2" align="start" collisionPadding={12}>+ <p className="px-1 pb-2 text-[13px] font-medium">From your library</p>+ {lib && (+ <LibraryGrid+ kinds={["image"]}+ onPick={(v) => {+ if (!value.includes(v.ref)) onChange([...value, v.ref].slice(0, max));+ setLib(false);+ }}+ />+ )}+ </PopoverContent>+ </Popover>+ <input+ ref={input}+ type="file"+ accept="image/png,image/jpeg,image/webp"+ multiple+ hidden+ onChange={(e) => {+ void add([...(e.target.files ?? [])]);+ e.target.value = "";+ }}+ />+ </div>+ )}+ </div>+ );+}++/** Ad Multiplier: a reference ad (4–30 s) → new versions: recreated from a prompt, or with a new hook / CTA. */+export function AdMultiplier({ models }: { models: Record<string, ModelInfo> }) {+ const qc = useQueryClient();+ const { engine, setEngine } = useMarketingEngine();+ const { higgsfield } = useStatusFlags();+ const [video, setVideo] = useState<SlotValue | null>(null);+ const [duration, setDuration] = useState<number | null>(null);+ const [range, setRange] = useState<Range | null>(null);+ const [images, setImages] = useState<string[]>([]);+ const [prompt, setPrompt] = useState("");+ const [hookOn, setHookOn] = useState(false);+ const [ctaOn, setCtaOn] = useState(false);+ const [hook, setHook] = useState("");+ const [cta, setCta] = useState("");+ const [quality, setQuality] = useState<Quality>("720p");+ const [picked, setPicked] = useState<string | null>(null);+ const [versions, setVersions] = useState(1);+ const [busy, setBusy] = useState<string | null>(null);+ const box = useRef<HTMLTextAreaElement>(null);+ const resultsRef = useRef<HTMLDivElement>(null);++ const sections = hookOn || ctaOn;+ const choices = MULTIPLIER_MODELS[engine];+ const fallback = engine === "cloud" && !higgsfield ? "kling-o3" : choices[0].id;+ const modelId = picked && choices.some((c) => c.id === picked) ? picked : fallback;+ const model = models[modelId];+ const maxImages = engine === "open" ? 1 : (model?.maxImages ?? 0);+ const cut = range ?? (duration ? initialClip(duration) : null);+ const length = cut ? cut.end - cut.start : 0;+ const ready = !!video && !video.uploading && !!video.ref && duration != null && !!cut;++ /** A new reference (a library pick, or an upload that reports its preview first, then its server URL). */+ const startVideo = () => {+ setDuration(null);+ setRange(null);+ };+ const onFile = (f: File) => {+ if (!f.type.startsWith("video/") && !/\.(mp4|mov|webm|m4v)$/i.test(f.name)) return void toast("Video only — drop a clip here");+ startVideo();+ void fileToSlot(f, setVideo, "video");+ };+ const onDuration = (d: number) => {+ const first = duration == null;+ setDuration(d);+ setRange((r) => r ?? initialClip(d));+ if (!first) return;+ if (d > MULTIPLIER.maxSeconds + 0.05) toast(`Using the first ${MULTIPLIER.maxSeconds} s — move the in and out points to pick another part`, { id: "mult-trim" });+ if (d < MULTIPLIER.minSeconds - 0.05) toast.error(`That clip is ${d.toFixed(1)} s — the reference needs ${MULTIPLIER.minSeconds}–${MULTIPLIER.maxSeconds} s`, { id: "mult-trim" });+ };++ const body = useMemo(() => {+ if (!ready || !video || !cut || duration == null) return null;+ return {+ engine,+ video: video.ref,+ duration,+ start: cut.start,+ end: cut.end,+ images: images.length ? images : undefined,+ mode: sections ? "sections" : "prompt",+ prompt: sections ? undefined : prompt.trim() || undefined,+ hook: hookOn ? hook : null,+ cta: ctaOn ? cta : null,+ quality,+ modelId: sections ? undefined : modelId,+ versions,+ };+ }, [ready, video, cut, duration, engine, images, sections, prompt, hookOn, hook, ctaOn, cta, quality, modelId, versions]);+ // Prices are quoted as if the in/out frames were read here (they're grabbed when you press Generate).+ const estBody = useMemo(() => (body && sections ? { ...body, firstFrame: hookOn ? body.video : undefined, lastFrame: ctaOn ? body.video : undefined } : body), [body, sections, hookOn, ctaOn]);+ const est = useEstimate<RunEstimate>("/api/ads/multiplier/estimate", estBody);+ const blocker = !video ? "Upload a reference video" : video.uploading ? "Uploading the video…" : duration == null ? "Reading the video…" : length < MULTIPLIER.minSeconds - 0.05 || length > MULTIPLIER.maxSeconds + 0.05 ? "Video duration: 4-30 seconds" : est.data?.blocker;+ const cost = est.data && !est.data.blocker ? (est.data.demo ? "Demo · free" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`) : "";++ const mention = (n: number) => {+ const tag = `@image_${n}`;+ const el = box.current;+ const at = el?.selectionStart ?? prompt.length;+ const before = prompt.slice(0, at);+ const after = prompt.slice(el?.selectionEnd ?? at);+ const pad = before && !/\s$/.test(before) ? " " : "";+ const next = `${before}${pad}${tag} ${after}`.slice(0, MULTIPLIER.maxChars);+ setPrompt(next);+ requestAnimationFrame(() => {+ el?.focus();+ const pos = (before + pad + tag + " ").length;+ el?.setSelectionRange(pos, pos);+ });+ };+ const used = mentionedImages(prompt).filter((n) => n <= images.length);+ const missing = mentionedImages(prompt).filter((n) => n > images.length);++ const generate = async () => {+ if (blocker || !body || !video || !cut) return void toast(blocker ?? "Upload a reference video", { id: "mult-blocker" });+ setBusy(sections ? "Reading the frames…" : "Starting…");+ try {+ const firstFrame = sections && hookOn ? await uploadFrame(video.ref, cut.start + 0.04, "hook-frame") : undefined;+ const lastFrame = sections && ctaOn ? await uploadFrame(video.ref, cut.end - 0.08, "cta-frame") : undefined;+ setBusy("Starting…");+ const r = await send<{ runs: MarketingRun[] }>("/api/ads/multiplier", "POST", { ...body, firstFrame, lastFrame });+ addRuns(qc, "ad-multiplier", r.runs);+ toast.success(r.runs.length > 1 ? `Making ${r.runs.length} versions` : "Making your new version", { duration: 1600 });+ resultsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ setBusy(null);+ }+ };++ return (+ <div className="flex min-h-svh min-w-0 flex-col">+ <MarketingHeader title="Ad Multiplier" active="multiplier" engine={engine} onEngine={setEngine} />+ <main className="mx-auto w-full min-w-0 max-w-[1180px] flex-1 px-3 pt-6 pb-20 sm:px-6 sm:pt-10">+ <div className="pb-6 text-center">+ <h2 className="font-heading text-display text-balance">Turn one winning ad into many</h2>+ <p className="mx-auto mt-2 max-w-xl text-[15px] text-muted-foreground">Upload an ad that works. Recreate it with new people, products or places — or keep it and try a new hook or call to action.</p>+ </div>++ <div className="grid min-w-0 gap-5 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,1fr)]">+ <section className="min-w-0 rounded-2xl border bg-background p-4 sm:p-5" aria-label="Reference ad">+ <div className="mb-3 flex items-center justify-between gap-2">+ <h3 className="text-[15px] font-semibold">Reference ad</h3>+ {video && (+ <Button variant="ghost" size="sm" onClick={() => (setVideo(null), startVideo())}>+ <RefreshCw /> Replace+ </Button>+ )}+ </div>+ {!video ? (+ <ReferenceDrop onFile={onFile} onPick={(v) => (startVideo(), setVideo(v))} />+ ) : (+ <div className="relative">+ <ClipRange src={video.preview} duration={duration} value={range} onChange={setRange} onDuration={onDuration} />+ {video.uploading && (+ <p className="mt-2 inline-flex items-center gap-1.5 text-[12px] text-muted-foreground">+ <Loader2 className="size-3 animate-spin" /> Uploading…+ </p>+ )}+ </div>+ )}+ </section>++ <section className="min-w-0 space-y-5 rounded-2xl border bg-background p-4 sm:p-5" aria-label="What to change">+ <div>+ <div className="mb-2 flex items-baseline justify-between gap-2">+ <h3 className="text-[15px] font-semibold">Images</h3>+ <span className="text-[12px] text-muted-foreground">+ {images.length}/{MULTIPLIER.maxImages}+ </span>+ </div>+ <MentionImages value={images} onChange={setImages} onMention={sections ? undefined : mention} max={MULTIPLIER.maxImages} />+ <p className="mt-2 text-[12px] text-muted-foreground">+ {sections+ ? "Used when the clip's own frames can't be read."+ : engine === "open"+ ? "Wan Animate puts your first mentioned image into the ad's performance."+ : maxImages+ ? `People, products or places to swap in. Tap one to mention it — ${model?.name ?? "this model"} uses up to ${maxImages}.`+ : `${model?.name ?? "This model"} edits from the prompt alone — pick Kling O3 to use your images.`}+ </p>+ </div>++ <div className="space-y-3">+ <div className="flex flex-wrap items-center gap-x-5 gap-y-2">+ <label className="flex items-center gap-2 text-[13px] font-medium">+ <Switch checked={hookOn} onCheckedChange={setHookOn} aria-label="Change hook" /> Change hook+ </label>+ <label className="flex items-center gap-2 text-[13px] font-medium">+ <Switch checked={ctaOn} onCheckedChange={setCtaOn} aria-label="Change CTA" /> Change CTA+ </label>+ </div>+ {sections ? (+ <div className="space-y-2.5">+ {hookOn && (+ <label className="block space-y-1">+ <span className="text-[12px] font-medium text-muted-foreground">New opening line (optional)</span>+ <textarea value={hook} onChange={(e) => setHook(e.target.value.slice(0, MULTIPLIER.maxChars))} rows={2} className={areaCls} placeholder="Stop scrolling — this changed my mornings" />+ </label>+ )}+ {ctaOn && (+ <label className="block space-y-1">+ <span className="text-[12px] font-medium text-muted-foreground">New call to action (optional)</span>+ <textarea value={cta} onChange={(e) => setCta(e.target.value.slice(0, MULTIPLIER.maxChars))} rows={2} className={areaCls} placeholder="Tap the link and get 20% off today" />+ </label>+ )}+ <p className="text-[12px] text-muted-foreground">A new clip is made from the {hookOn && ctaOn ? "first and last frames" : hookOn ? "first frame" : "last frame"} and joined {hookOn && ctaOn ? "around" : hookOn ? "before" : "after"} your ad. The prompt is off while these are on.</p>+ </div>+ ) : (+ <div>+ <label htmlFor="mult-prompt" className="mb-1 block text-[12px] font-medium text-muted-foreground">+ Prompt+ </label>+ <textarea+ id="mult-prompt"+ ref={box}+ value={prompt}+ onChange={(e) => setPrompt(e.target.value.slice(0, MULTIPLIER.maxChars))}+ rows={4}+ className={areaCls}+ placeholder={`${MULTIPLIER.defaultPrompt} Or: swap the presenter for @image_1 and set it in a sunny kitchen.`}+ />+ <div className="mt-1 flex flex-wrap items-center justify-between gap-2 text-[11px] text-muted-foreground">+ <span>{missing.length ? <span className="text-destructive">No image {missing.map((n) => `@image_${n}`).join(", ")} — add it or remove the mention</span> : used.length ? `Mentions: ${used.map((n) => `@image_${n}`).join(", ")}` : "Empty prompt: “Recreate this ad.”"}</span>+ <span className="font-mono tabular-nums">+ {prompt.length}/{MULTIPLIER.maxChars}+ </span>+ </div>+ </div>+ )}+ </div>++ <div className="grid gap-3 sm:grid-cols-2">+ {!sections && (+ <div className="min-w-0">+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Model</p>+ <Select value={modelId} onValueChange={setPicked}>+ <SelectTrigger className="h-9 w-full" aria-label="Model">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {choices.map((c) => (+ <SelectItem key={c.id} value={c.id}>+ {models[c.id]?.name ?? c.id}+ {c.id === "seedance-2-5" && !higgsfield ? " · needs Higgsfield" : ""}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="mt-1 line-clamp-2 text-[11px] text-muted-foreground">{choices.find((c) => c.id === modelId)?.note}</p>+ </div>+ )}+ <div className="min-w-0">+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Quality</p>+ <Seg+ label="Quality"+ value={quality}+ onChange={setQuality}+ options={MULTIPLIER.qualities.map((q) => ({ id: q, label: q, title: engine === "open" && q === "1080p" ? "Open-source models make 720p" : undefined }))}+ />+ {engine === "open" && quality === "1080p" && <p className="mt-1 text-[11px] text-muted-foreground">Made at {multiplierResolution(quality, engine)} on open-source models</p>}+ </div>+ <div className="min-w-0">+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Versions</p>+ <div className="inline-flex items-center gap-1 rounded-full bg-muted p-0.5" role="group" aria-label="Versions">+ <button type="button" onClick={() => setVersions((v) => Math.max(1, v - 1))} disabled={versions <= 1} className="grid size-7 place-items-center rounded-full hover:bg-background disabled:opacity-40" aria-label="Fewer versions">+ <Minus className="size-3.5" />+ </button>+ <span className="w-6 text-center font-mono text-[13px] tabular-nums" aria-live="polite">+ {versions}+ </span>+ <button type="button" onClick={() => setVersions((v) => Math.min(4, v + 1))} disabled={versions >= 4} className="grid size-7 place-items-center rounded-full hover:bg-background disabled:opacity-40" aria-label="More versions">+ <Plus className="size-3.5" />+ </button>+ </div>+ </div>+ </div>++ {est.data?.notes.length ? (+ <ul className="space-y-1 rounded-xl bg-muted/60 px-3 py-2 text-[12px] text-muted-foreground">+ {est.data.notes.map((n) => (+ <li key={n}>{n}</li>+ ))}+ </ul>+ ) : null}++ <div className="flex flex-wrap items-center justify-end gap-3 border-t pt-4">+ <p className="mr-auto text-[12px] text-muted-foreground">{est.data?.steps.length ? est.data.steps.map((s) => s.label).join(" → ") : "New versions keep the reference's length and framing"}</p>+ {cost && <span className="font-mono text-[13px] text-muted-foreground">{cost}</span>}+ <Button size="lg" onClick={() => void generate()} aria-disabled={!!blocker || !!busy} className={cn(blocker && "bg-muted text-subtle-foreground hover:bg-muted")} title={blocker}>+ {busy ? <Loader2 className="animate-spin" /> : <Sparkles />} {busy ?? (versions > 1 ? `Generate ${versions} versions` : "Generate")}+ </Button>+ </div>+ {blocker && video && <p className="-mt-3 text-right text-[12px] text-muted-foreground">{blocker}</p>}+ </section>+ </div>++ <div ref={resultsRef} className="scroll-mt-28 pt-10">+ <h2 className="mb-4 font-heading text-[24px]">Your versions</h2>+ <RunsList+ feature="ad-multiplier"+ empty={+ <div className="rounded-2xl border border-dashed py-12 text-center">+ <EmptyIcon icon={Copy} />+ <p className="mt-4 text-[14px] text-muted-foreground">{video ? "Pick what to change and press Generate." : "Start with an ad that already works."}</p>+ </div>+ }+ />+ </div>+ <p className="flex flex-wrap items-center justify-center gap-1.5 pt-6 text-center text-[12px] text-subtle-foreground">+ <Sparkles className="size-3" /> Cloud: Seedance 2.5 edit (Higgsfield), Kling O3 edit, Gemini Omni Flash · Open source: Wan 2.2 Animate, Wan 2.2 clips joined around your ad+ </p>+ </main>+ </div>+ );+}diff --git a/src/components/ads/new-ads.tsx b/src/components/ads/new-ads.tsxnew file mode 100644index 00000000..a93ca03f--- /dev/null+++ b/src/components/ads/new-ads.tsx@@ -0,0 +1,181 @@+"use client";++import { Loader2, Minus, Plus, Sparkles } from "lucide-react";+import { useMemo, useState } from "react";+import { toast } from "sonner";+import { Button } from "@/components/ui/button";+import { AddFromLink, ProductCard, ProductDialog, UploadProductButton } from "@/components/brand/products";+import { AD_RATIOS, MAX_ADS_PER_PRODUCT, MAX_PRODUCTS_PER_RUN, type BrandKit, type Product } from "@/lib/catalog/marketing";+import { formatCost } from "@/lib/format";+import { cn } from "@/lib/utils";+import { useCreativeActions, useEstimate, useProductActions, useStatusFlags } from "@/components/marketing/hooks";++interface BatchEstimate {+ route: "fuobe" | "higgsfield";+ modelName: string;+ total: number;+ costUsd: number | null;+ perAd: number | null;+ demo: boolean;+ copyBy: "llm" | "rules";+ blocker?: string;+}++function Stepper({ value, onChange, label }: { value: number; onChange: (n: number) => void; label: string }) {+ return (+ <div className="inline-flex items-center gap-1 rounded-full bg-muted p-0.5" role="group" aria-label={label}>+ <button type="button" onClick={() => onChange(Math.max(1, value - 1))} disabled={value <= 1} className="grid size-7 place-items-center rounded-full hover:bg-background disabled:opacity-40" aria-label={`Fewer ads for ${label}`}>+ <Minus className="size-3.5" />+ </button>+ <input+ value={value}+ onChange={(e) => {+ const n = parseInt(e.target.value, 10);+ if (Number.isFinite(n)) onChange(Math.min(MAX_ADS_PER_PRODUCT, Math.max(1, n)));+ }}+ inputMode="numeric"+ aria-label={`Ads for ${label}`}+ className="h-7 w-9 bg-transparent text-center font-mono text-[13px] tabular-nums outline-none"+ />+ <button type="button" onClick={() => onChange(Math.min(MAX_ADS_PER_PRODUCT, value + 1))} disabled={value >= MAX_ADS_PER_PRODUCT} className="grid size-7 place-items-center rounded-full hover:bg-background disabled:opacity-40" aria-label={`More ads for ${label}`}>+ <Plus className="size-3.5" />+ </button>+ </div>+ );+}++/** Select products (≤10) → "How many ads to create?" (≤20 each, total price first) → Create. */+export function NewAds({ brand, products, engine, onCreated }: { brand: BrandKit; products: Product[]; engine: "cloud" | "open"; onCreated: (batchId: string) => void }) {+ const { createBatch } = useCreativeActions(brand.id);+ const { remove } = useProductActions();+ const { higgsfield } = useStatusFlags();+ const [selected, setSelected] = useState<string[]>(() => products.slice(0, MAX_PRODUCTS_PER_RUN).map((p) => p.id));+ const [counts, setCounts] = useState<Record<string, number>>({});+ const [editing, setEditing] = useState<Product | null>(null);+ const [route, setRoute] = useState<"fuobe" | "higgsfield">(higgsfield && engine === "cloud" ? "higgsfield" : "fuobe");+ const [ratio, setRatio] = useState<string>("4:5");+ const effectiveRoute = engine === "open" || !higgsfield ? "fuobe" : route;+ const items = selected.filter((id) => products.some((p) => p.id === id)).map((productId) => ({ productId, count: counts[productId] ?? 4 }));+ const total = items.reduce((n, i) => n + i.count, 0);+ const body = useMemo(() => (items.length ? { brandId: brand.id, engine, route: effectiveRoute, items, ratio: effectiveRoute === "higgsfield" ? ratio : undefined } : null), [brand.id, engine, effectiveRoute, items, ratio]);+ const est = useEstimate<BatchEstimate>("/api/ads/estimate", body);+ const toggle = (id: string) =>+ setSelected((s) => {+ if (s.includes(id)) return s.filter((x) => x !== id);+ if (s.length >= MAX_PRODUCTS_PER_RUN) {+ toast(`Up to ${MAX_PRODUCTS_PER_RUN} products per run`);+ return s;+ }+ return [...s, id];+ });+ const create = () => {+ if (!body) return void toast("Select at least one product");+ if (est.data?.blocker) return void toast(est.data.blocker);+ createBatch.mutate(body, {+ onSuccess: (r) => {+ toast.success(`Generating ${r.creatives.length} ads`, { duration: 1800 });+ onCreated(r.batchId);+ },+ onError: (e) => toast.error((e as Error).message),+ });+ };+ const price = est.data ? (est.data.demo ? "Demo · free" : est.data.costUsd == null ? "price unknown" : `≈ ${formatCost(est.data.costUsd)}`) : "";+ return (+ <div className="space-y-6">+ <section className="rounded-2xl border bg-background p-4 sm:p-5">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h3 className="text-[16px] font-semibold">Select products to create ads</h3>+ <p className="text-[13px] text-muted-foreground">+ {products.length} product{products.length === 1 ? "" : "s"} found · up to {MAX_PRODUCTS_PER_RUN} per run. Product details may contain mistakes — check them before you continue.+ </p>+ </div>+ <div className="flex gap-1.5">+ <Button variant="ghost" size="sm" onClick={() => setSelected(selected.length ? [] : products.slice(0, MAX_PRODUCTS_PER_RUN).map((p) => p.id))}>+ {selected.length ? "Deselect all" : "Select all"}+ </Button>+ </div>+ </div>+ <div className="mt-3 flex flex-col gap-2 sm:flex-row">+ <AddFromLink brandId={brand.id} limit={5} className="flex-1" placeholder="Add product from link" onAdded={(ps) => setSelected((s) => [...new Set([...s, ...ps.map((p) => p.id)])].slice(0, MAX_PRODUCTS_PER_RUN))} />+ <UploadProductButton brandId={brand.id} onSaved={(p) => setSelected((s) => [...new Set([...s, p.id])].slice(0, MAX_PRODUCTS_PER_RUN))} />+ </div>+ {products.length ? (+ <div className="mt-4 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">+ {products.map((p) => (+ <ProductCard key={p.id} product={p} selected={selected.includes(p.id)} onToggle={() => toggle(p.id)} disabled={selected.length >= MAX_PRODUCTS_PER_RUN} onEdit={() => setEditing(p)} onDelete={() => remove.mutate(p.id)} />+ ))}+ </div>+ ) : (+ <p className="mt-4 rounded-xl bg-muted/60 px-4 py-6 text-center text-[13px] text-muted-foreground">No products yet. Paste a product link or upload one to start making ads.</p>+ )}+ </section>++ {items.length > 0 && (+ <section className="rounded-2xl border bg-background p-4 sm:p-5">+ <h3 className="text-[16px] font-semibold">How many ads to create?</h3>+ <p className="text-[13px] text-muted-foreground">Each ad comes in 1:1, 4:5 and 9:16, with a headline, copy and a call to action.</p>+ <ul className="mt-4 divide-y">+ {items.map((i) => {+ const p = products.find((x) => x.id === i.productId)!;+ return (+ <li key={i.productId} className="flex items-center gap-3 py-2.5">+ <span className="size-10 shrink-0 overflow-hidden rounded-lg bg-muted">+ {/* eslint-disable-next-line @next/next/no-img-element */}+ {p.images[0] && <img src={p.images[0]} alt="" className="size-full object-cover" />}+ </span>+ <span className="min-w-0 flex-1 truncate text-[14px] font-medium">{p.name}</span>+ <Stepper value={i.count} onChange={(n) => setCounts((c) => ({ ...c, [i.productId]: n }))} label={p.name} />+ </li>+ );+ })}+ </ul>+ {engine === "cloud" && higgsfield && (+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <span className="text-[12px] font-medium text-muted-foreground">Made by</span>+ <div role="radiogroup" aria-label="Route" className="inline-flex rounded-full bg-muted p-0.5">+ {(["higgsfield", "fuobe"] as const).map((r) => (+ <button key={r} role="radio" aria-checked={route === r} onClick={() => setRoute(r)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", route === r && "bg-background text-foreground shadow-soft")}>+ {r === "higgsfield" ? "Higgsfield Ads Studio" : "Fuobe (your fonts, editable words)"}+ </button>+ ))}+ </div>+ {route === "higgsfield" && (+ <div role="radiogroup" aria-label="Format" className="inline-flex rounded-full bg-muted p-0.5">+ {AD_RATIOS.map((r) => (+ <button key={r} role="radio" aria-checked={ratio === r} onClick={() => setRatio(r)} className={cn("h-7 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground", ratio === r && "bg-background text-foreground shadow-soft")}>+ {r}+ </button>+ ))}+ </div>+ )}+ </div>+ )}+ <div className="mt-5 flex flex-wrap items-center justify-between gap-3 rounded-xl bg-muted/60 px-4 py-3">+ <div className="min-w-0 text-[13px]">+ <p className="font-medium">+ Create {total} ad{total === 1 ? "" : "s"} for{" "}+ {items.slice(0, 3).map((i) => (+ <span key={i.productId} className="mx-0.5 inline-block max-w-40 truncate rounded-full bg-background px-2 align-bottom text-[12px]">+ {products.find((p) => p.id === i.productId)?.name}+ </span>+ ))}+ {items.length > 3 && ` +${items.length - 3}`} and the brand+ </p>+ <p className="text-[12px] text-muted-foreground">+ {est.data?.blocker ?? (est.data ? `${est.data.modelName}${est.data.perAd != null && !est.data.demo ? ` · ${formatCost(est.data.perAd)} per ad` : ""}${effectiveRoute === "fuobe" ? ` · copy by ${est.data.copyBy === "llm" ? "your LLM" : "Fuobe's rules"}` : ""}` : "Pricing…")}+ </p>+ </div>+ <div className="flex items-center gap-3">+ <span className="font-mono text-[14px] font-medium tabular-nums">{est.isFetching && !est.data ? "…" : price}</span>+ <Button size="lg" onClick={create} disabled={createBatch.isPending || !!est.data?.blocker}>+ {createBatch.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} Create {total} ads+ </Button>+ </div>+ </div>+ </section>+ )}+ <ProductDialog open={!!editing} onOpenChange={(o) => !o && setEditing(null)} product={editing} brandId={brand.id} />+ </div>+ );+}diff --git a/src/lib/catalog/apps.ts b/src/lib/catalog/apps.tsindex daa06c9b..8c187006 100644--- a/src/lib/catalog/apps.ts+++ b/src/lib/catalog/apps.ts@@ -497,10 +497,13 @@ export const APPS: Preset[] = [prompt:"Create a bold, high-end social media advertisement featuring the product from the image, dynamic composition, premium lighting, props that match the product. {prompt}. Keep the product exact.",}),+ // Click to Ad and Link to Video Ad open the Click to Ad flow (/marketing/click-to-ad, redirected in+ // next.config.ts): a product link → product kit → a 9:16 ad with voiceover and captions. The+ // entries stay so the gallery keeps its cards.app({name: "Click to Ad",category: "Product",- description: "Product photo → UGC or studio ad creative",+ description: "Product link → 9:16 video ad with voiceover and captions",icon: "MousePointerClick",hue: 30,inputs: [product],@@ -516,12 +519,11 @@ export const APPS: Preset[] = [],prompt:"Create an ad image: {option:format}. {prompt}. The product from the image must keep its exact shape, colors, label and logo. Leave clean space for a headline.",- parity: "Higgsfield scrapes a product URL and builds a whole ad set; Fuobe needs a product photo and makes one creative per run",}),app({name: "Link to Video Ad",category: "Product",- description: "Product photo → short video ad",+ description: "Paste a product link, get a short video ad",icon: "Link",hue: 45,inputs: [product],@@ -531,7 +533,6 @@ export const APPS: Preset[] = ["A short commercial for the product in the image: the camera glides in from a wide hero angle, the product rotates slightly as light sweeps across its surface, then the shot settles on a crisp close-up of the logo. {prompt}. Premium studio lighting, the product's design and label stay exactly the same.",cloud: VIDEO_CLOUD,open: VIDEO_OPEN,- parity: "Higgsfield builds the ad from a product URL with scripts and voiceover; Fuobe animates one product photo",}),app({name: "Unboxing Video",diff --git a/tests/marketing-client.test.ts b/tests/marketing-client.test.tsnew file mode 100644index 00000000..39a55583--- /dev/null+++ b/tests/marketing-client.test.ts@@ -0,0 +1,78 @@+import zlib from "node:zlib";+import { describe, expect, it } from "vitest";+import { crc32, uniqueNames, zipFiles } from "@/components/ads/zip";+import { clampClip, initialClip, MULTIPLIER } from "@/lib/catalog/marketing";++/** Read a stored zip back: every entry's name and bytes, from the central directory. */+function readZip(zip: Uint8Array): { name: string; data: Uint8Array; crc: number }[] {+ const v = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);+ const eocd = zip.byteLength - 22;+ expect(v.getUint32(eocd, true)).toBe(0x06054b50);+ const count = v.getUint16(eocd + 10, true);+ let at = v.getUint32(eocd + 16, true);+ const out = [];+ for (let i = 0; i < count; i++) {+ expect(v.getUint32(at, true)).toBe(0x02014b50);+ const crc = v.getUint32(at + 16, true);+ const size = v.getUint32(at + 24, true);+ const nameLen = v.getUint16(at + 28, true);+ const extra = v.getUint16(at + 30, true);+ const comment = v.getUint16(at + 32, true);+ const local = v.getUint32(at + 42, true);+ const name = new TextDecoder().decode(zip.subarray(at + 46, at + 46 + nameLen));+ expect(v.getUint32(local, true)).toBe(0x04034b50);+ expect(v.getUint16(local + 8, true)).toBe(0); // stored+ const start = local + 30 + v.getUint16(local + 26, true) + v.getUint16(local + 28, true);+ out.push({ name, data: zip.subarray(start, start + size), crc });+ at += 46 + nameLen + extra + comment;+ }+ return out;+}++describe("Download all (browser zip)", () => {+ it("computes the standard CRC-32", () => {+ const data = new TextEncoder().encode("The quick brown fox jumps over the lazy dog");+ expect(crc32(data)).toBe(0x414fa339);+ expect(crc32(data)).toBe(zlib.crc32(data));+ expect(crc32(new Uint8Array())).toBe(0);+ });++ it("keeps names unique without losing the extension", () => {+ expect(uniqueNames(["ad.png", "AD.png", "ad.png", "readme"])).toEqual(["ad.png", "AD (2).png", "ad (3).png", "readme"]);+ });++ it("writes a zip any unzip tool reads back byte for byte", () => {+ const a = new Uint8Array(5000).map((_, i) => i % 251);+ const b = new TextEncoder().encode("second ad");+ const zip = zipFiles([+ { name: "ember-oat-granola-4x5-1.png", data: a },+ { name: "ember-oat-granola-4x5-1.png", data: b },+ ]);+ const files = readZip(zip);+ expect(files.map((f) => f.name)).toEqual(["ember-oat-granola-4x5-1.png", "ember-oat-granola-4x5-1 (2).png"]);+ expect([...files[0].data]).toEqual([...a]);+ expect(new TextDecoder().decode(files[1].data)).toBe("second ad");+ expect(files[0].crc).toBe(zlib.crc32(a));+ expect(zipFiles([]).byteLength).toBe(22);+ });+});++describe("Ad Multiplier in/out points", () => {+ it("starts with the whole clip, or its first 30 s", () => {+ expect(initialClip(12.34)).toEqual({ start: 0, end: 12.3 });+ expect(initialClip(95)).toEqual({ start: 0, end: MULTIPLIER.maxSeconds });+ });++ it("keeps the range 4–30 s inside the clip, moving the other point", () => {+ // Out point dragged far: the in point follows to keep 30 s.+ expect(clampClip({ start: 0, end: 50 }, 60, "end")).toEqual({ start: 20, end: 50 });+ // In point dragged past the out point: the out point moves to keep 4 s.+ expect(clampClip({ start: 20, end: 21 }, 60, "start")).toEqual({ start: 20, end: 24 });+ // Near the end of the clip the in point gives way instead.+ expect(clampClip({ start: 58, end: 60 }, 60, "start")).toEqual({ start: 56, end: 60 });+ // Out of bounds values are pulled back in.+ expect(clampClip({ start: -3, end: 70 }, 60, "start")).toEqual({ start: 0, end: 30 });+ // A clip under 4 s can't be fixed by trimming; it stays whole (the form says why).+ expect(clampClip({ start: 0, end: 3 }, 3, "end")).toEqual({ start: 0, end: 3 });+ });+});