Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Marketing Studio, Click to Ad and the brand kit UI

Claudeb7cf2772fa0d
diff --git a/src/app/(studio)/marketing/click-to-ad/page.tsx b/src/app/(studio)/marketing/click-to-ad/page.tsx
new file mode 100644
index 00000000..304a49cc
--- /dev/null
+++ b/src/app/(studio)/marketing/click-to-ad/page.tsx
@@ -0,0 +1,9 @@
+import type { Metadata } from "next";
+import { ClickToAd } from "@/components/marketing/click-to-ad";
+import { marketingModelInfo } from "@/components/marketing/model-info";
+
+export const metadata: Metadata = { title: "Click to Ad" };
+
+export default function Page() {
+ return <ClickToAd models={marketingModelInfo()} />;
+}
diff --git a/src/app/(studio)/marketing/page.tsx b/src/app/(studio)/marketing/page.tsx
new file mode 100644
index 00000000..97ed0eb7
--- /dev/null
+++ b/src/app/(studio)/marketing/page.tsx
@@ -0,0 +1,9 @@
+import type { Metadata } from "next";
+import { MarketingStudio } from "@/components/marketing/marketing-studio";
+import { marketingModelInfo } from "@/components/marketing/model-info";
+
+export const metadata: Metadata = { title: "Marketing Studio" };
+
+export default function Page() {
+ return <MarketingStudio models={marketingModelInfo()} />;
+}
diff --git a/src/app/api/marketing/runs/[id]/again/route.ts b/src/app/api/marketing/runs/[id]/again/route.ts
new file mode 100644
index 00000000..d2966ea7
--- /dev/null
+++ b/src/app/api/marketing/runs/[id]/again/route.ts
@@ -0,0 +1,11 @@
+import { failure, rerun } from "@/server/marketing";
+
+/** Run again: the same template, product and settings as a new run. */
+export async function POST(_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]/again">) {
+ const { id } = await ctx.params;
+ try {
+ return Response.json({ runs: await rerun(id) }, { status: 201 });
+ } catch (e) {
+ return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);
+ }
+}
diff --git a/src/app/api/marketing/runs/[id]/compose/route.ts b/src/app/api/marketing/runs/[id]/compose/route.ts
new file mode 100644
index 00000000..4a1b2bb1
--- /dev/null
+++ b/src/app/api/marketing/runs/[id]/compose/route.ts
@@ -0,0 +1,16 @@
+import { z } from "zod";
+import { failure, readBody, saveRunComposite } from "@/server/marketing";
+
+const Body = z.object({ url: z.string().startsWith("/api/files/"), ratio: z.string().regex(/^\d+:\d+$/), text: z.string().max(1000).default("") });
+
+/** Save an open-engine result with its words set in the browser (an uploaded PNG) to the Library. */
+export async function POST(request: Request, ctx: RouteContext<"/api/marketing/runs/[id]/compose">) {
+ const { id } = await ctx.params;
+ const body = await readBody(request, Body, "Upload the image first");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(saveRunComposite(id, body), { status: 201 });
+ } catch (e) {
+ return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);
+ }
+}
diff --git a/src/components/ads/ad-canvas.tsx b/src/components/ads/ad-canvas.tsx
new file mode 100644
index 00000000..b4df21e5
--- /dev/null
+++ b/src/components/ads/ad-canvas.tsx
@@ -0,0 +1,56 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { cn } from "@/lib/utils";
+import { sizeFor } from "./layout";
+import { renderAd, type RenderInput } from "./render";
+
+/**
+ * A creative drawn on a canvas at the size it's shown (device pixels), redrawn when its input
+ * changes. `lazy` waits until the card scrolls near the viewport (the Ads grid can hold hundreds).
+ */
+export function AdCanvas({ input, className, lazy, label }: { input: RenderInput; className?: string; lazy?: boolean; label: string }) {
+ const box = useRef<HTMLDivElement>(null);
+ const canvas = useRef<HTMLCanvasElement>(null);
+ const [visible, setVisible] = useState(!lazy);
+ const [width, setWidth] = useState(0);
+ const key = JSON.stringify(input);
+ useEffect(() => {
+ const el = box.current;
+ if (!el) return;
+ const ro = new ResizeObserver(([e]) => setWidth(Math.round(e.contentRect.width)));
+ ro.observe(el);
+ let io: IntersectionObserver | null = null;
+ if (lazy) {
+ io = new IntersectionObserver(([e]) => e.isIntersecting && setVisible(true), { rootMargin: "400px" });
+ io.observe(el);
+ }
+ return () => {
+ ro.disconnect();
+ io?.disconnect();
+ };
+ }, [lazy]);
+ useEffect(() => {
+ if (!visible || !width || !canvas.current) return;
+ let live = true;
+ const c = canvas.current;
+ const scale = (width * Math.min(2, window.devicePixelRatio || 1)) / sizeFor(input.ratio).w;
+ const off = document.createElement("canvas");
+ void renderAd(off, input, scale).then(() => {
+ if (!live) return;
+ c.width = off.width;
+ c.height = off.height;
+ c.getContext("2d")?.drawImage(off, 0, 0);
+ });
+ return () => {
+ live = false;
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [key, visible, width]);
+ const { w, h } = sizeFor(input.ratio);
+ return (
+ <div ref={box} className={cn("relative w-full overflow-hidden bg-muted", className)} style={{ aspectRatio: `${w} / ${h}` }}>
+ <canvas ref={canvas} role="img" aria-label={label} className="absolute inset-0 size-full" />
+ </div>
+ );
+}
diff --git a/src/components/ads/ad-editor.tsx b/src/components/ads/ad-editor.tsx
new file mode 100644
index 00000000..c3a45a76
--- /dev/null
+++ b/src/components/ads/ad-editor.tsx
@@ -0,0 +1,187 @@
+"use client";
+
+import { Download, FolderDown, Library, Loader2, RotateCcw } from "lucide-react";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Switch } from "@/components/ui/switch";
+import { areaCls, inputCls } from "@/components/brand/fields";
+import { uploadFile } from "@/lib/api";
+import type { BrandKit } from "@/lib/catalog/marketing";
+import { cn } from "@/lib/utils";
+import { AdCanvas } from "./ad-canvas";
+import { AD_LAYOUTS, exportName, themeFrom, type AdLayout } from "./layout";
+import { downloadBlob, exportPng, type RenderInput } from "./render";
+import { zipFiles } from "./zip";
+
+export interface AdText {
+ headline: string;
+ body: string;
+ cta: string;
+}
+
+/** Everything a creative needs to be drawn in one format. */
+export function renderInput(o: { ratio: string; layout: AdLayout; text: AdText; brand?: BrandKit | null; image?: string | null; logo?: boolean; baked?: boolean }): RenderInput {
+ return {
+ ratio: o.ratio,
+ layout: o.layout,
+ content: { headline: o.text.headline, body: o.text.body || undefined, cta: o.text.cta || undefined, brand: o.brand?.name },
+ theme: themeFrom(o.brand),
+ image: o.image,
+ logo: o.logo !== false ? (o.brand?.logo ?? null) : null,
+ baked: o.baked,
+ };
+}
+
+/** Download every format of a creative as a zip (or one PNG when there's a single format). */
+export async function downloadFormats(base: { brand: string; product?: string; n: number }, inputs: RenderInput[]) {
+ const files = await Promise.all(inputs.map(async (i) => ({ name: exportName(base.brand, base.product, String(i.ratio), base.n), data: new Uint8Array(await (await exportPng(i)).arrayBuffer()) })));
+ if (files.length === 1) return downloadBlob(new Blob([files[0].data as BlobPart], { type: "image/png" }), files[0].name);
+ downloadBlob(new Blob([zipFiles(files) as BlobPart], { type: "application/zip" }), exportName(base.brand, base.product, "all", base.n).replace(/-all-(\d+)\.png$/, "-$1.zip"));
+}
+
+/**
+ * Edit a creative's words and layout and see every format change live; export PNGs (one format or
+ * all, zipped) or save the composited image to the Library.
+ */
+export function AdEditor({
+ open,
+ onOpenChange,
+ title,
+ image,
+ baked,
+ ratios,
+ initial,
+ brand,
+ productName,
+ number = 1,
+ onSaveText,
+ onSaveToLibrary,
+}: {
+ open: boolean;
+ onOpenChange: (o: boolean) => void;
+ title: string;
+ image?: string | null;
+ baked?: boolean;
+ ratios: string[];
+ initial: AdText & { layout?: AdLayout | null };
+ brand?: BrandKit | null;
+ productName?: string;
+ number?: number;
+ /** Persist edited words/layout (Ads Studio creatives). */
+ onSaveText?: (t: AdText & { layout: AdLayout }) => void;
+ /** Upload the PNG and record it (returns when saved). */
+ onSaveToLibrary?: (url: string, ratio: string, text: AdText) => Promise<void>;
+}) {
+ const id = useId();
+ const [text, setText] = useState<AdText>(initial);
+ const [layout, setLayout] = useState<AdLayout>(initial.layout ?? "overlay");
+ const [ratio, setRatio] = useState(ratios[0]);
+ const [logo, setLogo] = useState(true);
+ const [busy, setBusy] = useState<"" | "png" | "zip" | "save">("");
+ const input = (r: string) => renderInput({ ratio: r, layout, text, brand, image, logo, baked });
+ const changed = text.headline !== initial.headline || text.body !== initial.body || text.cta !== initial.cta || layout !== (initial.layout ?? "overlay");
+ const close = (o: boolean) => {
+ if (!o && changed && onSaveText) onSaveText({ ...text, layout });
+ onOpenChange(o);
+ };
+ const base = { brand: brand?.name ?? "ad", product: productName, n: number };
+ const run = async (what: "png" | "zip" | "save") => {
+ setBusy(what);
+ try {
+ if (what === "png") await downloadFormats(base, [input(ratio)]);
+ else if (what === "zip") await downloadFormats(base, ratios.map(input));
+ else if (onSaveToLibrary) {
+ const blob = await exportPng(input(ratio));
+ const asset = await uploadFile(new File([blob], exportName(base.brand, base.product, ratio, base.n), { type: "image/png" }));
+ await onSaveToLibrary(asset.url, ratio, text);
+ toast.success("Saved to your library", { duration: 2000 });
+ }
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy("");
+ }
+ };
+ return (
+ <Dialog open={open} onOpenChange={close}>
+ <DialogContent className="max-h-[94svh] gap-0 overflow-y-auto p-0 sm:max-w-4xl">
+ <DialogHeader className="border-b px-5 py-4">
+ <DialogTitle className="truncate pr-8">{title}</DialogTitle>
+ <DialogDescription>{baked ? "Made whole by Higgsfield Ads Studio — download it as is." : "Edit the words and layout; every format updates as you type."}</DialogDescription>
+ </DialogHeader>
+ <div className="grid min-w-0 gap-5 p-5 md:grid-cols-[minmax(0,1fr)_320px]">
+ <div className="min-w-0">
+ {ratios.length > 1 && (
+ <div role="tablist" aria-label="Format" className="mb-3 inline-flex rounded-full bg-muted p-0.5">
+ {ratios.map((r) => (
+ <button key={r} role="tab" aria-selected={r === ratio} onClick={() => setRatio(r)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", r === ratio && "bg-background text-foreground shadow-soft")}>
+ {r}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="mx-auto" style={{ maxWidth: ratio === "9:16" ? 300 : ratio === "4:5" ? 380 : 440 }}>
+ <AdCanvas input={input(ratio)} className="rounded-xl shadow-normal" label={`${title}, ${ratio}`} />
+ </div>
+ </div>
+ {!baked ? (
+ <div className="min-w-0 space-y-3">
+ <label className="block space-y-1.5">
+ <span className="text-[12px] font-medium text-muted-foreground">Headline</span>
+ <input id={`${id}-h`} value={text.headline} onChange={(e) => setText({ ...text, headline: e.target.value })} maxLength={140} className={inputCls} />
+ </label>
+ <label className="block space-y-1.5">
+ <span className="text-[12px] font-medium text-muted-foreground">Copy</span>
+ <textarea value={text.body} onChange={(e) => setText({ ...text, body: e.target.value })} maxLength={400} rows={3} className={areaCls} />
+ </label>
+ <label className="block space-y-1.5">
+ <span className="text-[12px] font-medium text-muted-foreground">Button</span>
+ <input value={text.cta} onChange={(e) => setText({ ...text, cta: e.target.value })} maxLength={40} className={inputCls} placeholder="Shop now" />
+ </label>
+ <div>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Layout</p>
+ <div role="radiogroup" aria-label="Layout" className="grid grid-cols-2 gap-1.5">
+ {AD_LAYOUTS.map((l) => (
+ <button key={l.id} role="radio" aria-checked={layout === l.id} title={l.hint} onClick={() => setLayout(l.id)} className={cn("rounded-lg border px-2.5 py-2 text-left text-[12px] transition-colors hover:bg-accent", layout === l.id && "border-primary bg-brand-faint text-brand-text")}>
+ <span className="block font-medium">{l.name}</span>
+ <span className="line-clamp-1 text-[11px] text-muted-foreground">{l.hint}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ {brand?.logo && (
+ <label className="flex items-center justify-between gap-2 text-[13px]">
+ Show logo <Switch checked={logo} onCheckedChange={setLogo} aria-label="Show logo" />
+ </label>
+ )}
+ {changed && (
+ <button type="button" onClick={() => (setText({ headline: initial.headline, body: initial.body, cta: initial.cta }), setLayout(initial.layout ?? "overlay"))} className="inline-flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground">
+ <RotateCcw className="size-3" /> Undo changes
+ </button>
+ )}
+ </div>
+ ) : (
+ <div />
+ )}
+ </div>
+ <div className="flex flex-wrap items-center justify-end gap-2 border-t px-5 py-3">
+ {onSaveToLibrary && (
+ <Button variant="ghost" onClick={() => void run("save")} disabled={!!busy || !image}>
+ {busy === "save" ? <Loader2 className="animate-spin" /> : <Library />} Save to library
+ </Button>
+ )}
+ {ratios.length > 1 && (
+ <Button variant="outline" onClick={() => void run("zip")} disabled={!!busy}>
+ {busy === "zip" ? <Loader2 className="animate-spin" /> : <FolderDown />} All formats
+ </Button>
+ )}
+ <Button onClick={() => void run("png")} disabled={!!busy}>
+ {busy === "png" ? <Loader2 className="animate-spin" /> : <Download />} Download {ratio}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/ads/layout.ts b/src/components/ads/layout.ts
index db589b4d..6ff558e3 100644
--- a/src/components/ads/layout.ts
+++ b/src/components/ads/layout.ts
@@ -13,6 +13,13 @@ export const AD_SIZE: Record<AdRatio, { w: number; h: number }> = {
"9:16": { w: 1080, h: 1920 },
};
+/** Canvas size for any "w:h" ratio, 1080 px wide (Ads Studio's three formats, or a poster's own shape). */
+export function sizeFor(ratio: string): { w: number; h: number } {
+ if (ratio in AD_SIZE) return AD_SIZE[ratio as AdRatio];
+ const [a, b] = ratio.split(":").map(Number);
+ return a > 0 && b > 0 ? { w: 1080, h: Math.round((1080 * b) / a) } : AD_SIZE["1:1"];
+}
+
export type AdLayout = "overlay" | "panel" | "band" | "frame";
export const AD_LAYOUTS: { id: AdLayout; name: string; hint: string }[] = [
@@ -23,7 +30,7 @@ export const AD_LAYOUTS: { id: AdLayout; name: string; hint: string }[] = [
];
/** A sensible layout per format when the creative hasn't picked one. */
-export const defaultLayout = (ratio: AdRatio, seed = 0): AdLayout => (ratio === "9:16" ? (seed % 3 === 2 ? "frame" : "panel") : (["overlay", "overlay", "band", "frame"] as AdLayout[])[seed % 4]);
+export const defaultLayout = (ratio: string, seed = 0): AdLayout => (sizeFor(ratio).h / sizeFor(ratio).w > 1.5 ? (seed % 3 === 2 ? "frame" : "panel") : (["overlay", "overlay", "band", "frame"] as AdLayout[])[seed % 4]);
/** Width of `text` set in `font` (a CSS font string), in px. The canvas provides it in the browser. */
export type Measure = (text: string, font: string) => number;
@@ -224,7 +231,8 @@ const heightOf = (b: TextBox | undefined) => (b ? b.lines.length * b.lineHeight
// The plan
export interface PlanInput {
- ratio: AdRatio;
+ /** "1:1", "4:5", "9:16" (or any w:h). */
+ ratio: AdRatio | string;
layout: AdLayout;
content: AdContent;
theme: AdTheme;
@@ -236,9 +244,10 @@ export interface PlanInput {
/** Lay out one creative. Every box stays inside the canvas; text shrinks before it overflows. */
export function planAd(p: PlanInput): AdPlan {
- const { w: W, h: H } = AD_SIZE[p.ratio];
+ const { w: W, h: H } = sizeFor(p.ratio);
const m = Math.round(W * 0.07);
- const tall = p.ratio === "9:16";
+ const tall = H / W > 1.5;
+ const portrait = H / W > 1.15;
const t = p.theme;
const inner = W - 2 * m;
@@ -246,12 +255,12 @@ export function planAd(p: PlanInput): AdPlan {
const headlineMax = W * (tall ? 0.1 : 0.088);
const fitHeadline = (width: number, lines: number, max = headlineMax) => fitText(p.content.headline || " ", width, lines, t.heading, 800, max, W * 0.042, p.measure);
const fitBody = (width: number) => (p.content.body?.trim() ? fitText(p.content.body, width, tall ? 4 : 3, t.body, 400, W * 0.034, W * 0.026, p.measure) : null);
- const ctaBox = (x: number, bottom: number, color: string, onColor: string, align: "left" | "center"): AdPlan["cta"] => {
+ const ctaBox = (x: number, bottom: number, color: string, onColor: string, align: "left" | "center", maxW = inner): AdPlan["cta"] => {
if (!p.content.cta?.trim()) return undefined;
const size = W * 0.032;
- const label = fitText(p.content.cta.trim(), inner - size * 2.4, 1, t.body, 700, size, W * 0.024, p.measure);
+ const label = fitText(p.content.cta.trim(), maxW - size * 2.4, 1, t.body, 700, size, W * 0.024, p.measure);
const tw = p.measure(label.lines[0], fontString(t.body, label.size, 700));
- const bw = Math.min(inner, tw + label.size * 2.4);
+ const bw = Math.min(maxW, tw + label.size * 2.4);
const bh = label.size * 2.3;
const bx = align === "center" ? (W - bw) / 2 : x;
return {
@@ -264,22 +273,65 @@ export function planAd(p: PlanInput): AdPlan {
text: textBox(label, bx + bw / 2, bottom - bh + (bh - label.size * 1.12) / 2, t.body, 700, onColor, "center", bw),
};
};
+ /** The CTA pill: brand colour (frame, overlay), or paper on the brand-colour panel. */
+ const panelCta = (onPaper: boolean, x: number, bottom: number, maxW = inner) =>
+ onPaper ? ctaBox(x, bottom, t.accent, t.onAccent, "left", maxW) : ctaBox(x, bottom, t.paper, readableOn(t.paper) === "#ffffff" ? "#ffffff" : t.ink, "left", maxW);
const logoRect = (x: number, y: number, maxW: number, maxH: number, align: "left" | "center" = "left"): Rect | undefined =>
p.logo ? containIn(p.logo.w, p.logo.h, { x, y, w: maxW, h: maxH }, align) : undefined;
const brandText = (x: number, y: number, color: string, align: "left" | "center"): TextBox | undefined =>
!p.logo && p.content.brand?.trim() ? textBox(fitText(p.content.brand.trim().toUpperCase(), inner * 0.6, 1, t.body, 700, W * 0.03, W * 0.022, p.measure), x, y, t.body, 700, color, align, inner * 0.6, 1.1) : undefined;
const image = (r: Rect, radius = 0): AdPlan["image"] => (p.image ? { ...r, ...coverCrop(p.image.w, p.image.h, r.w, r.h), radius } : null);
+ // Landscape (a 16:9 poster): the words get a column beside the picture, not the strip under it.
+ if (W / H > 1.3 && p.layout !== "band") {
+ const framed = p.layout === "frame";
+ const overlay = p.layout === "overlay";
+ const half = Math.round(W * 0.5);
+ const colW = overlay ? Math.round(W * 0.6) - m : half - Math.round(m * 1.5);
+ const bg = overlay ? t.ink : framed ? t.paper : t.accent;
+ const ink = overlay ? "#ffffff" : framed ? (readableOn(bg) === "#ffffff" ? "#ffffff" : t.ink) : t.onAccent;
+ const imgRect = overlay ? { x: 0, y: 0, w: W, h: H } : framed ? { x: half, y: m, w: W - half - m, h: H - 2 * m } : { x: half, y: 0, w: W - half, h: H };
+ const top = m * 1.7;
+ const bottom = H - m;
+ const cta = panelCta(framed || overlay, m, bottom, colW);
+ const gap = m * 0.35;
+ let body = fitBody(colW);
+ const room = () => (cta ? cta.y - gap : bottom) - top - (body ? body.lines.length * body.size * 1.32 + gap : 0);
+ let head = fitHeadline(colW, 4);
+ while (head.lines.length * head.size * 1.08 > room() && head.size > W * 0.042) head = fitHeadline(colW, 4, head.size * 0.92);
+ // Still too tall at the smallest headline: the body steps aside.
+ if (body && head.lines.length * head.size * 1.08 > room()) body = null;
+ const headH = head.lines.length * head.size * 1.08;
+ const bodyH = body ? body.lines.length * body.size * 1.32 + gap : 0;
+ // Overlay: the words sit just above the CTA; panel and frame: from the top of the column.
+ const headY = overlay ? Math.max(top, (cta ? cta.y - gap : bottom) - bodyH - headH) : top;
+ const headline = textBox(head, m, headY, t.heading, 800, ink, "left", colW, 1.08);
+ const bodyBox = body ? textBox(body, m, headY + heightOf(headline) + gap, t.body, overlay ? 500 : 400, overlay ? "rgba(255,255,255,0.9)" : ink, "left", colW, 1.32) : undefined;
+ return {
+ w: W,
+ h: H,
+ bg,
+ image: image(imgRect, framed ? W * 0.02 : 0),
+ panel: overlay || framed ? undefined : { x: 0, y: 0, w: half, h: H, color: bg },
+ scrim: overlay ? { x: 0, y: H * 0.2, w: W, h: H * 0.8, from: "rgba(0,0,0,0)", to: "rgba(0,0,0,0.74)" } : undefined,
+ logo: logoRect(m, m * 0.5, W * 0.22, m * 0.85),
+ brand: brandText(m, m * 0.65, ink, "left"),
+ headline,
+ body: bodyBox,
+ cta,
+ };
+ }
+
if (p.layout === "panel" || p.layout === "frame") {
const framed = p.layout === "frame";
// Frame: the picture on the brand's paper; panel: the words on a brand-colour panel.
const bg = framed ? t.paper : t.accent;
const ink = framed ? (readableOn(bg) === "#ffffff" ? "#ffffff" : t.ink) : t.onAccent;
- const imgH = Math.round(H * (tall ? 0.56 : p.ratio === "4:5" ? 0.58 : 0.54));
+ const imgH = Math.round(H * (tall ? 0.56 : portrait ? 0.58 : 0.54));
const imgRect = framed ? { x: m, y: m * 1.9, w: W - 2 * m, h: imgH - m * 1.4 } : { x: 0, y: 0, w: W, h: imgH };
const top = imgRect.y + imgRect.h + m * 0.8;
const bottom = H - m;
- const cta = framed ? ctaBox(m, bottom, t.accent, t.onAccent, "left") : ctaBox(m, bottom, t.paper, readableOn(t.paper) === "#ffffff" ? "#ffffff" : t.ink, "left");
+ const cta = panelCta(framed, m, bottom);
const body = fitBody(inner);
const gap = m * 0.4;
let head = fitHeadline(inner, tall ? 3 : 2);
@@ -303,7 +355,8 @@ export function planAd(p: PlanInput): AdPlan {
if (p.layout === "band") {
const bandH = Math.round(H * (tall ? 0.24 : 0.27));
- const head = fitHeadline(inner, 2, W * 0.08);
+ // A short (landscape) band takes a smaller headline so two lines still fit in it.
+ const head = fitHeadline(inner, 2, Math.min(W * 0.08, bandH * 0.4));
const headline = textBox(head, W / 2, (bandH - head.lines.length * head.size * 1.08) / 2 + m * 0.25, t.heading, 800, t.onAccent, "center", inner, 1.08);
const bottom = H - m;
const cta = ctaBox(m, bottom, t.paper, readableOn(t.paper) === "#ffffff" ? "#ffffff" : t.ink, "center");
@@ -355,7 +408,7 @@ export function planRects(plan: AdPlan): Rect[] {
}
/** File name for an exported creative: "acme-serum-4x5-3.png". */
-export function exportName(brand: string, product: string | undefined, ratio: AdRatio, n: number): string {
+export function exportName(brand: string, product: string | undefined, ratio: string, n: number): string {
const slug = (s: string) =>
s
.toLowerCase()
diff --git a/src/components/ads/render.ts b/src/components/ads/render.ts
new file mode 100644
index 00000000..4fd96dd9
--- /dev/null
+++ b/src/components/ads/render.ts
@@ -0,0 +1,186 @@
+"use client";
+
+import type { AdRatio } from "@/lib/catalog/marketing";
+import { planAd, sizeFor, type AdContent, type AdLayout, type AdPlan, type AdTheme, type TextBox } from "./layout";
+
+/**
+ * Draw an ad plan (layout.ts) on a canvas: the visual cropped to its box, scrims and panels, the
+ * logo, the words in the brand's Google Fonts and the CTA pill. Used for grid previews (small),
+ * the editor and PNG exports (full size), so they all match.
+ */
+
+const images = new Map<string, Promise<HTMLImageElement>>();
+
+export function loadImage(src: string): Promise<HTMLImageElement> {
+ let p = images.get(src);
+ if (!p) {
+ p = new Promise((resolve, reject) => {
+ const img = new Image();
+ img.decoding = "async";
+ img.onload = () => resolve(img);
+ img.onerror = () => {
+ images.delete(src);
+ reject(new Error("The picture didn't load"));
+ };
+ img.src = src;
+ });
+ images.set(src, p);
+ }
+ return p;
+}
+
+const fonts = new Map<string, Promise<void>>();
+const SYSTEM = /^(inter|system-ui|arial|helvetica|georgia|times new roman|sans-serif|serif)$/i;
+
+/** Load a Google Fonts family (400–800) once; resolves after at most `timeout` ms so offline installs fall back. */
+export function ensureFont(family: string | undefined, timeout = 2500): Promise<void> {
+ if (!family || typeof document === "undefined") return Promise.resolve();
+ const key = family.trim();
+ let p = fonts.get(key);
+ if (!p) {
+ p = new Promise<void>((resolve) => {
+ const done = () => resolve();
+ const timer = setTimeout(done, timeout);
+ const finish = () =>
+ Promise.all([400, 700, 800].map((w) => document.fonts.load(`${w} 32px "${key}"`)))
+ .catch(() => undefined)
+ .finally(() => {
+ clearTimeout(timer);
+ done();
+ });
+ if (SYSTEM.test(key) && key.toLowerCase() !== "inter") return finish();
+ const id = `gf-${key.replace(/\W+/g, "-").toLowerCase()}`;
+ if (!document.getElementById(id)) {
+ const link = document.createElement("link");
+ link.id = id;
+ link.rel = "stylesheet";
+ link.href = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(key).replace(/%20/g, "+")}:wght@400;500;600;700;800&display=swap`;
+ link.onload = () => void finish();
+ link.onerror = done;
+ document.head.appendChild(link);
+ } else void finish();
+ });
+ fonts.set(key, p);
+ }
+ return p;
+}
+
+let measureCtx: CanvasRenderingContext2D | null = null;
+export const measureText = (text: string, font: string) => {
+ measureCtx ??= document.createElement("canvas").getContext("2d");
+ if (!measureCtx) return text.length * 10;
+ measureCtx.font = font;
+ return measureCtx.measureText(text).width;
+};
+
+function rounded(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
+ ctx.beginPath();
+ ctx.roundRect(x, y, w, h, r);
+}
+
+function drawText(ctx: CanvasRenderingContext2D, t: TextBox) {
+ ctx.font = t.font;
+ ctx.fillStyle = t.color;
+ ctx.textBaseline = "top";
+ ctx.textAlign = t.align === "center" ? "center" : "left";
+ t.lines.forEach((line, i) => ctx.fillText(line, t.x, t.y + i * t.lineHeight + (t.lineHeight - t.size) / 2));
+}
+
+export function drawPlan(ctx: CanvasRenderingContext2D, plan: AdPlan, image: CanvasImageSource | null, logo: CanvasImageSource | null) {
+ ctx.save();
+ ctx.fillStyle = plan.bg;
+ ctx.fillRect(0, 0, plan.w, plan.h);
+ if (plan.image && image) {
+ ctx.save();
+ if (plan.image.radius) {
+ rounded(ctx, plan.image.x, plan.image.y, plan.image.w, plan.image.h, plan.image.radius);
+ ctx.clip();
+ }
+ ctx.drawImage(image, plan.image.sx, plan.image.sy, plan.image.sw, plan.image.sh, plan.image.x, plan.image.y, plan.image.w, plan.image.h);
+ ctx.restore();
+ } else if (plan.image) {
+ // No visual yet: a soft placeholder in the picture's box.
+ ctx.fillStyle = "rgba(127,127,127,0.18)";
+ rounded(ctx, plan.image.x, plan.image.y, plan.image.w, plan.image.h, plan.image.radius);
+ ctx.fill();
+ }
+ if (plan.panel) {
+ ctx.fillStyle = plan.panel.color;
+ ctx.fillRect(plan.panel.x, plan.panel.y, plan.panel.w, plan.panel.h);
+ }
+ if (plan.scrim) {
+ const g = ctx.createLinearGradient(0, plan.scrim.y, 0, plan.scrim.y + plan.scrim.h);
+ g.addColorStop(0, plan.scrim.from);
+ g.addColorStop(1, plan.scrim.to);
+ ctx.fillStyle = g;
+ ctx.fillRect(plan.scrim.x, plan.scrim.y, plan.scrim.w, plan.scrim.h);
+ }
+ if (plan.logo && logo) ctx.drawImage(logo, plan.logo.x, plan.logo.y, plan.logo.w, plan.logo.h);
+ if (plan.brand) drawText(ctx, plan.brand);
+ drawText(ctx, plan.headline);
+ if (plan.body) drawText(ctx, plan.body);
+ if (plan.cta) {
+ ctx.fillStyle = plan.cta.color;
+ rounded(ctx, plan.cta.x, plan.cta.y, plan.cta.w, plan.cta.h, plan.cta.radius);
+ ctx.fill();
+ drawText(ctx, plan.cta.text);
+ }
+ ctx.restore();
+}
+
+export interface RenderInput {
+ ratio: AdRatio | string;
+ layout: AdLayout;
+ content: AdContent;
+ theme: AdTheme;
+ image?: string | null;
+ logo?: string | null;
+ /** The visual already holds the words (Higgsfield Ads Studio): draw it alone. */
+ baked?: boolean;
+}
+
+/** Render a creative onto `canvas` at `scale` (1 = full 1080-wide size). */
+export async function renderAd(canvas: HTMLCanvasElement, input: RenderInput, scale = 1): Promise<void> {
+ const [img, logo] = await Promise.all([input.image ? loadImage(input.image).catch(() => null) : null, input.logo ? loadImage(input.logo).catch(() => null) : null, ensureFont(input.theme.heading), ensureFont(input.theme.body)]);
+ const { w, h } = sizeFor(input.ratio);
+ canvas.width = Math.round(w * scale);
+ canvas.height = Math.round(h * scale);
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ ctx.setTransform(scale, 0, 0, scale, 0, 0);
+ if (input.baked) {
+ const plan = planAd({ ratio: input.ratio, layout: "overlay", content: { headline: "" }, theme: input.theme, image: img ? { w: img.naturalWidth, h: img.naturalHeight } : null, measure: measureText });
+ ctx.fillStyle = "#111";
+ ctx.fillRect(0, 0, w, h);
+ if (img && plan.image) ctx.drawImage(img, plan.image.sx, plan.image.sy, plan.image.sw, plan.image.sh, 0, 0, w, h);
+ return;
+ }
+ const plan = planAd({
+ ratio: input.ratio,
+ layout: input.layout,
+ content: input.content,
+ theme: input.theme,
+ image: img ? { w: img.naturalWidth, h: img.naturalHeight } : { w: 4, h: 5 },
+ logo: logo ? { w: logo.naturalWidth || 400, h: logo.naturalHeight || 120 } : null,
+ measure: measureText,
+ });
+ drawPlan(ctx, plan, img, logo);
+}
+
+/** A full-size PNG of a creative. */
+export async function exportPng(input: RenderInput): Promise<Blob> {
+ const canvas = document.createElement("canvas");
+ await renderAd(canvas, input, 1);
+ return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Couldn't export the image"))), "image/png"));
+}
+
+export function downloadBlob(blob: Blob, name: string) {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = name;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 2000);
+}
diff --git a/src/components/ads/zip.ts b/src/components/ads/zip.ts
new file mode 100644
index 00000000..6d321ebb
--- /dev/null
+++ b/src/components/ads/zip.ts
@@ -0,0 +1,93 @@
+/**
+ * A tiny "stored" (uncompressed) zip writer for the browser: "Download all" bundles the PNGs the
+ * canvas made without a server round trip. PNGs are already compressed, so storing loses nothing.
+ */
+
+const TABLE = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+
+export function crc32(data: Uint8Array): number {
+ let c = 0xffffffff;
+ for (let i = 0; i < data.length; i++) c = TABLE[(c ^ data[i]) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+/** Unique names: a second "ad.png" becomes "ad (2).png". */
+export function uniqueNames(names: string[]): string[] {
+ const seen = new Map<string, number>();
+ return names.map((n) => {
+ const k = n.toLowerCase();
+ const count = (seen.get(k) ?? 0) + 1;
+ seen.set(k, count);
+ if (count === 1) return n;
+ const dot = n.lastIndexOf(".");
+ return dot > 0 ? `${n.slice(0, dot)} (${count})${n.slice(dot)}` : `${n} (${count})`;
+ });
+}
+
+export function zipFiles(files: { name: string; data: Uint8Array }[], date = new Date()): Uint8Array {
+ const enc = new TextEncoder();
+ const names = uniqueNames(files.map((f) => f.name));
+ const dosTime = ((date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1)) & 0xffff;
+ const dosDate = (((date.getFullYear() - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate()) & 0xffff;
+ const locals: Uint8Array[] = [];
+ const centrals: Uint8Array[] = [];
+ let offset = 0;
+ files.forEach((f, i) => {
+ const name = enc.encode(names[i]);
+ const crc = crc32(f.data);
+ const local = new Uint8Array(30 + name.length);
+ const lv = new DataView(local.buffer);
+ lv.setUint32(0, 0x04034b50, true);
+ lv.setUint16(4, 20, true);
+ lv.setUint16(6, 0x0800, true); // UTF-8 names
+ lv.setUint16(8, 0, true);
+ lv.setUint16(10, dosTime, true);
+ lv.setUint16(12, dosDate, true);
+ lv.setUint32(14, crc, true);
+ lv.setUint32(18, f.data.length, true);
+ lv.setUint32(22, f.data.length, true);
+ lv.setUint16(26, name.length, true);
+ local.set(name, 30);
+ const central = new Uint8Array(46 + name.length);
+ const cv = new DataView(central.buffer);
+ cv.setUint32(0, 0x02014b50, true);
+ cv.setUint16(4, 20, true);
+ cv.setUint16(6, 20, true);
+ cv.setUint16(8, 0x0800, true);
+ cv.setUint16(10, 0, true);
+ cv.setUint16(12, dosTime, true);
+ cv.setUint16(14, dosDate, true);
+ cv.setUint32(16, crc, true);
+ cv.setUint32(20, f.data.length, true);
+ cv.setUint32(24, f.data.length, true);
+ cv.setUint16(28, name.length, true);
+ cv.setUint32(42, offset, true);
+ central.set(name, 46);
+ locals.push(local, f.data);
+ centrals.push(central);
+ offset += local.length + f.data.length;
+ });
+ const centralSize = centrals.reduce((n, c) => n + c.length, 0);
+ const end = new Uint8Array(22);
+ const ev = new DataView(end.buffer);
+ ev.setUint32(0, 0x06054b50, true);
+ ev.setUint16(8, files.length, true);
+ ev.setUint16(10, files.length, true);
+ ev.setUint32(12, centralSize, true);
+ ev.setUint32(16, offset, true);
+ const out = new Uint8Array(offset + centralSize + 22);
+ let at = 0;
+ for (const part of [...locals, ...centrals, end]) {
+ out.set(part, at);
+ at += part.length;
+ }
+ return out;
+}
diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsx
index 8ea7fba1..2313b212 100644
--- a/src/components/app-sidebar.tsx
+++ b/src/components/app-sidebar.tsx
@@ -38,6 +38,8 @@ import {
Library,
PersonStanding,
Scissors,
+ Megaphone,
+ Target,
type LucideIcon,
} from "lucide-react";
import {
@@ -110,6 +112,8 @@ const NAV: NavGroupDef[] = [
label: "Studios",
items: [
{ href: "/cinema", label: "Cinema Studio", icon: Clapperboard },
+ { href: "/marketing", label: "Marketing Studio", icon: Megaphone },
+ { href: "/ads", label: "Ads Studio", icon: Target },
{ href: "/lipsync", label: "Lipsync & avatars", icon: Mic2 },
{ href: "/motion-control", label: "Motion control", icon: PersonStanding },
{ href: "/video-edit", label: "Edit video", icon: Scissors },
diff --git a/src/components/brand/brand-dialog.tsx b/src/components/brand/brand-dialog.tsx
new file mode 100644
index 00000000..ffc4578b
--- /dev/null
+++ b/src/components/brand/brand-dialog.tsx
@@ -0,0 +1,242 @@
+"use client";
+
+import { ArrowRight, Check, Globe, Loader2, Palette, PenLine, Plus, Sparkles } from "lucide-react";
+import Link from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { kmeans, samplePixels } from "@/components/cinema/color-math";
+import { chipBase, chipIdle, chipOn } from "@/components/studio/chip";
+import { BRAND_EXAMPLES, type BrandKit } from "@/lib/catalog/marketing";
+import { cn } from "@/lib/utils";
+import { useBrand, useBrandActions, useBrands, useCreateBrand } from "@/components/marketing/hooks";
+import { BrandSummary } from "./brand-kit-form";
+import { areaCls, inputCls } from "./fields";
+import { ImageList } from "./image-list";
+import { ResearchProgress } from "./research-progress";
+
+/** The main colours of some pictures (k-means in the browser), for a kit made by hand. */
+export async function paletteFromImages(urls: string[], k = 5): Promise<string[]> {
+ const pixels = [];
+ for (const src of urls.slice(0, 4)) {
+ try {
+ const img = new Image();
+ img.src = src;
+ await img.decode();
+ const c = document.createElement("canvas");
+ c.width = 64;
+ c.height = Math.max(1, Math.round((64 * img.naturalHeight) / Math.max(1, img.naturalWidth)));
+ const ctx = c.getContext("2d");
+ if (!ctx) continue;
+ ctx.drawImage(img, 0, 0, c.width, c.height);
+ pixels.push(...samplePixels(ctx.getImageData(0, 0, c.width, c.height).data, 2000));
+ } catch {
+ // A picture the browser can't decode adds nothing.
+ }
+ }
+ return pixels.length ? kmeans(pixels, k).map((x) => x.color) : [];
+}
+
+/** Website → research, or a description → a kit made by hand. Calls `onDone` with the brand once it's ready. */
+export function BrandStart({ onDone, compact }: { onDone: (b: BrandKit) => void; compact?: boolean }) {
+ const create = useCreateBrand();
+ const [mode, setMode] = useState<"site" | "manual">("site");
+ const [site, setSite] = useState("");
+ const [desc, setDesc] = useState("");
+ const [images, setImages] = useState<string[]>([]);
+ const submitSite = () => {
+ if (!site.trim()) return void toast("Add a website or social link.");
+ create.mutate({ website: site.trim() }, { onSuccess: onDone, onError: (e) => toast.error((e as Error).message) });
+ };
+ const submitManual = async () => {
+ if (!desc.trim() && !images.length) return void toast("Add a description or upload images");
+ const colors = images.length ? await paletteFromImages(images) : undefined;
+ create.mutate({ description: desc.trim(), images, colors: colors?.length ? colors : undefined }, { onSuccess: onDone, onError: (e) => toast.error((e as Error).message) });
+ };
+ return mode === "site" ? (
+ <div className="space-y-3">
+ <form
+ className={cn("flex gap-2", compact ? "flex-col sm:flex-row" : "flex-col sm:flex-row")}
+ onSubmit={(e) => {
+ e.preventDefault();
+ submitSite();
+ }}
+ >
+ <div className="relative min-w-0 flex-1">
+ <Globe className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
+ <input value={site} onChange={(e) => setSite(e.target.value)} placeholder="www.yourbrand.com" aria-label="Your website" className={cn(inputCls, "h-11 rounded-full pl-9 text-[14px]")} autoFocus={!compact} />
+ </div>
+ <Button type="submit" size="lg" className="h-11 rounded-full px-5" disabled={create.isPending}>
+ {create.isPending ? <Loader2 className="animate-spin" /> : <Sparkles />} Research my brand
+ </Button>
+ </form>
+ <p className="text-center text-[13px] text-muted-foreground">
+ Your logo, colours, fonts, voice, selling points and products load from the site.{" "}
+ <button type="button" onClick={() => setMode("manual")} className="font-medium text-brand-text hover:underline">
+ Or create it manually
+ </button>
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-3 text-left">
+ <label className="block text-[13px] font-medium">Describe your business — what you sell, who it&apos;s for, what makes it yours</label>
+ <textarea value={desc} onChange={(e) => setDesc(e.target.value)} rows={4} className={areaCls} placeholder="e.g. Ember & Oat — small-batch granola roasted in Portland…" autoFocus />
+ <div className="flex flex-wrap gap-1.5">
+ {BRAND_EXAMPLES.map((x) => (
+ <button key={x.label} type="button" onClick={() => setDesc(x.text)} className={cn(chipBase, "h-7 px-2.5 text-[12px]", desc === x.text ? chipOn : chipIdle)}>
+ {x.label}
+ </button>
+ ))}
+ </div>
+ <div>
+ <p className="text-[13px] font-medium">Your product (optional)</p>
+ <p className="mb-2 text-[12px] text-muted-foreground">We&apos;ll build the identity around it — palette, typography and mood.</p>
+ <ImageList value={images} onChange={setImages} max={4} size="sm" />
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-2 pt-1">
+ <button type="button" onClick={() => setMode("site")} className="text-[13px] text-muted-foreground hover:text-foreground">
+ ← Use a website instead
+ </button>
+ <Button onClick={() => void submitManual()} disabled={create.isPending}>
+ {create.isPending ? <Loader2 className="animate-spin" /> : <PenLine />} Create brand kit
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/** "Add your brand kit" as a dialog (Marketing Studio, Click to Ad): start, research, then use it. */
+export function BrandKitDialog({ open, onOpenChange, onUse }: { open: boolean; onOpenChange: (o: boolean) => void; onUse: (b: BrandKit) => void }) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[90svh] overflow-y-auto sm:max-w-lg">
+ {/* Mounts with the dialog: every opening starts at "paste your link". */}
+ <BrandKitFlow onOpenChange={onOpenChange} onUse={onUse} />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function BrandKitFlow({ onOpenChange, onUse }: { onOpenChange: (o: boolean) => void; onUse: (b: BrandKit) => void }) {
+ const [id, setId] = useState<string | null>(null);
+ const view = useBrand(id);
+ const actions = useBrandActions(id ?? "");
+ const b = view.data?.brand;
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{b?.status === "ready" ? "Your Brand Kit is ready" : "Add your brand kit"}</DialogTitle>
+ <DialogDescription>
+ {b?.status === "ready" ? "Review it any time — every generation stays on-brand." : "One link is all we need to keep every campaign on-brand."}
+ </DialogDescription>
+ </DialogHeader>
+ {!id && <BrandStart compact onDone={(x) => setId(x.id)} />}
+ {id && !b && (
+ <div className="grid h-40 place-items-center">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
+ </div>
+ )}
+ {b?.status === "researching" && <ResearchProgress brand={b} onCancel={() => actions.cancel.mutate()} canceling={actions.cancel.isPending} />}
+ {b && b.status !== "researching" && (
+ <div className="space-y-4">
+ <BrandSummary brand={b} />
+ {(b.note || b.error) && <p className="rounded-xl bg-highlight/20 px-3 py-2 text-[13px]">{b.error ?? b.note}</p>}
+ {b.status === "canceled" && <p className="text-[13px] text-muted-foreground">Research canceled. The kit keeps what it found so far.</p>}
+ {b.productCount ? <p className="text-[13px] text-muted-foreground">Found {b.productCount} product{b.productCount === 1 ? "" : "s"}.</p> : null}
+ <div className="flex flex-wrap justify-end gap-2">
+ <Button variant="outline" asChild>
+ <Link href={`/ads/${b.id}?step=kit`}>Review and edit</Link>
+ </Button>
+ <Button
+ onClick={() => {
+ onUse(b);
+ onOpenChange(false);
+ }}
+ >
+ <Check /> Use this kit
+ </Button>
+ </div>
+ </div>
+ )}
+ </>
+ );
+}
+
+/** The composer's Brand kit chip: pick a kit, none, or add one. */
+export function BrandChip({ value, onChange }: { value: string | null; onChange: (id: string | null, brand?: BrandKit) => void }) {
+ const [open, setOpen] = useState(false);
+ const [adding, setAdding] = useState(false);
+ const brands = useBrands();
+ const current = brands.data?.find((b) => b.id === value);
+ const ready = brands.data?.filter((b) => b.status !== "researching") ?? [];
+ return (
+ <>
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <button type="button" className={cn(chipBase, current ? chipOn : chipIdle, "max-w-48")} aria-label={current ? `Brand kit: ${current.name}` : "Brand kit"}>
+ {current?.colors.length ? (
+ <span className="flex -space-x-1">
+ {current.colors.slice(0, 3).map((c) => (
+ <span key={c} className="size-3 rounded-full border border-background" style={{ background: c }} />
+ ))}
+ </span>
+ ) : (
+ <Palette className="size-3.5" />
+ )}
+ <span className="truncate">{current?.name ?? "Brand kit"}</span>
+ </button>
+ </PopoverTrigger>
+ <PopoverContent side="top" align="start" collisionPadding={12} className="w-[min(92vw,320px)] p-1.5">
+ <p className="px-2 pt-1 pb-1.5 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">Brand kit</p>
+ <div className="max-h-72 overflow-y-auto">
+ {ready.map((b) => (
+ <button
+ key={b.id}
+ type="button"
+ onClick={() => {
+ onChange(b.id, b);
+ setOpen(false);
+ }}
+ className={cn("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left hover:bg-accent", b.id === value && "bg-brand-faint")}
+ >
+ <BrandSummary brand={b} className="min-w-0 flex-1 [&_.size-12]:size-9" />
+ {b.id === value && <Check className="size-3.5 shrink-0 text-brand-text" />}
+ </button>
+ ))}
+ {!ready.length && <p className="px-2 py-3 text-[13px] text-muted-foreground">No brand kit added yet — paste a link or create one manually to get started.</p>}
+ </div>
+ <div className="mt-1 flex gap-1 border-t pt-1.5">
+ <button
+ type="button"
+ onClick={() => {
+ setOpen(false);
+ setAdding(true);
+ }}
+ className="flex h-8 flex-1 items-center gap-1.5 rounded-lg px-2 text-[13px] font-medium hover:bg-accent"
+ >
+ <Plus className="size-3.5" /> Add brand kit
+ </button>
+ {value && (
+ <button
+ type="button"
+ onClick={() => {
+ onChange(null);
+ setOpen(false);
+ }}
+ className="h-8 rounded-lg px-2 text-[13px] text-muted-foreground hover:bg-accent"
+ >
+ No brand kit
+ </button>
+ )}
+ <Link href="/ads" className="flex h-8 items-center gap-1 rounded-lg px-2 text-[13px] text-muted-foreground hover:bg-accent" onClick={() => setOpen(false)}>
+ Manage <ArrowRight className="size-3" />
+ </Link>
+ </div>
+ </PopoverContent>
+ </Popover>
+ <BrandKitDialog open={adding} onOpenChange={setAdding} onUse={(b) => onChange(b.id, b)} />
+ </>
+ );
+}
diff --git a/src/components/brand/brand-kit-form.tsx b/src/components/brand/brand-kit-form.tsx
new file mode 100644
index 00000000..7c4eb21e
--- /dev/null
+++ b/src/components/brand/brand-kit-form.tsx
@@ -0,0 +1,273 @@
+"use client";
+
+import { Check, Loader2, Plus, Trash2, Upload, X } from "lucide-react";
+import { useEffect, useId, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { BRAND_LANGUAGES, MAX_SELLING_POINTS, SOCIAL_NETWORKS, type BrandKit, type BrandKitFields } from "@/lib/catalog/marketing";
+import { cn } from "@/lib/utils";
+import { useUpdateBrand } from "@/components/marketing/hooks";
+import { areaCls, ColorList, FieldRow, FontField, inputCls, TagInput } from "./fields";
+import { ImageList, uploadImages } from "./image-list";
+
+type Draft = BrandKitFields;
+
+const pickFields = (b: BrandKit): Draft => ({
+ name: b.name,
+ website: b.website,
+ logo: b.logo,
+ tagline: b.tagline,
+ overview: b.overview,
+ colors: b.colors,
+ fonts: b.fonts,
+ values: b.values,
+ aesthetics: b.aesthetics,
+ tone: b.tone,
+ audience: b.audience,
+ sellingPoints: b.sellingPoints,
+ competitors: b.competitors,
+ socials: b.socials,
+ language: b.language,
+ images: b.images,
+ details: b.details,
+});
+
+/** Save what changed, 700 ms after the last edit (and when the form goes away). */
+function useAutosave(brand: BrandKit) {
+ const update = useUpdateBrand(brand.id);
+ const [draft, setDraft] = useState<Draft>(() => pickFields(brand));
+ const [state, setState] = useState<"idle" | "saving" | "saved">("idle");
+ const saved = useRef<Draft>(pickFields(brand));
+ const pending = useRef<Partial<Draft>>({});
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const flush = useRef(() => {});
+ useEffect(() => {
+ flush.current = () => {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = null;
+ const patch = pending.current;
+ if (!Object.keys(patch).length) return;
+ pending.current = {};
+ setState("saving");
+ update.mutate(patch, {
+ onSuccess: (b) => {
+ saved.current = pickFields(b);
+ setState("saved");
+ },
+ onError: (e) => {
+ setState("idle");
+ toast.error((e as Error).message);
+ },
+ });
+ };
+ });
+ useEffect(() => () => flush.current(), []);
+ const set = <K extends keyof Draft>(key: K, value: Draft[K]) => {
+ setDraft((d) => ({ ...d, [key]: value }));
+ pending.current = { ...pending.current, [key]: value };
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(() => flush.current(), 700);
+ };
+ return { draft, set, state, flush: () => flush.current() };
+}
+
+export function SaveState({ state }: { state: "idle" | "saving" | "saved" }) {
+ if (state === "idle") return null;
+ return (
+ <span className="inline-flex items-center gap-1 text-[12px] text-muted-foreground" aria-live="polite">
+ {state === "saving" ? <Loader2 className="size-3 animate-spin" /> : <Check className="size-3" />}
+ {state === "saving" ? "Saving…" : "Saved"}
+ </span>
+ );
+}
+
+function Section({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {
+ return (
+ <section className="space-y-3 rounded-2xl border bg-background p-4 sm:p-5">
+ <div>
+ <h3 className="text-[14px] font-semibold">{title}</h3>
+ {hint && <p className="mt-0.5 text-[12px] text-muted-foreground">{hint}</p>}
+ </div>
+ {children}
+ </section>
+ );
+}
+
+function LogoField({ value, onChange }: { value?: string; onChange: (v?: string) => void }) {
+ const input = useRef<HTMLInputElement>(null);
+ const [busy, setBusy] = useState(false);
+ return (
+ <div className="flex items-center gap-3">
+ <div className="checkerboard grid h-16 w-28 shrink-0 place-items-center overflow-hidden rounded-xl border">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {value ? <img src={value} alt="Logo" className="max-h-full max-w-full object-contain p-1.5" /> : <span className="text-[11px] text-muted-foreground">No logo</span>}
+ </div>
+ <div className="flex flex-wrap gap-1.5">
+ <button type="button" onClick={() => input.current?.click()} className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent">
+ {busy ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />}
+ {value ? "Replace logo" : "Upload logo"}
+ </button>
+ {value && (
+ <button type="button" onClick={() => onChange(undefined)} className="inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[13px] text-muted-foreground hover:bg-accent">
+ <X className="size-3.5" /> Remove
+ </button>
+ )}
+ </div>
+ <input
+ ref={input}
+ type="file"
+ accept="image/png,image/jpeg,image/webp,image/svg+xml"
+ hidden
+ onChange={async (e) => {
+ const f = e.target.files?.[0];
+ e.target.value = "";
+ if (!f) return;
+ setBusy(true);
+ const [url] = await uploadImages([f.type === "image/svg+xml" ? f : f]).catch(() => []);
+ setBusy(false);
+ if (url) onChange(url);
+ }}
+ />
+ </div>
+ );
+}
+
+function Socials({ value, onChange }: { value: BrandKitFields["socials"]; onChange: (v: BrandKitFields["socials"]) => void }) {
+ return (
+ <div className="space-y-2">
+ {value.map((s, i) => (
+ <div key={i} className="flex min-w-0 items-center gap-2">
+ <Select value={s.network} onValueChange={(network) => onChange(value.map((x, j) => (j === i ? { ...x, network } : x)))}>
+ <SelectTrigger className="h-9 w-32 shrink-0" aria-label="Network">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {SOCIAL_NETWORKS.map((n) => (
+ <SelectItem key={n} value={n}>
+ {n}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <input value={s.url} onChange={(e) => onChange(value.map((x, j) => (j === i ? { ...x, url: e.target.value } : x)))} placeholder="https://…" aria-label={`${s.network} link`} className={inputCls} />
+ <button type="button" aria-label={`Remove ${s.network}`} onClick={() => onChange(value.filter((_, j) => j !== i))} className="grid size-8 shrink-0 place-items-center rounded-full text-muted-foreground hover:bg-accent">
+ <Trash2 className="size-3.5" />
+ </button>
+ </div>
+ ))}
+ {value.length < SOCIAL_NETWORKS.length && (
+ <button type="button" onClick={() => onChange([...value, { network: SOCIAL_NETWORKS.find((n) => !value.some((s) => s.network === n)) ?? "Instagram", url: "" }])} className="inline-flex h-8 items-center gap-1.5 rounded-full bg-secondary px-3 text-[13px] font-medium hover:bg-accent">
+ <Plus className="size-3.5" /> Add a social link
+ </button>
+ )}
+ </div>
+ );
+}
+
+/** Review and edit every field of a brand kit; changes save on their own. */
+export function BrandKitForm({ brand }: { brand: BrandKit }) {
+ const { draft, set, state } = useAutosave(brand);
+ const id = useId();
+ const f = (k: string) => `${id}-${k}`;
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-end">
+ <SaveState state={state} />
+ </div>
+ <Section title="Identity">
+ <div className="grid gap-4 sm:grid-cols-2">
+ <FieldRow label="Brand name" htmlFor={f("name")}>
+ <input id={f("name")} value={draft.name} onChange={(e) => set("name", e.target.value)} placeholder="Enter brand name" className={inputCls} />
+ </FieldRow>
+ <FieldRow label="Website" htmlFor={f("site")}>
+ <input id={f("site")} value={draft.website ?? ""} onChange={(e) => set("website", e.target.value)} placeholder="www.yourbrand.com" className={inputCls} />
+ </FieldRow>
+ </div>
+ <FieldRow label="Logo">
+ <LogoField value={draft.logo} onChange={(v) => set("logo", v ?? "")} />
+ </FieldRow>
+ <FieldRow label="Tagline" htmlFor={f("tag")}>
+ <input id={f("tag")} value={draft.tagline ?? ""} onChange={(e) => set("tagline", e.target.value)} placeholder="Enter your brand tagline" className={inputCls} />
+ </FieldRow>
+ <FieldRow label="Description" htmlFor={f("desc")} hint="What the brand sells, who it's for and what makes it different">
+ <textarea id={f("desc")} value={draft.overview ?? ""} onChange={(e) => set("overview", e.target.value)} rows={3} className={areaCls} />
+ </FieldRow>
+ </Section>
+ <Section title="Look" hint="Colours and fonts are used on every ad you make.">
+ <FieldRow label="Colours">
+ <ColorList value={draft.colors} onChange={(v) => set("colors", v)} />
+ </FieldRow>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <FontField label="Display font" value={draft.fonts.heading} onChange={(v) => set("fonts", { ...draft.fonts, heading: v })} sample={draft.name || "Your headline"} />
+ <FontField label="Body font" value={draft.fonts.body} onChange={(v) => set("fonts", { ...draft.fonts, body: v })} sample="The quick brown fox jumps over the lazy dog" />
+ </div>
+ <FieldRow label="Aesthetics" hint="Look and feel, e.g. Minimal, muted colours, natural light">
+ <TagInput label="Aesthetics" value={draft.aesthetics} onChange={(v) => set("aesthetics", v)} placeholder="Add a look" />
+ </FieldRow>
+ <FieldRow label="Images">
+ <ImageList value={draft.images} onChange={(v) => set("images", v)} max={12} size="sm" />
+ </FieldRow>
+ </Section>
+ <Section title="Voice and audience">
+ <FieldRow label="Tone of voice">
+ <TagInput label="Tone of voice" value={draft.tone} onChange={(v) => set("tone", v)} placeholder="e.g. Warm, honest, playful" />
+ </FieldRow>
+ <FieldRow label="Audience" htmlFor={f("aud")} hint="Who the ads are for">
+ <input id={f("aud")} value={draft.audience ?? ""} onChange={(e) => set("audience", e.target.value)} placeholder="People 30+ with dry, sensitive skin who avoid retinol" className={inputCls} />
+ </FieldRow>
+ <FieldRow label="Selling points" hint={`Main reasons to buy, e.g. Free shipping over $50 (up to ${MAX_SELLING_POINTS})`}>
+ <TagInput label="Selling points" value={draft.sellingPoints} onChange={(v) => set("sellingPoints", v)} max={MAX_SELLING_POINTS} placeholder="Add a selling point" />
+ </FieldRow>
+ <FieldRow label="Values">
+ <TagInput label="Values" value={draft.values} onChange={(v) => set("values", v)} placeholder="e.g. Sustainability" />
+ </FieldRow>
+ <div className="grid gap-4 sm:grid-cols-2">
+ <FieldRow label="Language">
+ <Select value={draft.language ?? "English"} onValueChange={(v) => set("language", v)}>
+ <SelectTrigger className="h-9 w-full" aria-label="Language">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {BRAND_LANGUAGES.map((l) => (
+ <SelectItem key={l} value={l}>
+ {l}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FieldRow>
+ <FieldRow label="Competitors">
+ <TagInput label="Competitors" value={draft.competitors} onChange={(v) => set("competitors", v)} placeholder="Brand names" />
+ </FieldRow>
+ </div>
+ </Section>
+ <Section title="Socials and details">
+ <Socials value={draft.socials} onChange={(v) => set("socials", v)} />
+ <FieldRow label="Additional details" hint="Anything else the ads should know: offers, claims to avoid, shipping…">
+ <TagInput label="Additional details" value={draft.details} onChange={(v) => set("details", v)} max={12} placeholder="Add a detail" />
+ </FieldRow>
+ </Section>
+ </div>
+ );
+}
+
+/** A compact read-only summary: logo, name, colours, fonts. */
+export function BrandSummary({ brand, className }: { brand: BrandKit; className?: string }) {
+ return (
+ <div className={cn("flex min-w-0 items-center gap-3", className)}>
+ <div className="checkerboard grid size-12 shrink-0 place-items-center overflow-hidden rounded-xl border">
+ {/* 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 p-1" /> : <span className="text-[16px] font-semibold">{brand.name.slice(0, 1)}</span>}
+ </div>
+ <div className="min-w-0">
+ <p className="truncate text-[14px] font-semibold">{brand.name}</p>
+ <div className="mt-1 flex items-center gap-1">
+ {brand.colors.slice(0, 6).map((c) => (
+ <span key={c} className="size-3.5 rounded-full border" style={{ background: c }} title={c} />
+ ))}
+ {brand.fonts.heading && <span className="ml-1 truncate text-[11px] text-muted-foreground">{brand.fonts.heading}</span>}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/brand/fields.tsx b/src/components/brand/fields.tsx
new file mode 100644
index 00000000..b85b8764
--- /dev/null
+++ b/src/components/brand/fields.tsx
@@ -0,0 +1,162 @@
+"use client";
+
+import { Plus, X } from "lucide-react";
+import { useEffect, useId, useState } from "react";
+import { ensureFont } from "@/components/ads/render";
+import { cn } from "@/lib/utils";
+
+/** Small form pieces shared by the brand kit and product forms. */
+
+export const inputCls =
+ "h-9 w-full min-w-0 rounded-lg border bg-background px-3 text-[13px] outline-none transition-[border-color,box-shadow] placeholder:text-subtle-foreground focus-visible:border-primary focus-visible:ring-4 focus-visible:ring-brand-faint aria-invalid:border-destructive";
+export const areaCls = cn(inputCls, "h-auto min-h-20 resize-y py-2 leading-relaxed");
+
+export function FieldRow({ label, hint, children, className, htmlFor }: { label: string; hint?: React.ReactNode; children: React.ReactNode; className?: string; htmlFor?: string }) {
+ return (
+ <div className={cn("min-w-0 space-y-1.5", className)}>
+ <label htmlFor={htmlFor} className="block text-[12px] font-medium text-muted-foreground">
+ {label}
+ </label>
+ {children}
+ {hint && <p className="text-[11px] text-subtle-foreground">{hint}</p>}
+ </div>
+ );
+}
+
+/** Tags: Enter or comma adds, Backspace on an empty field removes the last, × removes one. */
+export function TagInput({ value, onChange, placeholder, max = 8, label }: { value: string[]; onChange: (v: string[]) => void; placeholder?: string; max?: number; label: string }) {
+ const [text, setText] = useState("");
+ const id = useId();
+ const add = (raw: string) => {
+ const parts = raw
+ .split(/[,\n]/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+ if (!parts.length) return;
+ const next = [...value];
+ for (const p of parts) if (!next.some((x) => x.toLowerCase() === p.toLowerCase()) && next.length < max) next.push(p);
+ onChange(next);
+ setText("");
+ };
+ return (
+ <div className="flex min-h-9 flex-wrap items-center gap-1.5 rounded-lg border bg-background p-1.5 focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint">
+ {value.map((t, i) => (
+ <span key={`${t}-${i}`} className="inline-flex max-w-full items-center gap-1 rounded-full bg-secondary py-0.5 pr-1 pl-2.5 text-[12px]">
+ <span className="truncate">{t}</span>
+ <button type="button" aria-label={`Remove ${t}`} onClick={() => onChange(value.filter((_, j) => j !== i))} className="grid size-4 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <X className="size-3" />
+ </button>
+ </span>
+ ))}
+ {value.length < max && (
+ <input
+ id={id}
+ aria-label={label}
+ value={text}
+ onChange={(e) => (e.target.value.includes(",") ? add(e.target.value) : setText(e.target.value))}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ add(text);
+ } else if (e.key === "Backspace" && !text && value.length) onChange(value.slice(0, -1));
+ }}
+ onBlur={() => add(text)}
+ placeholder={value.length ? "Add…" : placeholder}
+ className="h-6 min-w-24 flex-1 bg-transparent px-1 text-[13px] outline-none placeholder:text-subtle-foreground"
+ />
+ )}
+ </div>
+ );
+}
+
+const HEX = /^#[0-9a-f]{6}$/i;
+
+/** Brand colours: swatches with a picker and a hex field; the first is the main colour. */
+export function ColorList({ value, onChange, max = 8 }: { value: string[]; onChange: (v: string[]) => void; max?: number }) {
+ return (
+ <div className="flex flex-wrap items-start gap-2">
+ {value.map((hex, i) => (
+ <ColorSwatch
+ key={i}
+ hex={hex}
+ main={i === 0}
+ onChange={(h) => onChange(value.map((x, j) => (j === i ? h : x)))}
+ onRemove={() => onChange(value.filter((_, j) => j !== i))}
+ onMain={i ? () => onChange([hex, ...value.filter((_, j) => j !== i)]) : undefined}
+ />
+ ))}
+ {value.length < max && (
+ <button type="button" onClick={() => onChange([...value, "#888888"])} className="grid h-[68px] w-16 place-items-center rounded-xl border border-dashed border-border-strong text-muted-foreground hover:border-primary hover:text-brand-text" aria-label="Add a colour">
+ <Plus className="size-4" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+function ColorSwatch({ hex, main, onChange, onRemove, onMain }: { hex: string; main: boolean; onChange: (h: string) => void; onRemove: () => void; onMain?: () => void }) {
+ const [text, setText] = useState(hex);
+ // A new colour from outside (the picker, "Main") replaces what's typed.
+ const [shown, setShown] = useState(hex);
+ if (shown !== hex) {
+ setShown(hex);
+ setText(hex);
+ }
+ return (
+ <div className="group/sw relative w-16">
+ <label className="block h-11 cursor-pointer overflow-hidden rounded-xl border shadow-soft" style={{ background: HEX.test(hex) ? hex : "#888" }}>
+ <input type="color" value={HEX.test(hex) ? hex : "#888888"} onChange={(e) => onChange(e.target.value)} className="sr-only" aria-label={`Colour ${hex}${main ? " (main)" : ""}`} />
+ </label>
+ <input
+ value={text}
+ onChange={(e) => {
+ setText(e.target.value);
+ const v = e.target.value.startsWith("#") ? e.target.value : `#${e.target.value}`;
+ if (HEX.test(v)) onChange(v.toLowerCase());
+ }}
+ aria-label="Hex colour"
+ className="mt-1 h-6 w-full rounded-md bg-transparent px-1 text-center font-mono text-[11px] outline-none focus:bg-muted"
+ />
+ {main && <span className="absolute top-1 left-1 rounded-full bg-black/45 px-1.5 text-[9px] font-semibold tracking-wide text-white uppercase">Main</span>}
+ <div className="absolute -top-1.5 -right-1.5 flex gap-0.5 opacity-100 transition-opacity sm:opacity-0 sm:group-hover/sw:opacity-100 sm:group-focus-within/sw:opacity-100">
+ {onMain && (
+ <button type="button" onClick={onMain} className="h-5 rounded-full border bg-background px-1.5 text-[9px] font-semibold shadow-soft" aria-label="Make this the main colour">
+ Main
+ </button>
+ )}
+ <button type="button" onClick={onRemove} className="grid size-5 place-items-center rounded-full border bg-background shadow-soft" aria-label={`Remove ${hex}`}>
+ <X className="size-3" />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export const POPULAR_FONTS = [
+ "Inter", "DM Sans", "Manrope", "Poppins", "Montserrat", "Space Grotesk", "Work Sans", "Nunito Sans", "Rubik", "Outfit", "Plus Jakarta Sans", "Sora", "Lexend", "Archivo",
+ "Oswald", "Bebas Neue", "Anton", "Playfair Display", "Fraunces", "Cormorant Garamond", "DM Serif Display", "Libre Baskerville", "Lora", "Merriweather", "EB Garamond",
+ "Instrument Serif", "Syne", "Unbounded", "Righteous", "Pacifico", "Caveat", "Permanent Marker", "Archivo Black", "Abril Fatface", "IBM Plex Sans", "Roboto", "Open Sans",
+];
+
+/** A Google Fonts family by name, with a live sample in that font. */
+export function FontField({ label, value, onChange, sample }: { label: string; value?: string; onChange: (v: string) => void; sample: string }) {
+ const id = useId();
+ const [loadedFont, setLoadedFont] = useState<string | null>(null);
+ const loaded = !!value && loadedFont === value;
+ useEffect(() => {
+ if (value) void ensureFont(value).then(() => setLoadedFont(value));
+ }, [value]);
+ return (
+ <FieldRow label={label} htmlFor={id}>
+ <input id={id} list={`${id}-fonts`} value={value ?? ""} onChange={(e) => onChange(e.target.value)} placeholder="e.g. Playfair Display" className={inputCls} />
+ <datalist id={`${id}-fonts`}>
+ {POPULAR_FONTS.map((f) => (
+ <option key={f} value={f} />
+ ))}
+ </datalist>
+ <p className={cn("truncate text-[20px] leading-tight transition-opacity", !loaded && value && "opacity-60")} style={{ fontFamily: value ? `"${value}", system-ui` : undefined }}>
+ {sample}
+ </p>
+ </FieldRow>
+ );
+}
diff --git a/src/components/brand/image-list.tsx b/src/components/brand/image-list.tsx
new file mode 100644
index 00000000..8b3d2677
--- /dev/null
+++ b/src/components/brand/image-list.tsx
@@ -0,0 +1,116 @@
+"use client";
+
+import { ImagePlus, Library, Loader2, X } from "lucide-react";
+import { useRef, useState } from "react";
+import { toast } from "sonner";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { LibraryGrid } from "@/components/studio/media-slot";
+import { uploadFile } from "@/lib/api";
+import { cn } from "@/lib/utils";
+
+/** Upload files as images; resolves the /api/files URLs (bad files are skipped with a toast). */
+export async function uploadImages(files: File[]): Promise<string[]> {
+ const out: string[] = [];
+ for (const f of files) {
+ if (!f.type.startsWith("image/")) {
+ toast(`${f.name} isn't an image`);
+ continue;
+ }
+ if (f.size > 32 * 1024 * 1024) {
+ toast("An image is over 32 MB. Use a smaller one.");
+ continue;
+ }
+ try {
+ out.push((await uploadFile(f)).url);
+ } catch (e) {
+ toast.error((e as Error).message);
+ }
+ }
+ return out;
+}
+
+/** A row of pictures with add (upload or library), remove and "first is the hero". */
+export function ImageList({ value, onChange, max = 8, label = "Add image", heroLabel, size = "md" }: { value: string[]; onChange: (v: string[]) => void; max?: number; label?: string; heroLabel?: string; size?: "sm" | "md" }) {
+ const input = useRef<HTMLInputElement>(null);
+ const [busy, setBusy] = useState(0);
+ const [lib, setLib] = useState(false);
+ const dim = size === "sm" ? "size-14" : "size-20";
+ 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={cn("group/img relative shrink-0 overflow-hidden rounded-xl bg-muted", dim)}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={src} alt="" className="size-full object-cover" />
+ {i === 0 && heroLabel && <span className="absolute inset-x-0 bottom-0 bg-black/50 py-0.5 text-center text-[10px] font-medium text-white">{heroLabel}</span>}
+ {i > 0 && heroLabel && (
+ <button type="button" onClick={() => onChange([src, ...value.filter((x) => x !== src)])} className="absolute inset-x-0 bottom-0 bg-black/50 py-0.5 text-[10px] font-medium text-white opacity-100 sm:opacity-0 sm:group-hover/img:opacity-100 focus-visible:opacity-100">
+ Make first
+ </button>
+ )}
+ <button type="button" aria-label="Remove image" 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 sm:opacity-0 sm:group-hover/img:opacity-100 focus-visible:opacity-100">
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ {Array.from({ length: busy }, (_, i) => (
+ <div key={`b${i}`} className={cn("grid shrink-0 place-items-center rounded-xl bg-muted", dim)}>
+ <Loader2 className="size-4 animate-spin text-muted-foreground" />
+ </div>
+ ))}
+ {value.length + busy < max && (
+ <div className={cn("relative flex shrink-0 flex-col overflow-hidden rounded-xl border border-dashed border-border-strong", dim)}>
+ <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">
+ <ImagePlus className="size-4" />
+ {size === "md" && label}
+ </button>
+ <Popover open={lib} onOpenChange={setLib}>
+ <PopoverTrigger asChild>
+ <button type="button" className="flex h-5 items-center justify-center gap-1 border-t border-dashed border-border-strong text-[10px] text-muted-foreground hover:bg-brand-faint hover:text-brand-text" aria-label="Choose from library">
+ <Library className="size-3" />
+ {size === "md" && "Library"}
+ </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,image/gif"
+ multiple
+ hidden
+ onChange={(e) => {
+ void add([...(e.target.files ?? [])]);
+ e.target.value = "";
+ }}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/brand/products.tsx b/src/components/brand/products.tsx
new file mode 100644
index 00000000..cd9197cf
--- /dev/null
+++ b/src/components/brand/products.tsx
@@ -0,0 +1,226 @@
+"use client";
+
+import { Check, Link2, Loader2, MoreHorizontal, Package, Pencil, Plus, Trash2, Upload } from "lucide-react";
+import { useId, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { MAX_SELLING_POINTS, type Product } from "@/lib/catalog/marketing";
+import { cn } from "@/lib/utils";
+import { useProductActions, type ProductInput } from "@/components/marketing/hooks";
+import { areaCls, FieldRow, inputCls, TagInput } from "./fields";
+import { ImageList } from "./image-list";
+
+export const priceText = (p: Pick<Product, "price" | "currency">) =>
+ p.price == null ? "" : `${p.currency && p.currency.length === 3 && p.currency !== "USD" ? `${p.currency} ` : "$"}${p.price % 1 ? p.price.toFixed(2) : p.price}`;
+
+/** Add (or edit) a product: name required; up to five selling points; pictures. */
+export function ProductDialog({ open, onOpenChange, brandId, product, onSaved }: { open: boolean; onOpenChange: (o: boolean) => void; brandId?: string | null; product?: Product | null; onSaved?: (p: Product) => void }) {
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-h-[90svh] overflow-y-auto sm:max-w-lg">
+ {/* The form mounts with the dialog, so every opening starts from the product as saved. */}
+ <ProductForm key={product?.id ?? "new"} onOpenChange={onOpenChange} brandId={brandId} product={product} onSaved={onSaved} />
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+const BLANK_PRODUCT: ProductInput = { name: "", description: "", audience: "", sellingPoints: [], images: [], url: "", price: null };
+
+function ProductForm({ onOpenChange, brandId, product, onSaved }: { onOpenChange: (o: boolean) => void; brandId?: string | null; product?: Product | null; onSaved?: (p: Product) => void }) {
+ const { create, update } = useProductActions();
+ const id = useId();
+ const [draft, setDraft] = useState<ProductInput>(() => (product ? { ...product } : BLANK_PRODUCT));
+ const [priceText_, setPriceText] = useState(() => (product?.price != null ? String(product.price) : ""));
+ const [dup, setDup] = useState<string | null>(null);
+ const set = <K extends keyof ProductInput>(k: K, v: ProductInput[K]) => setDraft((d) => ({ ...d, [k]: v }));
+ const price = priceText_.trim() ? Number(priceText_.replace(",", ".")) : null;
+ const priceError = price != null && (!Number.isFinite(price) || price < 0) ? "Price cannot be negative." : null;
+ const busy = create.isPending || update.isPending;
+ const save = (force = false) => {
+ if (!draft.name?.trim()) return void toast("Give the product a name");
+ if (priceError) return void toast(priceError);
+ const body = { ...draft, name: draft.name.trim(), price, brandId: product ? draft.brandId : (brandId ?? null) };
+ const done = (p: Product) => {
+ toast.success(product ? "Saved" : "Product added", { duration: 1500 });
+ onSaved?.(p);
+ onOpenChange(false);
+ };
+ if (product) update.mutate({ ...body, id: product.id }, { onSuccess: done, onError: (e) => toast.error((e as Error).message) });
+ else
+ create.mutate(
+ { ...body, force },
+ {
+ onSuccess: done,
+ onError: (e) => ((e as { status?: number }).status === 409 ? setDup((e as Error).message) : toast.error((e as Error).message)),
+ },
+ );
+ };
+ return (
+ <>
+ <DialogHeader>
+ <DialogTitle>{product ? "Edit product" : "Upload product"}</DialogTitle>
+ <DialogDescription>Products are shared by Marketing Studio, Ads Studio and Click to Ad.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <FieldRow label="Pictures" hint="The first picture is the one models see first.">
+ <ImageList value={draft.images ?? []} onChange={(v) => set("images", v)} heroLabel="Main" />
+ </FieldRow>
+ <FieldRow label="Product name" htmlFor={`${id}-n`}>
+ <input id={`${id}-n`} value={draft.name ?? ""} onChange={(e) => set("name", e.target.value)} placeholder="Acme Product" className={inputCls} required aria-required />
+ </FieldRow>
+ <FieldRow label="Description" htmlFor={`${id}-d`}>
+ <textarea id={`${id}-d`} value={draft.description ?? ""} onChange={(e) => set("description", e.target.value)} placeholder="What the product is and who it is for" rows={3} className={areaCls} />
+ </FieldRow>
+ <div className="grid gap-4 sm:grid-cols-[1fr_2fr]">
+ <FieldRow label="Price" htmlFor={`${id}-p`}>
+ <input id={`${id}-p`} inputMode="decimal" value={priceText_} onChange={(e) => setPriceText(e.target.value)} placeholder="29.90" aria-invalid={!!priceError} className={inputCls} />
+ {priceError && <p className="text-[11px] text-destructive">{priceError}</p>}
+ </FieldRow>
+ <FieldRow label="Link" htmlFor={`${id}-u`}>
+ <input id={`${id}-u`} value={draft.url ?? ""} onChange={(e) => set("url", e.target.value)} placeholder="https://yourshop.com/products/…" className={inputCls} />
+ </FieldRow>
+ </div>
+ <FieldRow label="Audience" htmlFor={`${id}-a`}>
+ <input id={`${id}-a`} value={draft.audience ?? ""} onChange={(e) => set("audience", e.target.value)} placeholder="People 30+ with dry, sensitive skin who avoid retinol" className={inputCls} />
+ </FieldRow>
+ <FieldRow label="Selling points" hint="Add up to five selling points.">
+ <TagInput label="Selling points" value={draft.sellingPoints ?? []} onChange={(v) => set("sellingPoints", v)} max={MAX_SELLING_POINTS} placeholder="e.g. Keeps drinks cold for 24 hours" />
+ </FieldRow>
+ {dup && (
+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-xl bg-highlight/20 px-3 py-2 text-[13px]">
+ <span>{dup}</span>
+ <Button size="sm" variant="outline" onClick={() => save(true)}>
+ Create anyway
+ </Button>
+ </div>
+ )}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button onClick={() => save()} disabled={busy}>
+ {busy && <Loader2 className="animate-spin" />}
+ {product ? "Save" : "Add product"}
+ </Button>
+ </DialogFooter>
+ </>
+ );
+}
+
+/** "Add product from link": reads the page, adds what it finds. */
+export function AddFromLink({ brandId, onAdded, limit = 3, withBrand, className, placeholder = "Paste a product link" }: { brandId?: string | null; onAdded?: (ps: Product[], extra: { brand?: { logo?: string; colors: string[]; name?: string } }) => void; limit?: number; withBrand?: boolean; className?: string; placeholder?: string }) {
+ const { read } = useProductActions();
+ const [url, setUrl] = useState("");
+ const [slow, setSlow] = useState(false);
+ const go = () => {
+ if (!url.trim()) return void toast("Use a valid product link.");
+ const host = (() => {
+ try {
+ return new URL(/^https?:/i.test(url) ? url : `https://${url}`).hostname;
+ } catch {
+ return url;
+ }
+ })();
+ setSlow(false);
+ const t = setTimeout(() => setSlow(true), 12_000);
+ const id = toast.loading(`Reading ${host}`);
+ read.mutate(
+ { url: url.trim(), brandId, limit, withBrand },
+ {
+ onSuccess: (r) => {
+ if (r.duplicate) toast(r.message ?? `«${r.duplicate.name}» is already among this brand's products.`, { id });
+ else if (r.message) toast.success(r.message, { id, duration: 5000 });
+ else toast.success(r.products.length === 1 ? `Added ${r.products[0].name}` : `Added ${r.products.length} products`, { id, duration: 2000 });
+ setUrl("");
+ onAdded?.(r.duplicate ? [r.duplicate] : r.products, { brand: r.brand });
+ },
+ onError: (e) => toast.error(`${(e as Error).message}`, { id, description: "Try again, or add it by hand." }),
+ onSettled: () => clearTimeout(t),
+ },
+ );
+ };
+ return (
+ <form
+ className={cn("flex min-w-0 gap-2", className)}
+ onSubmit={(e) => {
+ e.preventDefault();
+ go();
+ }}
+ >
+ <div className="relative min-w-0 flex-1">
+ <Link2 className="pointer-events-none absolute top-1/2 left-3 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <input value={url} onChange={(e) => setUrl(e.target.value)} placeholder={placeholder} aria-label="Product link" className={cn(inputCls, "pl-8")} />
+ </div>
+ <Button type="submit" variant="outline" disabled={read.isPending}>
+ {read.isPending ? <Loader2 className="animate-spin" /> : <Plus />} Add
+ </Button>
+ {read.isPending && slow && <span className="sr-only">This is taking longer than usual</span>}
+ </form>
+ );
+}
+
+export function ProductThumb({ product, className }: { product: Pick<Product, "images" | "name">; className?: string }) {
+ return (
+ <div className={cn("grid place-items-center overflow-hidden bg-muted", className)}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ {product.images[0] ? <img src={product.images[0]} alt="" className="size-full object-cover" loading="lazy" /> : <Package className="size-5 text-muted-foreground" />}
+ </div>
+ );
+}
+
+/** A product card: picture, name, price; select (Ads Studio) or open to edit. */
+export function ProductCard({ product, selected, onToggle, onEdit, onDelete, disabled }: { product: Product; selected?: boolean; onToggle?: () => void; onEdit?: () => void; onDelete?: () => void; disabled?: boolean }) {
+ const selectable = !!onToggle;
+ return (
+ <div className={cn("group/pc relative min-w-0 rounded-xl border bg-background p-2 transition-shadow", selected && "border-primary ring-4 ring-brand-faint", disabled && !selected && "opacity-60")}>
+ <button type="button" onClick={selectable ? onToggle : onEdit} disabled={disabled && !selected} aria-pressed={selectable ? selected : undefined} className="block w-full text-left outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-lg">
+ <ProductThumb product={product} className="aspect-square rounded-lg" />
+ <p className="mt-2 truncate text-[13px] font-medium">{product.name}</p>
+ <p className="truncate text-[12px] text-muted-foreground">{[priceText(product), product.images.length ? `${product.images.length} picture${product.images.length === 1 ? "" : "s"}` : "No pictures"].filter(Boolean).join(" · ")}</p>
+ </button>
+ {selectable && (
+ <span className={cn("pointer-events-none absolute top-3.5 left-3.5 grid size-5 place-items-center rounded-full border-2 border-white bg-black/30 text-white shadow", selected && "border-primary bg-primary")}>
+ {selected && <Check className="size-3" />}
+ </span>
+ )}
+ {(onEdit || onDelete) && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <button className="absolute top-3.5 right-3.5 grid size-7 place-items-center rounded-full bg-black/45 text-white opacity-100 backdrop-blur sm:opacity-0 sm:group-hover/pc:opacity-100 focus-visible:opacity-100 data-[state=open]:opacity-100" aria-label={`${product.name} actions`}>
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {onEdit && (
+ <DropdownMenuItem onClick={onEdit}>
+ <Pencil /> Edit
+ </DropdownMenuItem>
+ )}
+ {onDelete && (
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </div>
+ );
+}
+
+/** The "Upload product" button with its dialog. */
+export function UploadProductButton({ brandId, onSaved, variant = "outline" }: { brandId?: string | null; onSaved?: (p: Product) => void; variant?: "outline" | "ghost" | "secondary" }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <>
+ <Button variant={variant} onClick={() => setOpen(true)}>
+ <Upload /> Upload product
+ </Button>
+ <ProductDialog open={open} onOpenChange={setOpen} brandId={brandId} onSaved={onSaved} />
+ </>
+ );
+}
diff --git a/src/components/brand/research-progress.tsx b/src/components/brand/research-progress.tsx
new file mode 100644
index 00000000..2d8e8730
--- /dev/null
+++ b/src/components/brand/research-progress.tsx
@@ -0,0 +1,48 @@
+"use client";
+
+import { Loader2, Sparkles } from "lucide-react";
+import { useEffect, useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Progress } from "@/components/ui/progress";
+import { researchLabel, RESEARCH_LABELS, type BrandKit } from "@/lib/catalog/marketing";
+
+/** The clock, ticking every `every` ms (rotating labels). */
+function useNow(every: number) {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const t = setInterval(() => setNow(Date.now()), every);
+ return () => clearInterval(t);
+ }, [every]);
+ return now;
+}
+
+/** Just the current research label (a brand card's badge). */
+export function ResearchLabel({ progress }: { progress: BrandKit["progress"] }) {
+ const now = useNow(1500);
+ return <>{researchLabel(progress, now).label}</>;
+}
+
+/** "Usually takes about a minute": Higgsfield's rotating research labels, a progress bar and Cancel. */
+export function ResearchProgress({ brand, onCancel, canceling }: { brand: BrandKit; onCancel?: () => void; canceling?: boolean }) {
+ const now = useNow(700);
+ const { index, label } = researchLabel(brand.progress, now);
+ const host = brand.website ? new URL(brand.website).hostname.replace(/^www\./, "") : brand.name;
+ return (
+ <div role="status" aria-live="polite" className="mx-auto w-full max-w-md text-center">
+ <div className="mx-auto grid size-14 place-items-center rounded-2xl bg-brand-faint text-brand-text">
+ <Sparkles className="size-6 animate-pulse" />
+ </div>
+ <h2 className="mt-5 font-heading text-[26px] leading-tight">Researching {host}</h2>
+ <p className="mt-1 text-[14px] text-muted-foreground">Usually takes about a minute. You can leave this page — it keeps going.</p>
+ <Progress value={((index + 1) / RESEARCH_LABELS.length) * 100} className="mt-6 h-1.5" aria-label="Research progress" />
+ <p key={label} className="mt-3 animate-fade-up text-[13px] font-medium">
+ <span className="shimmer-text animate-shimmer-text">{label}…</span>
+ </p>
+ {onCancel && (
+ <Button variant="ghost" size="sm" className="mt-5 text-muted-foreground" onClick={onCancel} disabled={canceling}>
+ {canceling && <Loader2 className="animate-spin" />} Cancel research
+ </Button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/marketing/click-to-ad.tsx b/src/components/marketing/click-to-ad.tsx
new file mode 100644
index 00000000..08a8c9e2
--- /dev/null
+++ b/src/components/marketing/click-to-ad.tsx
@@ -0,0 +1,340 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { Check, Clapperboard, Loader2, MousePointerClick, PenLine, RefreshCw, Sparkles, Wand2 } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import { areaCls, inputCls } from "@/components/brand/fields";
+import { ImageList } from "@/components/brand/image-list";
+import { AddFromLink, priceText, ProductThumb, UploadProductButton } from "@/components/brand/products";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { AD_STYLES, KIT_LABELS, type MarketingRun, type Product, type RunEstimate } from "@/lib/catalog/marketing";
+import { formatCost } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { addRuns, send, useBrand, useEstimate, useProductActions, useProducts } from "./hooks";
+import type { ModelInfo } from "./model-info";
+import { AvatarSlot, VoiceControl } from "./pickers";
+import { RunsList } from "./runs";
+import { EmptyIcon, MarketingHeader, useMarketingEngine } from "./shell";
+import { TemplatePreview } from "./template-preview";
+
+function Step({ n, title, hint, done, children }: { n: number; title: string; hint?: string; done?: boolean; children: React.ReactNode }) {
+ return (
+ <section className="rounded-2xl border bg-background p-4 sm:p-6">
+ <div className="mb-4 flex items-start gap-3">
+ <span className={cn("grid size-7 shrink-0 place-items-center rounded-full text-[13px] font-semibold", done ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground")}>{done ? <Check className="size-3.5" /> : n}</span>
+ <div className="min-w-0">
+ <h2 className="text-[16px] font-semibold">{title}</h2>
+ {hint && <p className="text-[13px] text-muted-foreground">{hint}</p>}
+ </div>
+ </div>
+ {children}
+ </section>
+ );
+}
+
+/** "Building your product kit": the six labels, stepped while the link is read. */
+function KitProgress() {
+ const [i, setI] = useState(0);
+ useEffect(() => {
+ const t = setInterval(() => setI((x) => Math.min(KIT_LABELS.length - 1, x + 1)), 1800);
+ return () => clearInterval(t);
+ }, []);
+ return (
+ <div role="status" className="mt-4 rounded-xl bg-muted/60 p-4">
+ <p className="text-[12px] font-semibold tracking-wide text-muted-foreground uppercase">Building your product kit</p>
+ <ol className="mt-2 grid gap-1 sm:grid-cols-2">
+ {KIT_LABELS.map((l, k) => (
+ <li key={l} className={cn("flex items-center gap-2 text-[13px]", k > i && "text-subtle-foreground")}>
+ {k < i ? <Check className="size-3.5 text-success" /> : k === i ? <Loader2 className="size-3.5 animate-spin text-brand-text" /> : <span className="size-3.5" />}
+ {l}
+ </li>
+ ))}
+ </ol>
+ </div>
+ );
+}
+
+const styleScene = (presenter: boolean, dark?: boolean) => (presenter ? "selfie" : dark ? "noir" : "orbit");
+
+/** Click to Ad: product link → product kit → style → a 9:16 ad of up to 12 s with voiceover and captions. */
+export function ClickToAd({ models }: { models: Record<string, ModelInfo> }) {
+ const qc = useQueryClient();
+ const { engine, setEngine } = useMarketingEngine();
+ const products = useProducts();
+ const { update, read } = useProductActions();
+ const [productId, setProductId] = useState<string | null>(null);
+ const [picked, setPicked] = useState<string[]>([]);
+ const [brandBits, setBrandBits] = useState<{ logo?: string; colors: string[] } | null>(null);
+ const [styleId, setStyleId] = useState(AD_STYLES[0].id);
+ const [presenter, setPresenter] = useState<boolean | null>(null);
+ const [voice, setVoice] = useState<string | undefined>();
+ const [sample, setSample] = useState<SlotValue | null>(null);
+ const [avatar, setAvatar] = useState<SlotValue | null>(null);
+ const [quality, setQuality] = useState<"480p" | "720p">("480p");
+ const [mode, setMode] = useState<"auto" | "custom">("auto");
+ const [instructions, setInstructions] = useState("");
+ const [script, setScript] = useState<string | null>(null);
+ const [writing, setWriting] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const resultsRef = useRef<HTMLDivElement>(null);
+ const product = products.data?.find((p) => p.id === productId) ?? null;
+ const brand = useBrand(product?.brandId).data?.brand;
+ const style = AD_STYLES.find((s) => s.id === styleId)!;
+ const withPresenter = presenter ?? style.presenter;
+ const [name, setName] = useState("");
+ const [desc, setDesc] = useState("");
+
+ const choose = (p: Product, bits?: { logo?: string; colors: string[] }) => {
+ setProductId(p.id);
+ setPicked(p.images.slice(0, 3));
+ setName(p.name);
+ setDesc(p.description ?? "");
+ setScript(null);
+ if (bits) setBrandBits(bits);
+ };
+ const saveField = (patch: { name?: string; description?: string }) => {
+ if (!product) return;
+ if (patch.name !== undefined && !patch.name.trim()) return void toast("Give the product a name");
+ update.mutate({ id: product.id, ...patch });
+ };
+ const body = useMemo(
+ () =>
+ productId
+ ? {
+ engine,
+ productId,
+ styleId,
+ images: picked.length ? picked : undefined,
+ presenter: withPresenter,
+ script: script ?? undefined,
+ instructions: mode === "custom" ? instructions || undefined : undefined,
+ quality,
+ voice,
+ voiceSample: sample?.ref,
+ avatar: withPresenter ? avatar?.ref : undefined,
+ }
+ : null,
+ [engine, productId, styleId, picked, withPresenter, script, mode, instructions, quality, voice, sample, avatar],
+ );
+ const est = useEstimate<RunEstimate>("/api/marketing/click-to-ad/estimate", body);
+ const blocker = !product ? "Select a product or enter a product URL" : !product.images.length ? `${product.name} has no images` : !desc.trim() ? "Add a description" : est.data?.blocker;
+ const cost = est.data && !est.data.blocker ? (est.data.demo ? "Demo · free" : est.data.costUsd == null ? "" : `≈ ${formatCost(est.data.costUsd)}`) : "";
+
+ const writeScript = async () => {
+ if (!productId) return;
+ setWriting(true);
+ try {
+ const r = await send<{ script: string; by: "llm" | "rules" }>("/api/marketing/script", "POST", { engine, productId, styleId, presenter: withPresenter, instructions: mode === "custom" ? instructions : undefined });
+ setScript(r.script);
+ if (r.by === "rules") toast("Written from your product's facts — connect Claude or Ollama in Settings for livelier scripts", { duration: 4000 });
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setWriting(false);
+ }
+ };
+ const generate = async () => {
+ if (blocker) return void toast(blocker, { id: "c2a-blocker" });
+ setBusy(true);
+ try {
+ const r = await send<{ run: MarketingRun; script: string }>("/api/marketing/click-to-ad", "POST", body);
+ addRuns(qc, "click-to-ad", [r.run]);
+ setScript(r.script);
+ toast.success("Creating your video", { duration: 1600 });
+ resultsRef.current?.scrollIntoView({ behavior: "smooth", block: "start" });
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <MarketingHeader title="Click to Ad" active="click" engine={engine} onEngine={setEngine} />
+ <main className="mx-auto w-full min-w-0 max-w-[980px] flex-1 space-y-5 px-3 pt-6 pb-20 sm:px-6 sm:pt-10">
+ <div className="pb-2 text-center">
+ <h2 className="font-heading text-display text-balance">Make a video ad in one click</h2>
+ <p className="mx-auto mt-2 max-w-xl text-[15px] text-muted-foreground">Drop a product link, get a 9:16 ad with voiceover and captions — ready for TikTok, Reels and Shorts. No filming, no editing, no brief.</p>
+ </div>
+
+ <Step n={1} title="Your product" hint="Paste the product's own page, or pick one you saved." done={!!product}>
+ <AddFromLink limit={1} withBrand placeholder="https://yourshop.com/products/…" onAdded={(ps, extra) => ps[0] && choose(ps[0], extra.brand)} />
+ {read.isPending && <KitProgress />}
+ <div className="mt-5">
+ <div className="mb-2 flex items-center justify-between gap-2">
+ <p className="text-[12px] font-medium text-muted-foreground">Or select your product</p>
+ <UploadProductButton variant="ghost" onSaved={(p) => choose(p)} />
+ </div>
+ {products.data?.length ? (
+ <div className="scrollbar-none -mx-1 flex gap-2 overflow-x-auto px-1 pb-1">
+ {products.data.map((p) => (
+ <button key={p.id} type="button" onClick={() => choose(p)} aria-pressed={p.id === productId} className={cn("w-28 shrink-0 rounded-xl border p-1.5 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring", p.id === productId && "border-primary bg-brand-faint")}>
+ <ProductThumb product={p} className="aspect-square rounded-lg" />
+ <span className="mt-1 block truncate text-[12px] font-medium">{p.name}</span>
+ <span className="block truncate text-[11px] text-muted-foreground">{priceText(p) || `${p.images.length} pictures`}</span>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="text-[13px] text-muted-foreground">No saved products yet.</p>
+ )}
+ </div>
+ </Step>
+
+ {product && (
+ <Step n={2} title="Your product kit" hint="Review the details we extracted — edit anything before generating your video." done={!!desc.trim() && picked.length > 0}>
+ <div className="grid min-w-0 gap-5 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
+ <div className="min-w-0 space-y-3">
+ <p className="text-[12px] font-medium text-muted-foreground">These {Math.min(3, picked.length) || 3} images will be used in your video</p>
+ <ImageList value={picked} onChange={(v) => setPicked(v.slice(0, 5))} max={5} heroLabel="First" size="sm" />
+ {product.images.filter((u) => !picked.includes(u)).length > 0 && (
+ <>
+ <p className="text-[12px] text-muted-foreground">Additional images found — tap to use</p>
+ <div className="flex flex-wrap gap-2">
+ {product.images
+ .filter((u) => !picked.includes(u))
+ .map((u) => (
+ <button key={u} type="button" onClick={() => setPicked((p) => [...p, u].slice(0, 5))} className="size-14 overflow-hidden rounded-xl opacity-70 hover:opacity-100" aria-label="Use this image">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={u} alt="" className="size-full object-cover" />
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+ {(brandBits?.logo || brand?.logo || (brandBits?.colors.length ?? brand?.colors.length)) && (
+ <div className="flex items-center gap-3 pt-1">
+ {(brandBits?.logo || brand?.logo) && (
+ <div className="checkerboard grid h-10 w-20 place-items-center overflow-hidden rounded-lg border">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={brandBits?.logo || brand?.logo} alt="Logo" className="max-h-full max-w-full object-contain p-1" />
+ </div>
+ )}
+ <div className="flex gap-1">
+ {(brandBits?.colors.length ? brandBits.colors : (brand?.colors ?? [])).slice(0, 6).map((c) => (
+ <span key={c} className="size-5 rounded-full border" style={{ background: c }} title={c} />
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="min-w-0 space-y-3">
+ <label className="block space-y-1.5">
+ <span className="text-[12px] font-medium text-muted-foreground">Product name</span>
+ <input value={name} onChange={(e) => setName(e.target.value)} onBlur={() => name !== product.name && saveField({ name })} className={inputCls} required />
+ </label>
+ <label className="block space-y-1.5">
+ <span className="text-[12px] font-medium text-muted-foreground">Description</span>
+ <textarea value={desc} onChange={(e) => setDesc(e.target.value)} onBlur={() => desc !== (product.description ?? "") && saveField({ description: desc })} rows={5} className={areaCls} placeholder="What the product is and who it is for" />
+ </label>
+ </div>
+ </div>
+ </Step>
+ )}
+
+ {product && (
+ <Step n={3} title="Choose a style and start" hint="Pick what looks right for your product.">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
+ {AD_STYLES.map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ aria-pressed={s.id === styleId}
+ onClick={() => {
+ setStyleId(s.id);
+ setPresenter(null);
+ setScript(null);
+ }}
+ className={cn("min-w-0 rounded-xl text-left outline-none focus-visible:ring-2 focus-visible:ring-ring", s.id === styleId && "ring-2 ring-primary ring-offset-2 ring-offset-background")}
+ >
+ <div className="aspect-[9/14] overflow-hidden rounded-xl">
+ <TemplatePreview id={s.id} look={{ scene: styleScene(s.presenter, s.dark), hue: s.hue, hue2: (s.hue + 35) % 360, dark: s.dark }} video />
+ </div>
+ <p className="mt-1.5 truncate text-[13px] font-medium">{s.name}</p>
+ <p className="line-clamp-2 text-[11px] text-muted-foreground">{s.description}</p>
+ </button>
+ ))}
+ </div>
+ <div className="mt-5 grid min-w-0 gap-4 md:grid-cols-2">
+ <div className="space-y-3">
+ <div>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Who&apos;s in it</p>
+ <div role="radiogroup" aria-label="Presenter" className="inline-flex rounded-full bg-muted p-0.5">
+ {[true, false].map((v) => (
+ <button key={String(v)} role="radio" aria-checked={withPresenter === v} onClick={() => (setPresenter(v), setScript(null))} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", withPresenter === v && "bg-background text-foreground shadow-soft")}>
+ {v ? "A presenter" : "Product only"}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="flex flex-wrap items-center gap-2">
+ {withPresenter && <AvatarSlot value={avatar} onChange={setAvatar} />}
+ <VoiceControl engine={engine} models={models} voice={voice} sample={sample} onVoice={setVoice} onSample={setSample} />
+ </div>
+ <div>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Video quality</p>
+ <div role="radiogroup" aria-label="Video quality" className="inline-flex rounded-full bg-muted p-0.5">
+ {(["480p", "720p"] as const).map((q) => (
+ <button key={q} role="radio" aria-checked={quality === q} onClick={() => setQuality(q)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", quality === q && "bg-background text-foreground shadow-soft")}>
+ {q === "480p" ? "Standard" : "High"}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ <div className="min-w-0 space-y-2">
+ <div className="flex items-center justify-between gap-2">
+ <div role="radiogroup" aria-label="Script mode" className="inline-flex rounded-full bg-muted p-0.5">
+ {(["auto", "custom"] as const).map((m) => (
+ <button key={m} role="radio" aria-checked={mode === m} onClick={() => setMode(m)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", mode === m && "bg-background text-foreground shadow-soft")}>
+ {m === "auto" ? "Auto-generate" : "Custom script"}
+ </button>
+ ))}
+ </div>
+ <Button variant="ghost" size="sm" onClick={() => void writeScript()} disabled={writing}>
+ {writing ? <Loader2 className="animate-spin" /> : script ? <RefreshCw /> : <PenLine />} {script ? "Rewrite" : "Write script"}
+ </Button>
+ </div>
+ {mode === "custom" && (
+ <textarea value={instructions} onChange={(e) => (setInstructions(e.target.value), setScript(null))} rows={2} className={areaCls} placeholder="Add specific instructions, e.g. highlight eco-friendly materials, mention free shipping" aria-label="Script instructions" />
+ )}
+ {script !== null ? (
+ <textarea value={script} onChange={(e) => setScript(e.target.value)} rows={4} className={areaCls} aria-label="Voiceover script" />
+ ) : (
+ <p className="rounded-xl bg-muted/60 px-3 py-2.5 text-[13px] text-muted-foreground">The voiceover is written when you generate — or press Write script to read and edit it first.</p>
+ )}
+ </div>
+ </div>
+ <div className="mt-6 flex flex-wrap items-center justify-end gap-3 border-t pt-4">
+ <p className="mr-auto text-[12px] text-muted-foreground">9:16 · up to 12 s · voiceover and captions{est.data?.steps.length ? ` · ${est.data.steps.length} steps` : ""}</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" /> : <Wand2 />} Generate video
+ </Button>
+ </div>
+ {blocker && product && <p className="mt-2 text-right text-[12px] text-muted-foreground">{blocker}</p>}
+ </Step>
+ )}
+
+ <div ref={resultsRef} className="scroll-mt-28 pt-6">
+ <h2 className="mb-4 font-heading text-[24px]">Your video ads</h2>
+ <RunsList
+ feature="click-to-ad"
+ empty={
+ <div className="rounded-2xl border border-dashed py-12 text-center">
+ <EmptyIcon icon={product ? Clapperboard : MousePointerClick} />
+ <p className="mt-4 text-[14px] text-muted-foreground">{product ? "Pick a style and press Generate video." : "Start with a product link above."}</p>
+ </div>
+ }
+ />
+ </div>
+ <p className="flex items-center justify-center gap-1.5 pt-4 text-[12px] text-subtle-foreground">
+ <Sparkles className="size-3" /> Cloud: Seedance 2.5 shots or an OmniHuman presenter, ElevenLabs voice, Auto Subtitle · Open source: Wan 2.2, InfiniteTalk, Chatterbox (your voice sample), caption burn-in
+ </p>
+ </main>
+ </div>
+ );
+}
diff --git a/src/components/marketing/hooks.ts b/src/components/marketing/hooks.ts
new file mode 100644
index 00000000..b411b42e
--- /dev/null
+++ b/src/components/marketing/hooks.ts
@@ -0,0 +1,282 @@
+"use client";
+
+import { keepPreviousData, useMutation, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { useEffect, useRef, useState } from "react";
+import { useGenerationEvents, useStatus } from "@/lib/api";
+import type { AdCreative, BrandKit, BrandKitFields, MarketingRun, Product, RunEstimate, RunFeature } from "@/lib/catalog/marketing";
+import type { Generation } from "@/lib/catalog/types";
+
+/**
+ * React Query hooks for /api/brands, /api/products, /api/marketing and /api/ads (kept next to the
+ * marketing views that use them). Runs and creatives update live from the shared generation stream.
+ */
+
+async function json<T>(res: Response): Promise<T> {
+ if (res.status === 204) return undefined as T;
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
+ if (!res.ok) throw Object.assign(new Error(body.error ?? `Request failed (${res.status})`), { status: res.status });
+ return body;
+}
+
+export const send = async <T,>(url: string, method: string, body?: unknown) =>
+ json<T>(await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) }));
+
+const active = (g: Generation) => g.status === "queued" || g.status === "running";
+
+// ---------------------------------------------------------------------------
+// Brands
+
+export function useBrands() {
+ return useQuery({
+ queryKey: ["brands"],
+ queryFn: async () => (await json<{ items: BrandKit[] }>(await fetch("/api/brands"))).items,
+ staleTime: 5_000,
+ refetchInterval: (q) => (q.state.data?.some((b) => b.status === "researching") ? 1500 : false),
+ });
+}
+
+export interface BrandView {
+ brand: BrandKit;
+ products: Product[];
+}
+
+export function useBrand(id: string | null | undefined) {
+ return useQuery({
+ queryKey: ["brands", id],
+ enabled: !!id,
+ queryFn: async () => json<BrandView>(await fetch(`/api/brands/${id}`)),
+ retry: (n, e) => (e as { status?: number }).status !== 404 && n < 1,
+ refetchInterval: (q) => (q.state.data?.brand.status === "researching" ? 900 : false),
+ });
+}
+
+function invalidateBrands(qc: QueryClient) {
+ void qc.invalidateQueries({ queryKey: ["brands"] });
+ void qc.invalidateQueries({ queryKey: ["products"] });
+}
+
+export function useCreateBrand() {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (body: { website: string } | { description: string; name?: string; images?: string[]; colors?: string[] }) => send<BrandKit>("/api/brands", "POST", body),
+ onSuccess: () => invalidateBrands(qc),
+ });
+}
+
+export function useUpdateBrand(id: string) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (patch: Partial<BrandKitFields>) => send<BrandKit>(`/api/brands/${id}`, "PATCH", patch),
+ onSuccess: (b) => {
+ qc.setQueryData<BrandView>(["brands", id], (old) => (old ? { ...old, brand: b } : old));
+ void qc.invalidateQueries({ queryKey: ["brands"], exact: true });
+ },
+ });
+}
+
+export function useBrandActions(id: string) {
+ const qc = useQueryClient();
+ const done = () => invalidateBrands(qc);
+ return {
+ retry: useMutation({ mutationFn: () => send<BrandKit>(`/api/brands/${id}/research`, "POST"), onSuccess: done }),
+ cancel: useMutation({ mutationFn: () => send<BrandKit>(`/api/brands/${id}/research`, "DELETE"), onSuccess: done }),
+ remove: useMutation({ mutationFn: () => send<void>(`/api/brands/${id}`, "DELETE"), onSuccess: done }),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Products
+
+/** All products (`brandId` undefined), a brand's, or the unassigned ones (null). */
+export function useProducts(brandId?: string | null) {
+ const q = brandId === undefined ? "" : `?brand=${brandId ?? "none"}`;
+ return useQuery({
+ queryKey: ["products", brandId ?? (brandId === null ? "none" : "all")],
+ queryFn: async () => (await json<{ items: Product[] }>(await fetch(`/api/products${q}`))).items,
+ staleTime: 5_000,
+ });
+}
+
+export type ProductInput = Partial<Omit<Product, "id" | "createdAt" | "updatedAt">> & { name?: string };
+
+export function useProductActions() {
+ const qc = useQueryClient();
+ const done = () => {
+ void qc.invalidateQueries({ queryKey: ["products"] });
+ void qc.invalidateQueries({ queryKey: ["brands"] });
+ };
+ return {
+ create: useMutation({ mutationFn: (p: ProductInput & { force?: boolean }) => send<Product>("/api/products", "POST", p), onSuccess: done }),
+ update: useMutation({ mutationFn: ({ id, ...p }: ProductInput & { id: string }) => send<Product>(`/api/products/${id}`, "PATCH", p), onSuccess: done }),
+ remove: useMutation({ mutationFn: (id: string) => send<void>(`/api/products/${id}`, "DELETE"), onSuccess: done }),
+ read: useMutation({
+ mutationFn: (b: { url: string; brandId?: string | null; limit?: number; withBrand?: boolean }) =>
+ send<{ products: Product[]; found: number; duplicate?: Product; message?: string; brand: { name?: string; logo?: string; colors: string[]; fonts: { heading?: string; body?: string } } }>("/api/products/read", "POST", b),
+ onSuccess: done,
+ }),
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Runs (Marketing Studio, Click to Ad, Ad Multiplier)
+
+function patchRuns(runs: MarketingRun[] | undefined, g: Generation): MarketingRun[] | undefined {
+ if (!runs) return runs;
+ let changed = false;
+ const next = runs.map((r) => {
+ if (r.batchId !== g.batchId) return r;
+ const i = r.generations.findIndex((x) => x.id === g.id);
+ if (i >= 0 && r.generations[i].updatedAt > g.updatedAt) return r;
+ changed = true;
+ const generations = i >= 0 ? r.generations.map((x) => (x.id === g.id ? g : x)) : [...r.generations, g];
+ return { ...r, generations };
+ });
+ return changed ? next : runs;
+}
+
+/** Runs of one flow, live: stream events patch the steps in place; polling is the safety net. */
+export function useRuns(feature: RunFeature) {
+ const qc = useQueryClient();
+ const key = ["marketing-runs", feature];
+ const connected = useGenerationEvents((ev) => {
+ if (ev.type !== "generation" || !ev.generation.feature.startsWith(feature)) return;
+ const old = qc.getQueryData<MarketingRun[]>(key);
+ const next = patchRuns(old, ev.generation);
+ if (next !== old) qc.setQueryData(key, next);
+ });
+ return useQuery({
+ queryKey: key,
+ queryFn: async () => (await json<{ items: MarketingRun[] }>(await fetch(`/api/marketing/runs?feature=${feature}`))).items,
+ refetchInterval: (q) => (q.state.data?.some((r) => r.generations.some(active)) ? (connected ? 10_000 : 1500) : false),
+ });
+}
+
+export function useForgetRun(feature: RunFeature) {
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (id: string) => send<void>(`/api/marketing/runs/${id}`, "DELETE"),
+ onMutate: (id) => qc.setQueryData<MarketingRun[]>(["marketing-runs", feature], (old) => old?.filter((r) => r.id !== id)),
+ });
+}
+
+/** Put freshly made runs at the top of their list right away. */
+export function addRuns(qc: QueryClient, feature: RunFeature, runs: MarketingRun[]) {
+ qc.setQueryData<MarketingRun[]>(["marketing-runs", feature], (old) => [...runs, ...(old ?? []).filter((r) => !runs.some((x) => x.id === r.id))]);
+ void qc.invalidateQueries({ queryKey: ["marketing-runs", feature] });
+}
+
+/**
+ * A live estimate for a form: POSTs the body (debounced) to an estimate endpoint and keeps the
+ * last answer while the next one loads. `null` body = nothing to price yet.
+ */
+export function useEstimate<T = RunEstimate>(url: string, body: unknown | null, delay = 350) {
+ const text = body == null ? null : JSON.stringify(body);
+ const [debounced, setDebounced] = useState(text);
+ const first = useRef(true);
+ useEffect(() => {
+ if (first.current) {
+ first.current = false;
+ setDebounced(text);
+ return;
+ }
+ const t = setTimeout(() => setDebounced(text), delay);
+ return () => clearTimeout(t);
+ }, [text, delay]);
+ return useQuery({
+ queryKey: ["estimate", url, debounced],
+ enabled: debounced != null,
+ queryFn: async () => json<T>(await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: debounced! })),
+ placeholderData: keepPreviousData,
+ staleTime: 15_000,
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Ads Studio
+
+export function useCreatives(brandId: string | undefined) {
+ const qc = useQueryClient();
+ const key = ["ads", brandId];
+ const connected = useGenerationEvents((ev) => {
+ if (ev.type !== "generation" || ev.generation.feature !== "ads") return;
+ const list = qc.getQueryData<AdCreative[]>(key);
+ if (list?.some((c) => c.generationId === ev.generation.id)) void qc.invalidateQueries({ queryKey: key });
+ });
+ return useQuery({
+ queryKey: key,
+ enabled: !!brandId,
+ queryFn: async () => (await json<{ items: AdCreative[] }>(await fetch(`/api/ads/creatives?brand=${brandId}`))).items,
+ refetchInterval: (q) => {
+ const items = q.state.data;
+ if (!items?.some((c) => c.status === "writing" || c.status === "queued" || c.status === "rendering")) return false;
+ return items.some((c) => c.status === "writing") || !connected ? 1500 : 8000;
+ },
+ });
+}
+
+export function useCreativeActions(brandId: string) {
+ const qc = useQueryClient();
+ const key = ["ads", brandId];
+ const done = () => void qc.invalidateQueries({ queryKey: key });
+ return {
+ update: useMutation({
+ mutationFn: ({ id, ...patch }: { id: string; headline?: string; body?: string; cta?: string; layout?: string | null }) => send<AdCreative>(`/api/ads/creatives/${id}`, "PATCH", patch),
+ onSuccess: (c) => qc.setQueryData<AdCreative[]>(key, (old) => old?.map((x) => (x.id === c.id ? c : x))),
+ }),
+ remove: useMutation({
+ mutationFn: (id: string) => send<void>(`/api/ads/creatives/${id}`, "DELETE"),
+ onMutate: (id) => qc.setQueryData<AdCreative[]>(key, (old) => old?.filter((x) => x.id !== id)),
+ onSettled: done,
+ }),
+ retry: useMutation({ mutationFn: (id: string) => send<AdCreative>(`/api/ads/creatives/${id}/retry`, "POST"), onSuccess: done }),
+ save: useMutation({ mutationFn: ({ id, url, ratio }: { id: string; url: string; ratio: string }) => send<{ generation: Generation }>(`/api/ads/creatives/${id}/save`, "POST", { url, ratio }) }),
+ createBatch: useMutation({
+ mutationFn: (body: { brandId: string; engine: "cloud" | "open"; route?: "fuobe" | "higgsfield"; items: { productId: string; count: number }[]; direction?: string; ratio?: string }) =>
+ send<{ batchId: string; creatives: AdCreative[] }>("/api/ads/batches", "POST", body),
+ onSuccess: (r) => {
+ qc.setQueryData<AdCreative[]>(key, (old) => [...r.creatives, ...(old ?? [])]);
+ done();
+ void qc.invalidateQueries({ queryKey: ["brands"] });
+ },
+ }),
+ };
+}
+
+export interface ChatMessage {
+ id: string;
+ role: "user" | "assistant";
+ text: string;
+ at: number;
+ proposal?: { items: { productId: string; count: number }[]; direction?: string } | null;
+ batchId?: string;
+}
+
+export function useBrandChat(brandId: string) {
+ const qc = useQueryClient();
+ const key = ["brand-chat", brandId];
+ const query = useQuery({ queryKey: key, queryFn: async () => (await json<{ messages: ChatMessage[] }>(await fetch(`/api/brands/${brandId}/chat`))).messages });
+ const set = (m: ChatMessage[]) => qc.setQueryData(key, m);
+ return {
+ query,
+ say: useMutation({
+ mutationFn: (text: string) => send<{ messages: ChatMessage[] }>(`/api/brands/${brandId}/chat`, "POST", { text }),
+ onMutate: (text) => set([...(qc.getQueryData<ChatMessage[]>(key) ?? []), { id: `tmp-${Date.now()}`, role: "user", text, at: Date.now() }]),
+ onSuccess: (r) => set(r.messages),
+ onError: () => void qc.invalidateQueries({ queryKey: key }),
+ }),
+ confirm: useMutation({
+ mutationFn: (b: { messageId: string; engine: "cloud" | "open"; route?: "fuobe" | "higgsfield" }) => send<{ batchId: string; messages: ChatMessage[] }>(`/api/brands/${brandId}/chat/confirm`, "POST", b),
+ onSuccess: (r) => {
+ set(r.messages);
+ void qc.invalidateQueries({ queryKey: ["ads", brandId] });
+ },
+ }),
+ clear: useMutation({ mutationFn: () => send<void>(`/api/brands/${brandId}/chat`, "DELETE"), onSuccess: () => set([]) }),
+ };
+}
+
+/** What's connected, for picking routes in the UI (Higgsfield's own Ads Studio / Seedance edit). */
+export function useStatusFlags() {
+ const s = useStatus().data;
+ return { higgsfield: !!s?.providers.higgsfield?.configured, demoMode: s?.demoMode };
+}
diff --git a/src/components/marketing/marketing-studio.tsx b/src/components/marketing/marketing-studio.tsx
new file mode 100644
index 00000000..e4dd399e
--- /dev/null
+++ b/src/components/marketing/marketing-studio.tsx
@@ -0,0 +1,453 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { ArrowUp, ChevronDown, Image as ImageIcon, LayoutTemplate, Loader2, SlidersHorizontal, Type, Video, X } from "lucide-react";
+import { useSearchParams } from "next/navigation";
+import { Suspense, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
+import { toast } from "sonner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { chipBase, chipIdle, chipOn } from "@/components/studio/chip";
+import { MediaSlot, type SlotValue } from "@/components/studio/media-slot";
+import { ResponsivePanel } from "@/components/studio/responsive-panel";
+import { BrandChip } from "@/components/brand/brand-dialog";
+import { inputCls } from "@/components/brand/fields";
+import { FORMATS, formatModels, MAX_PROMPT, TEMPLATE_INDEX, type FormatId, type MarketingCategory, type MarketingTemplate, type RunEstimate } from "@/lib/catalog/marketing";
+import { formatCost } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { addRuns, send, useBrands, useEstimate, useStatusFlags } from "./hooks";
+import type { MarketingRun } from "@/lib/catalog/marketing";
+import type { ModelInfo } from "./model-info";
+import { AvatarSlot, HookPicker, ProductSlot, SettingPicker, VoiceControl, type ProductChoice } from "./pickers";
+import { RunsList } from "./runs";
+import { EmptyIcon, MarketingHeader, useMarketingEngine } from "./shell";
+import { TemplateGallery, type MediaFilter } from "./template-gallery";
+import { TemplatePreview } from "./template-preview";
+
+const IMAGE_FORMATS: FormatId[] = ["product-standalone", "product-with-model", "ads", "poster", "marketplace"];
+const VIDEO_FORMATS: FormatId[] = ["motion-hyper", "motion-2d", "motion-mixed", "motion-saas", "ugc-talking", "tiktok"];
+
+interface Draft {
+ format: FormatId;
+ templateId: string | null;
+ product: ProductChoice | null;
+ avatar: SlotValue | null;
+ reference: SlotValue | null;
+ hookId: string | null;
+ settingId: string | null;
+ prompt: string;
+ headline: string;
+ cta: string;
+ aspectRatio: string;
+ duration?: number;
+ batch: number;
+ modelId?: string;
+ voice?: string;
+ voiceSample: SlotValue | null;
+}
+
+const BLANK: Draft = { format: "product-standalone", templateId: null, product: null, avatar: null, reference: null, hookId: null, settingId: null, prompt: "", headline: "", cta: "", aspectRatio: "3:4", batch: 1, voiceSample: null };
+
+const BRAND_KEY = "fuobe:marketing-brand";
+const brandListeners = new Set<() => void>();
+const readBrand = () => {
+ try {
+ return localStorage.getItem(BRAND_KEY);
+ } catch {
+ return null;
+ }
+};
+
+/** The brand kit picked last time (kept in this browser), and a setter that remembers the choice. */
+function useSavedBrand(): [string | null, (id: string | null) => void] {
+ const id = useSyncExternalStore(
+ (cb) => {
+ brandListeners.add(cb);
+ return () => brandListeners.delete(cb);
+ },
+ readBrand,
+ () => null,
+ );
+ const save = (next: string | null) => {
+ try {
+ if (next) localStorage.setItem(BRAND_KEY, next);
+ else localStorage.removeItem(BRAND_KEY);
+ } catch {}
+ brandListeners.forEach((l) => l());
+ };
+ return [id, save];
+}
+
+function withTemplate(d: Draft, t: MarketingTemplate | null, format?: FormatId): Draft {
+ const f = FORMATS[t?.format ?? format ?? d.format];
+ return {
+ ...d,
+ format: f.id,
+ templateId: t?.id ?? null,
+ aspectRatio: f.aspectRatios.includes(t?.aspect ?? d.aspectRatio) ? (t?.aspect ?? d.aspectRatio) : f.defaultAspect,
+ duration: f.durations ? (t?.duration ?? f.durations.default) : undefined,
+ batch: Math.min(d.batch, f.batch),
+ hookId: f.hookAndSetting ? (t?.hook ?? null) : null,
+ settingId: f.hookAndSetting ? (t?.setting ?? d.settingId) : null,
+ headline: "",
+ cta: "",
+ modelId: undefined,
+ avatar: f.avatar === "none" ? null : d.avatar,
+ };
+}
+
+function SettingsPanel({ draft, set, models, higgsfield, engine }: { draft: Draft; set: (p: Partial<Draft>) => void; models: Record<string, ModelInfo>; higgsfield: boolean; engine: "cloud" | "open" }) {
+ const [open, setOpen] = useState(false);
+ const f = FORMATS[draft.format];
+ const choices = formatModels(f, engine, { product: !!draft.product, avatar: !!draft.avatar, higgsfield });
+ const model = choices.find((c) => c.id === draft.modelId) ?? choices[0];
+ const summary = [draft.aspectRatio, f.durations && `${draft.duration}s`, draft.batch > 1 && `×${draft.batch}`].filter(Boolean).join(" · ");
+ const seg = (active: boolean) => cn("h-7 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground", active && "bg-background text-foreground shadow-soft");
+ return (
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="Settings"
+ tooltip="Aspect ratio, length, batch and model"
+ trigger={
+ <button type="button" className={cn(chipBase, chipIdle)} aria-label={`Settings: ${summary}`}>
+ <SlidersHorizontal className="size-3.5" />
+ <span className="hidden sm:inline">{summary}</span>
+ </button>
+ }
+ >
+ <div className="space-y-4">
+ <div>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Aspect ratio</p>
+ <div role="radiogroup" aria-label="Aspect ratio" className="flex flex-wrap gap-1 rounded-2xl bg-muted p-0.5">
+ {f.aspectRatios.map((a) => (
+ <button key={a} role="radio" aria-checked={draft.aspectRatio === a} onClick={() => set({ aspectRatio: a })} className={seg(draft.aspectRatio === a)}>
+ {a}
+ </button>
+ ))}
+ </div>
+ </div>
+ {f.durations && (
+ <div>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Length · {draft.duration}s</p>
+ <input type="range" min={f.durations.min} max={f.durations.max} step={1} value={draft.duration ?? f.durations.default} onChange={(e) => set({ duration: Number(e.target.value) })} aria-label="Length in seconds" className="w-full accent-[var(--primary)]" />
+ <p className="mt-0.5 flex justify-between text-[11px] text-subtle-foreground">
+ <span>{f.durations.min}s</span>
+ <span>{f.durations.max}s</span>
+ </p>
+ </div>
+ )}
+ {f.batch > 1 && (
+ <div>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">{f.kind === "video" ? "Versions" : "Images"}</p>
+ <div role="radiogroup" aria-label="Batch size" className="inline-flex rounded-full bg-muted p-0.5">
+ {Array.from({ length: f.batch }, (_, i) => i + 1).map((n) => (
+ <button key={n} role="radio" aria-checked={draft.batch === n} onClick={() => set({ batch: n })} className={seg(draft.batch === n)}>
+ ×{n}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ <div>
+ <p className="mb-1.5 text-[12px] font-medium text-muted-foreground">Model</p>
+ <div className="space-y-1">
+ {choices.map((c) => (
+ <button key={c.id} type="button" onClick={() => set({ modelId: c.id })} className={cn("w-full rounded-lg px-2.5 py-1.5 text-left hover:bg-accent", model.id === c.id && "bg-brand-faint")}>
+ <span className={cn("block text-[13px] font-medium", model.id === c.id && "text-brand-text")}>{models[c.id]?.name ?? c.id}</span>
+ <span className="block text-[11px] text-muted-foreground">{c.note ?? models[c.id]?.tagline}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ </ResponsivePanel>
+ );
+}
+
+function TextPanel({ draft, set, template }: { draft: Draft; set: (p: Partial<Draft>) => void; template?: MarketingTemplate }) {
+ const [open, setOpen] = useState(false);
+ const has = draft.headline || draft.cta;
+ return (
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="Words on the image"
+ description="Set exactly, letter for letter: cloud models draw them; open-source results get them set on top in your brand fonts."
+ trigger={
+ <button type="button" className={cn(chipBase, has ? chipOn : chipIdle, "max-w-44")} aria-label="Headline and button text">
+ <Type className="size-3.5" />
+ <span className="truncate">{draft.headline || template?.headline?.replace(/\{\w+\}/g, "…") || "Headline"}</span>
+ </button>
+ }
+ >
+ <div className="space-y-3">
+ <label className="block space-y-1.5">
+ <span className="text-[12px] font-medium text-muted-foreground">Headline</span>
+ <input value={draft.headline} onChange={(e) => set({ headline: e.target.value })} maxLength={140} placeholder={template?.headline?.replace("{product}", "your product").replace("{brand}", "your brand") ?? "e.g. Crunch, sorted"} className={inputCls} />
+ </label>
+ <label className="block space-y-1.5">
+ <span className="text-[12px] font-medium text-muted-foreground">Button</span>
+ <input value={draft.cta} onChange={(e) => set({ cta: e.target.value })} maxLength={40} placeholder={template?.cta ?? "e.g. Shop now"} className={inputCls} />
+ </label>
+ </div>
+ </ResponsivePanel>
+ );
+}
+
+function FormatChip({ draft, onFormat }: { draft: Draft; onFormat: (f: FormatId) => void }) {
+ const [open, setOpen] = useState(false);
+ const f = FORMATS[draft.format];
+ const list = f.kind === "video" ? VIDEO_FORMATS : IMAGE_FORMATS;
+ return (
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="Format"
+ trigger={
+ <button type="button" className={cn(chipBase, chipIdle)} aria-label={`Format: ${f.cardLabel} · ${f.name}`}>
+ <LayoutTemplate className="size-3.5" />
+ {f.cardLabel === f.name ? f.name : `${f.cardLabel} · ${f.name}`}
+ <ChevronDown className="size-3 opacity-60" />
+ </button>
+ }
+ >
+ <div className="space-y-1">
+ {list.map((id) => (
+ <button key={id} type="button" onClick={() => (onFormat(id), setOpen(false))} className={cn("w-full rounded-lg px-2.5 py-1.5 text-left text-[13px] hover:bg-accent", id === draft.format && "bg-brand-faint text-brand-text")}>
+ <span className="font-medium">{FORMATS[id].cardLabel}</span>
+ {FORMATS[id].cardLabel !== FORMATS[id].name && <span className="text-muted-foreground"> · {FORMATS[id].name}</span>}
+ </button>
+ ))}
+ </div>
+ </ResponsivePanel>
+ );
+}
+
+function UrlParams({ onTemplate, onTab }: { onTemplate: (t: MarketingTemplate) => void; onTab: (t: "templates" | "generations") => void }) {
+ const q = useSearchParams();
+ const done = useRef(false);
+ useEffect(() => {
+ if (done.current) return;
+ done.current = true;
+ const t = q.get("template");
+ if (t && TEMPLATE_INDEX.get(t)) onTemplate(TEMPLATE_INDEX.get(t)!);
+ if (q.get("tab") === "generations") onTab("generations");
+ }, [q, onTemplate, onTab]);
+ return null;
+}
+
+/** Marketing Studio: pick a template (or a format), add your product, avatar, hook and brand kit, and generate. */
+export function MarketingStudio({ models }: { models: Record<string, ModelInfo> }) {
+ const qc = useQueryClient();
+ const { engine, setEngine } = useMarketingEngine();
+ const { higgsfield } = useStatusFlags();
+ const [tab, setTab] = useState<"templates" | "generations">("templates");
+ const [category, setCategory] = useState<MarketingCategory | "all">("all");
+ const [media, setMedia] = useState<MediaFilter>("all");
+ const [draft, setDraft] = useState<Draft>(BLANK);
+ const [busy, setBusy] = useState(false);
+ const [pulse, setPulse] = useState<string | null>(null);
+ const [focused, setFocused] = useState(false);
+ const prompt = useRef<HTMLTextAreaElement>(null);
+ const set = (p: Partial<Draft>) => setDraft((d) => ({ ...d, ...p }));
+ const f = FORMATS[draft.format];
+ const template = draft.templateId ? TEMPLATE_INDEX.get(draft.templateId) : undefined;
+ const kind = f.kind;
+
+ // The brand kit is remembered between visits (and dropped once it's deleted).
+ const [savedBrand, pickBrand] = useSavedBrand();
+ const brands = useBrands();
+ const brandId = savedBrand && brands.data?.some((b) => b.id === savedBrand) ? savedBrand : null;
+
+ const pickTemplate = (t: MarketingTemplate) => {
+ setDraft((d) => withTemplate(d, t));
+ requestAnimationFrame(() => prompt.current?.focus({ preventScroll: true }));
+ };
+
+ const body = useMemo(
+ () => ({
+ engine,
+ format: draft.format,
+ templateId: draft.templateId ?? undefined,
+ modelId: draft.modelId,
+ productId: draft.product?.productId,
+ productImages: draft.product && !draft.product.productId ? draft.product.images : undefined,
+ avatar: f.avatar !== "none" ? draft.avatar?.ref : undefined,
+ reference: draft.reference?.ref,
+ brandId: f.brandKit ? (brandId ?? undefined) : undefined,
+ hookId: f.hookAndSetting ? draft.hookId : undefined,
+ settingId: f.hookAndSetting ? draft.settingId : undefined,
+ prompt: draft.prompt.trim() || undefined,
+ headline: f.text ? draft.headline.trim() || undefined : undefined,
+ cta: f.text ? draft.cta.trim() || undefined : undefined,
+ aspectRatio: draft.aspectRatio,
+ duration: f.durations ? draft.duration : undefined,
+ batch: draft.batch,
+ voice: draft.voice,
+ voiceSample: draft.voiceSample?.ref,
+ }),
+ [draft, engine, f, brandId],
+ );
+ const est = useEstimate<RunEstimate>("/api/marketing/estimate", draft.avatar?.uploading || draft.voiceSample?.uploading ? null : body);
+ const blocker = draft.product === null && f.product === "required" ? "Attach a product to generate" : est.data?.blocker;
+ const cost = est.data && !est.data.blocker ? (est.data.demo ? "Demo · free" : est.data.costUsd == null ? "" : est.data.costUsd === 0 ? "Free" : `≈ ${formatCost(est.data.costUsd)}`) : "";
+
+ const generate = async () => {
+ if (blocker) {
+ toast(blocker, { id: "marketing-blocker" });
+ setPulse(/product/i.test(blocker) ? "product" : /avatar/i.test(blocker) ? "avatar" : null);
+ setTimeout(() => setPulse(null), 1600);
+ return;
+ }
+ setBusy(true);
+ try {
+ const r = await send<{ runs: MarketingRun[] }>("/api/marketing/runs", "POST", body);
+ addRuns(qc, "marketing", r.runs);
+ setTab("generations");
+ toast.success(r.runs.length > 1 ? `${r.runs.length} runs started` : f.pipeline === "image" ? "Generating" : `Started · ${est.data?.steps.length ?? ""} steps`, { duration: 1600 });
+ set({ prompt: "" });
+ } catch (e) {
+ toast.error((e as Error).message);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const toggleKind = (k: "image" | "video") => {
+ if (k === kind) return;
+ setMedia(k);
+ setDraft((d) => withTemplate(d, null, k === "image" ? "product-standalone" : "motion-hyper"));
+ };
+
+ return (
+ <div className="flex min-h-svh min-w-0 flex-col">
+ <MarketingHeader title="Marketing Studio" active="studio" engine={engine} onEngine={setEngine} />
+ <Suspense fallback={null}>
+ <UrlParams onTemplate={pickTemplate} onTab={setTab} />
+ </Suspense>
+ <main className="mx-auto w-full min-w-0 max-w-[1240px] flex-1 px-3 pb-10 sm:px-6">
+ <div className="pt-6 pb-2 text-center sm:pt-10">
+ <h2 className="font-heading text-display text-balance">Turn a product into ready-to-post content</h2>
+ <p className="mx-auto mt-2 max-w-xl text-[15px] text-muted-foreground">
+ Product shots, motion, UGC presenters, ads, posters and listings — from Fuobe&apos;s templates, on {engine === "open" ? "your own GPU" : "cloud models"}.
+ </p>
+ </div>
+ <div role="tablist" aria-label="View" className="mx-auto mt-4 flex w-fit rounded-full bg-muted p-0.5">
+ {(["templates", "generations"] as const).map((t) => (
+ <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={cn("h-8 rounded-full px-4 text-[13px] font-medium text-muted-foreground", tab === t && "bg-background text-foreground shadow-soft")}>
+ {t === "templates" ? "Templates" : "My generations"}
+ </button>
+ ))}
+ </div>
+ <div className="mt-6">
+ {tab === "templates" ? (
+ <TemplateGallery
+ category={category}
+ onCategory={setCategory}
+ media={media}
+ onMedia={(m) => {
+ setMedia(m);
+ if (m !== "all" && m !== kind) setDraft((d) => withTemplate(d, null, m === "image" ? "product-standalone" : "motion-hyper"));
+ }}
+ selected={draft.templateId ?? undefined}
+ onPick={pickTemplate}
+ />
+ ) : (
+ <RunsList
+ feature="marketing"
+ empty={
+ <div className="mx-auto max-w-md py-16 text-center">
+ <EmptyIcon icon={LayoutTemplate} />
+ <h3 className="mt-5 font-heading text-[24px]">Nothing made yet</h3>
+ <p className="mt-2 text-[14px] text-muted-foreground">Pick a template, add your product and press Generate. Results land here as they render.</p>
+ <button type="button" onClick={() => setTab("templates")} className="mt-5 h-9 rounded-full bg-primary px-4 text-[13px] font-medium text-primary-foreground">
+ Browse templates
+ </button>
+ </div>
+ }
+ />
+ )}
+ </div>
+ </main>
+
+ {/* Docked composer */}
+ <div className="sticky bottom-0 z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-3 pt-8 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6">
+ <div className="mx-auto w-full max-w-[860px] rounded-[20px] border bg-background p-2.5 shadow-normal transition-[border-color,box-shadow] focus-within:border-primary focus-within:ring-4 focus-within:ring-brand-faint sm:rounded-composer">
+ <div className="scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1.5 pb-1">
+ {template && (
+ <div className="relative flex h-14 shrink-0 items-center gap-2 rounded-xl bg-muted py-1 pr-7 pl-1">
+ <div className="h-12 w-9 overflow-hidden rounded-lg">
+ <TemplatePreview id={template.id} look={template.look} />
+ </div>
+ <div className="min-w-0">
+ <p className="max-w-32 truncate text-[12px] font-medium">{template.name}</p>
+ <p className="text-[11px] text-muted-foreground">{f.cardLabel}</p>
+ </div>
+ <button type="button" onClick={() => setDraft((d) => withTemplate(d, null, d.format))} aria-label="Clear template" className="absolute top-1 right-1 grid size-5 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground">
+ <X className="size-3" />
+ </button>
+ </div>
+ )}
+ {f.product !== "none" && <ProductSlot value={draft.product} onChange={(p) => set({ product: p })} required={f.product === "required"} brandId={brandId} pulse={pulse === "product"} />}
+ {f.avatar !== "none" && <AvatarSlot value={draft.avatar} onChange={(a) => set({ avatar: a })} pulse={pulse === "avatar"} />}
+ {f.pipeline !== "ugc" && <MediaSlot label="Reference" kind="image" value={draft.reference} onChange={(v) => set({ reference: v })} />}
+ </div>
+ <textarea
+ ref={prompt}
+ value={draft.prompt}
+ onChange={(e) => set({ prompt: e.target.value })}
+ onFocus={() => setFocused(true)}
+ onBlur={() => setFocused(false)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ void generate();
+ }
+ }}
+ maxLength={MAX_PROMPT}
+ rows={focused || draft.prompt ? 2 : 1}
+ placeholder={template ? (f.text ? "Describe your edit (optional)" : "What should look different? (optional)") : f.promptPlaceholder}
+ aria-label="Prompt"
+ className="field-sizing-content max-h-40 min-h-9 w-full resize-none bg-transparent px-2 py-1.5 text-[15px] outline-none placeholder:text-subtle-foreground"
+ />
+ <div className="flex min-w-0 items-center gap-1.5">
+ <div className="scrollbar-none flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto">
+ <div role="radiogroup" aria-label="Mode" className="inline-flex shrink-0 rounded-full bg-muted p-0.5">
+ {(["image", "video"] as const).map((k) => (
+ <button key={k} role="radio" aria-checked={kind === k} onClick={() => toggleKind(k)} aria-label={k === "image" ? "Image mode" : "Video mode"} className={cn("inline-flex h-7 items-center gap-1 rounded-full px-2.5 text-[12px] font-medium text-muted-foreground", kind === k && "bg-background text-foreground shadow-soft")}>
+ {k === "image" ? <ImageIcon className="size-3.5" /> : <Video className="size-3.5" />}
+ <span className="hidden sm:inline">{k === "image" ? "Image" : "Video"}</span>
+ </button>
+ ))}
+ </div>
+ {!template && <FormatChip draft={draft} onFormat={(id) => setDraft((d) => withTemplate(d, null, id))} />}
+ {f.hookAndSetting && <HookPicker value={draft.hookId} onChange={(h) => set({ hookId: h })} />}
+ {f.hookAndSetting && <SettingPicker value={draft.settingId} onChange={(s) => set({ settingId: s })} />}
+ {f.pipeline === "ugc" && <VoiceControl engine={engine} models={models} voice={draft.voice} sample={draft.voiceSample} onVoice={(v) => set({ voice: v })} onSample={(s) => set({ voiceSample: s })} />}
+ {f.text && <TextPanel draft={draft} set={set} template={template} />}
+ {f.brandKit && <BrandChip value={brandId} onChange={pickBrand} />}
+ <SettingsPanel draft={draft} set={set} models={models} higgsfield={higgsfield} engine={engine} />
+ </div>
+ <span className="hidden shrink-0 font-mono text-[12px] text-muted-foreground tabular-nums sm:inline">{est.isFetching && !est.data ? "…" : cost}</span>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ onClick={() => void generate()}
+ aria-label={template ? "Recreate template" : "Generate"}
+ aria-disabled={!!blocker || busy}
+ className={cn("grid size-10 shrink-0 place-items-center rounded-full transition-colors", blocker ? "bg-muted text-subtle-foreground" : "bg-primary text-primary-foreground hover:bg-primary/90")}
+ >
+ {busy ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent>{blocker ?? (template ? `Recreate template${cost ? ` · ${cost}` : ""}` : `Generate${cost ? ` · ${cost}` : ""}`)}</TooltipContent>
+ </Tooltip>
+ </div>
+ {est.data?.notes.length && !blocker ? <p className="truncate px-2 pt-1 text-[11px] text-muted-foreground">{est.data.notes[0]}</p> : null}
+ {blocker && <p className="px-2 pt-1 text-[11px] text-muted-foreground sm:hidden">{blocker}</p>}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/marketing/model-info.ts b/src/components/marketing/model-info.ts
new file mode 100644
index 00000000..e96bff97
--- /dev/null
+++ b/src/components/marketing/model-info.ts
@@ -0,0 +1,46 @@
+import { getModel } from "@/lib/catalog";
+import { FORMATS, formatModels, MULTIPLIER_MODELS, UGC_MODELS, type FormatId } from "@/lib/catalog/marketing";
+import type { Engine, ModelDef } from "@/lib/catalog/types";
+
+/**
+ * Slim model facts for the marketing pages, computed on the server (pages pass them as props), so
+ * the browser never loads the model catalog: names, engines, voices and what each takes.
+ */
+
+export interface ModelInfo {
+ id: string;
+ name: string;
+ engine: Engine;
+ tagline: string;
+ voices?: { id: string; name: string; hint?: string }[];
+ voiceClone?: boolean;
+ maxImages?: number;
+}
+
+const slim = (m: ModelDef): ModelInfo => ({
+ id: m.id,
+ name: m.name,
+ engine: m.engine,
+ tagline: m.tagline,
+ ...(m.options.voices?.length && { voices: m.options.voices.map((v) => ({ id: v.id, name: v.name, hint: v.hint })) }),
+ ...(m.options.voiceClone && { voiceClone: true }),
+ ...(m.options.maxImages != null && { maxImages: m.options.maxImages }),
+});
+
+/** Every model a marketing flow can name, by id. */
+export function marketingModelInfo(): Record<string, ModelInfo> {
+ const ids = new Set<string>(["text-llm", "oss-text-llm", "oss-qwen-image", "oss-infinitetalk-long", "ads-studio", "nano-banana-pro", "oss-qwen-edit"]);
+ for (const f of Object.keys(FORMATS) as FormatId[])
+ for (const engine of ["cloud", "open"] as const)
+ for (const has of [{ product: true, avatar: true, higgsfield: true }, { product: false, avatar: false, higgsfield: true }]) for (const c of formatModels(FORMATS[f], engine, has)) ids.add(c.id);
+ for (const engine of ["cloud", "open"] as const) {
+ Object.values(UGC_MODELS[engine]).forEach((id) => ids.add(id));
+ MULTIPLIER_MODELS[engine].forEach((c) => ids.add(c.id));
+ }
+ const out: Record<string, ModelInfo> = {};
+ for (const id of ids) {
+ const m = getModel(id);
+ if (m) out[id] = slim(m);
+ }
+ return out;
+}
diff --git a/src/components/marketing/pickers.tsx b/src/components/marketing/pickers.tsx
new file mode 100644
index 00000000..e83306ec
--- /dev/null
+++ b/src/components/marketing/pickers.tsx
@@ -0,0 +1,298 @@
+"use client";
+
+import { Check, ImagePlus, Loader2, Package, Sparkle, Upload, UserRound, X, Zap } from "lucide-react";
+import { useRef, useState } from "react";
+import { toast } from "sonner";
+import { chipBase, chipIdle, chipOn } from "@/components/studio/chip";
+import { LibraryGrid } from "@/components/studio/media-slot";
+import { ResponsivePanel } from "@/components/studio/responsive-panel";
+import { VoicePicker } from "@/components/studio/audio-controls";
+import type { SlotValue } from "@/components/studio/media-slot";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { AddFromLink, priceText, ProductThumb } from "@/components/brand/products";
+import { uploadImages } from "@/components/brand/image-list";
+import { useElements } from "@/lib/api";
+import { UGC_HOOKS, UGC_SETTINGS, type Product } from "@/lib/catalog/marketing";
+import type { ModelDef } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+import type { ModelInfo } from "./model-info";
+import { useProducts } from "./hooks";
+
+/** The product a run uses: a saved product, or a one-off photo. */
+export interface ProductChoice {
+ productId?: string;
+ name?: string;
+ images: string[];
+}
+
+export const productChoice = (p: Product): ProductChoice => ({ productId: p.id, name: p.name, images: p.images });
+
+const tile = "relative grid size-14 shrink-0 place-items-center overflow-hidden rounded-xl transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring";
+
+/** "Add your product": paste a link, upload a photo, or choose a saved product. */
+export function ProductSlot({ value, onChange, required, brandId, pulse }: { value: ProductChoice | null; onChange: (v: ProductChoice | null) => void; required?: boolean; brandId?: string | null; pulse?: boolean }) {
+ const [open, setOpen] = useState(false);
+ const products = useProducts();
+ const [busy, setBusy] = useState(false);
+ const input = useRef<HTMLInputElement>(null);
+ const list = [...(products.data ?? [])].sort((a, b) => Number(b.brandId === brandId) - Number(a.brandId === brandId));
+ const choose = (v: ProductChoice) => {
+ onChange(v);
+ setOpen(false);
+ };
+ return (
+ <div className="relative shrink-0">
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="Add your product"
+ description="Choose a product image or add a link."
+ tooltip={value ? (value.name ?? "Product photo") : `Product${required ? " · Required" : " · Optional"}`}
+ trigger={
+ <button type="button" data-slot-key="product" className={cn(tile, value ? "bg-muted" : "border border-dashed border-border-strong text-muted-foreground hover:border-primary hover:text-brand-text", pulse && "animate-pulse ring-2 ring-primary")} aria-label={value ? `Product: ${value.name ?? "photo"}. Change product` : "Add product"}>
+ {value?.images[0] ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={value.images[0]} alt="" className="size-full object-cover" />
+ ) : (
+ <span className="flex flex-col items-center gap-0.5 text-[10px] font-medium">
+ <Package className="size-4" />
+ Product
+ </span>
+ )}
+ </button>
+ }
+ >
+ <div className="space-y-4">
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium text-muted-foreground">Paste a link</p>
+ <AddFromLink brandId={brandId} limit={1} onAdded={(ps) => ps[0] && choose(productChoice(ps[0]))} />
+ </div>
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium text-muted-foreground">Upload a photo</p>
+ <button type="button" onClick={() => input.current?.click()} className={cn(chipBase, chipIdle)}>
+ {busy ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />} Upload a photo
+ </button>
+ <input
+ ref={input}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ hidden
+ onChange={async (e) => {
+ const f = [...(e.target.files ?? [])];
+ e.target.value = "";
+ if (!f.length) return;
+ setBusy(true);
+ const urls = await uploadImages(f);
+ setBusy(false);
+ if (urls.length) choose({ images: urls, name: f[0].name.replace(/\.\w+$/, "") });
+ }}
+ />
+ </div>
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium text-muted-foreground">Your products</p>
+ {products.isLoading ? (
+ <Loader2 className="size-4 animate-spin text-muted-foreground" />
+ ) : list.length ? (
+ <div className="grid max-h-64 grid-cols-3 gap-2 overflow-y-auto sm:grid-cols-4">
+ {list.map((p) => (
+ <button key={p.id} type="button" disabled={!p.images.length} onClick={() => choose(productChoice(p))} className={cn("min-w-0 rounded-lg p-1 text-left outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50", value?.productId === p.id && "bg-brand-faint")} title={p.images.length ? p.name : `${p.name} has no images`}>
+ <ProductThumb product={p} className="aspect-square rounded-md" />
+ <span className="mt-1 block truncate text-[11px] font-medium">{p.name}</span>
+ {priceText(p) && <span className="block truncate text-[10px] text-muted-foreground">{priceText(p)}</span>}
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="text-[12px] text-muted-foreground">No products yet — paste a link above, or add them in Ads Studio.</p>
+ )}
+ </div>
+ </div>
+ </ResponsivePanel>
+ {value && (
+ <button type="button" onClick={() => onChange(null)} aria-label="Remove product" className="absolute -top-1.5 -right-1.5 grid size-5 place-items-center rounded-full border bg-background text-muted-foreground shadow-soft hover:text-foreground">
+ <X className="size-3" />
+ </button>
+ )}
+ {required && !value && <span className="pointer-events-none absolute -bottom-1.5 left-1/2 -translate-x-1/2 rounded-full bg-background px-1 text-[9px] font-semibold text-brand-text">Required</span>}
+ </div>
+ );
+}
+
+/** "Choose avatar": one of your characters (Elements), a photo, or your library. */
+export function AvatarSlot({ value, onChange, pulse }: { value: SlotValue | null; onChange: (v: SlotValue | null) => void; pulse?: boolean }) {
+ const [open, setOpen] = useState(false);
+ const elements = useElements();
+ const people = (elements.data ?? []).filter((e) => e.kind === "character" && e.references[0]);
+ const [busy, setBusy] = useState(false);
+ const input = useRef<HTMLInputElement>(null);
+ const choose = (v: SlotValue) => {
+ onChange(v);
+ setOpen(false);
+ };
+ return (
+ <div className="relative shrink-0">
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title="Choose avatar"
+ description="Who presents or wears the product. Leave it empty and a model is made for you."
+ tooltip={value ? (value.name ?? "Avatar") : "Avatar · Optional"}
+ trigger={
+ <button type="button" data-slot-key="avatar" className={cn(tile, value ? "bg-muted" : "border border-dashed border-border-strong text-muted-foreground hover:border-primary hover:text-brand-text", pulse && "animate-pulse ring-2 ring-primary")} aria-label={value ? `Avatar: ${value.name ?? "photo"}. Replace avatar` : "Add avatar"}>
+ {value ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img src={value.preview} alt="" className="size-full object-cover" />
+ ) : (
+ <span className="flex flex-col items-center gap-0.5 text-[10px] font-medium">
+ <UserRound className="size-4" />
+ Avatar
+ </span>
+ )}
+ </button>
+ }
+ >
+ <div className="space-y-4">
+ <button type="button" onClick={() => input.current?.click()} className={cn(chipBase, chipIdle)}>
+ {busy ? <Loader2 className="size-3.5 animate-spin" /> : <ImagePlus className="size-3.5" />} Upload a photo
+ </button>
+ <input
+ ref={input}
+ type="file"
+ accept="image/png,image/jpeg,image/webp"
+ hidden
+ onChange={async (e) => {
+ const f = e.target.files?.[0];
+ e.target.value = "";
+ if (!f) return;
+ setBusy(true);
+ const [url] = await uploadImages([f]);
+ setBusy(false);
+ if (url) choose({ ref: url, preview: url, kind: "image", name: f.name });
+ }}
+ />
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium text-muted-foreground">Your characters</p>
+ {people.length ? (
+ <div className="grid grid-cols-4 gap-2">
+ {people.map((e) => (
+ <button key={e.id} type="button" onClick={() => choose({ ref: e.references[0], preview: e.references[0], kind: "image", name: e.name })} className={cn("min-w-0 rounded-lg p-1 hover:bg-accent", value?.ref === e.references[0] && "bg-brand-faint")}>
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img src={e.references[0]} alt="" className="aspect-square w-full rounded-md object-cover" />
+ <span className="mt-1 block truncate text-[11px]">{e.name}</span>
+ </button>
+ ))}
+ </div>
+ ) : (
+ <p className="text-[12px] text-muted-foreground">Save people you reuse as characters in Elements.</p>
+ )}
+ </div>
+ <div className="space-y-1.5">
+ <p className="text-[12px] font-medium text-muted-foreground">From your library</p>
+ {open && <LibraryGrid kinds={["image"]} onPick={choose} />}
+ </div>
+ </div>
+ </ResponsivePanel>
+ {value && (
+ <button type="button" onClick={() => onChange(null)} aria-label="Remove avatar" className="absolute -top-1.5 -right-1.5 grid size-5 place-items-center rounded-full border bg-background text-muted-foreground shadow-soft hover:text-foreground">
+ <X className="size-3" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+function ListPicker<T extends { id: string; name: string; type: string; prompt: string }>({
+ label,
+ icon: Icon,
+ items,
+ value,
+ onChange,
+ noneLabel,
+ groups,
+}: {
+ label: string;
+ icon: typeof Zap;
+ items: T[];
+ value: string | null;
+ onChange: (id: string | null) => void;
+ noneLabel: string;
+ groups: { type: string; title: string }[];
+}) {
+ const [open, setOpen] = useState(false);
+ const current = items.find((i) => i.id === value);
+ return (
+ <ResponsivePanel
+ open={open}
+ onOpenChange={setOpen}
+ title={`See all ${label.toLowerCase()}s`}
+ trigger={
+ <button type="button" className={cn(chipBase, current ? chipOn : chipIdle)} aria-label={current ? `${label}: ${current.name}` : `${label}: none`}>
+ <Icon className="size-3.5" />
+ {current ? current.name : `No ${label.toLowerCase()}`}
+ </button>
+ }
+ >
+ <div className="space-y-3">
+ <button type="button" onClick={() => (onChange(null), setOpen(false))} className={cn("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-[13px] hover:bg-accent", !value && "bg-brand-faint text-brand-text")}>
+ {noneLabel} {!value && <Check className="size-3.5" />}
+ </button>
+ {groups.map((g) => (
+ <div key={g.type}>
+ <p className="px-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">{g.title}</p>
+ {items
+ .filter((i) => i.type === g.type)
+ .map((i) => (
+ <button key={i.id} type="button" onClick={() => (onChange(i.id), setOpen(false))} className={cn("w-full rounded-lg px-2 py-1.5 text-left hover:bg-accent", i.id === value && "bg-brand-faint")}>
+ <span className={cn("flex items-center justify-between text-[13px] font-medium", i.id === value && "text-brand-text")}>
+ {i.name} {i.id === value && <Check className="size-3.5" />}
+ </span>
+ <span className="line-clamp-2 text-[12px] text-muted-foreground">{i.prompt}</span>
+ </button>
+ ))}
+ </div>
+ ))}
+ </div>
+ </ResponsivePanel>
+ );
+}
+
+export const HookPicker = ({ value, onChange }: { value: string | null; onChange: (id: string | null) => void }) => (
+ <ListPicker label="Hook" icon={Zap} items={UGC_HOOKS} value={value} onChange={onChange} noneLabel="No hook" groups={[{ type: "stunt", title: "Stunts" }, { type: "subtle", title: "Subtle" }]} />
+);
+
+export const SettingPicker = ({ value, onChange }: { value: string | null; onChange: (id: string | null) => void }) => (
+ <ListPicker label="Setting" icon={Sparkle} items={UGC_SETTINGS} value={value} onChange={onChange} noneLabel="No setting" groups={[{ type: "realistic", title: "Realistic" }, { type: "unrealistic", title: "Unrealistic" }]} />
+);
+
+/** The voiceover: a premade cloud voice, or (open source) a sample to clone. */
+export function VoiceControl({ engine, models, voice, sample, onVoice, onSample }: { engine: "cloud" | "open"; models: Record<string, ModelInfo>; voice?: string; sample: SlotValue | null; onVoice: (id?: string) => void; onSample: (v: SlotValue | null) => void }) {
+ const info = models[engine === "open" ? "oss-chatterbox" : "elevenlabs-v4"];
+ if (!info) return null;
+ const model = { id: info.id, name: info.name, options: { voices: info.voices, voiceClone: engine === "open" ? true : info.voiceClone } } as unknown as ModelDef;
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="inline-flex">
+ <VoicePicker
+ model={model}
+ voice={voice}
+ sample={sample}
+ label="Voice"
+ onChange={(c) => {
+ if (!c) return;
+ if (c.kind === "preset") {
+ onVoice(c.id);
+ onSample(null);
+ } else onSample(c.value);
+ }}
+ />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{engine === "open" ? "Open-source voices are cloned from a short sample (Chatterbox)" : `Voiceover by ${info.name}`}</TooltipContent>
+ </Tooltip>
+ );
+}
+
+export function requireToast(msg: string) {
+ toast(msg, { id: "marketing-blocker" });
+}
diff --git a/src/components/marketing/runs.tsx b/src/components/marketing/runs.tsx
new file mode 100644
index 00000000..6ec0d8f4
--- /dev/null
+++ b/src/components/marketing/runs.tsx
@@ -0,0 +1,231 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { AlertCircle, Check, Circle, Download, Loader2, MoreHorizontal, Repeat2, Type, X } from "lucide-react";
+import dynamic from "next/dynamic";
+import { useMemo, useState } from "react";
+import { toast } from "sonner";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { Skeleton } from "@/components/ui/skeleton";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { MediaThumb } from "@/components/studio/result-media";
+import { useGenerationActions } from "@/lib/api";
+import { FORMATS, runStatus, type BrandKit, type MarketingRun, type RunFeature } from "@/lib/catalog/marketing";
+import type { Generation } from "@/lib/catalog/types";
+import { elapsed, formatCost, ratioValue, timeAgo } from "@/lib/format";
+import { cn } from "@/lib/utils";
+import { addRuns, send, useBrands, useForgetRun, useRuns } from "./hooks";
+
+const Viewer = dynamic(() => import("@/components/studio/viewer").then((m) => m.Viewer), { ssr: false });
+const AdEditor = dynamic(() => import("@/components/ads/ad-editor").then((m) => m.AdEditor), { ssr: false });
+
+const active = (g: Generation) => g.status === "queued" || g.status === "running";
+
+function StepChip({ g }: { g: Generation }) {
+ const label = g.request.step?.label ?? g.modelName ?? g.modelId;
+ const icon =
+ g.status === "succeeded" ? (
+ <Check className="size-3 text-success" />
+ ) : g.status === "failed" || g.status === "canceled" ? (
+ <X className="size-3 text-destructive" />
+ ) : g.status === "running" || (g.status === "queued" && !g.message?.startsWith("Waits")) ? (
+ <Loader2 className="size-3 animate-spin text-brand-text" />
+ ) : (
+ <Circle className="size-2.5 text-subtle-foreground" />
+ );
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span tabIndex={0} className={cn("inline-flex h-6 shrink-0 items-center gap-1 rounded-full bg-secondary px-2 text-[11px] font-medium whitespace-nowrap outline-none focus-visible:ring-2 focus-visible:ring-ring", g.status === "failed" && "bg-destructive/10 text-destructive")}>
+ {icon}
+ {label}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-72">
+ {label} · {g.modelName ?? g.modelId}
+ {g.status === "failed" && g.error ? ` — ${g.error}` : g.status === "running" && g.progress != null ? ` — ${Math.round(g.progress * 100)}%` : ""}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+function runRatio(run: MarketingRun, g?: Generation): number {
+ const ar = g?.request.params?.aspectRatio ?? g?.aspectRatio ?? undefined;
+ return ratioValue(ar && ar !== "auto" ? ar : undefined, g?.kind === "video" ? 9 / 16 : 3 / 4);
+}
+
+function RunCard({ run, brand, onOpen, onCompose }: { run: MarketingRun; brand?: BrandKit; onOpen: (g: Generation, i: number) => void; onCompose: (run: MarketingRun) => void }) {
+ const qc = useQueryClient();
+ const forget = useForgetRun(run.feature);
+ const { cancel } = useGenerationActions();
+ const [again, setAgain] = useState(false);
+ const finals = run.generations.filter((g) => run.finalIds.includes(g.id));
+ const final = finals[0];
+ const status = runStatus(run);
+ const steps = run.generations.filter((g) => g.request.step);
+ const outputs = finals.flatMap((g) => (g.status === "succeeded" ? g.outputs.map((o, i) => ({ g, o, i })) : [])).filter((x) => x.o.kind !== "text");
+ const now = steps.find((g) => g.status === "running") ?? steps.find((g) => g.status === "queued" && !g.message?.startsWith("Waits"));
+ const done = steps.filter((g) => g.status === "succeeded").length;
+ const cost = run.generations.reduce((n, g) => n + (g.costUsd ?? 0), 0);
+ const ratio = runRatio(run, final);
+ const format = run.meta.format ? FORMATS[run.meta.format] : null;
+ const canCompose = run.engine === "open" && !!run.meta.overlay && status.state === "done" && outputs.some((x) => x.o.kind === "image");
+ const runAgain = () => {
+ setAgain(true);
+ send<{ runs: MarketingRun[] }>(`/api/marketing/runs/${run.id}/again`, "POST")
+ .then((r) => {
+ addRuns(qc, run.feature, r.runs);
+ toast.success("Started again", { duration: 1500 });
+ })
+ .catch((e) => toast.error((e as Error).message))
+ .finally(() => setAgain(false));
+ };
+ return (
+ <article className="group/run min-w-0 animate-fade-up">
+ <div className="relative">
+ {outputs.length ? (
+ <div className={cn("grid gap-1.5", outputs.length > 1 && "grid-cols-2")}>
+ {outputs.slice(0, 4).map(({ g, o, i }) => (
+ <button key={o.url} onClick={() => onOpen(g, i)} className="relative block overflow-hidden rounded-xl bg-muted outline-none focus-visible:ring-2 focus-visible:ring-ring" style={{ aspectRatio: ratio }} aria-label={`Open ${run.title}`}>
+ <MediaThumb output={o} g={g} />
+ </button>
+ ))}
+ </div>
+ ) : status.state === "failed" || status.state === "canceled" ? (
+ <div className="flex flex-col justify-between rounded-xl border border-dashed bg-background p-3" style={{ aspectRatio: Math.max(ratio, 0.75) }}>
+ <div className="space-y-1">
+ <p className="flex items-center gap-1.5 text-[13px] font-medium">
+ <AlertCircle className="size-3.5 text-destructive" />
+ {status.state === "canceled" ? "Canceled" : status.step ? `${status.step} didn't finish` : "Couldn't make this one"}
+ </p>
+ {status.error && <p className="line-clamp-6 text-[12px] leading-snug break-words text-muted-foreground">{status.error}</p>}
+ </div>
+ <button onClick={runAgain} disabled={again} className="mt-2 inline-flex h-7 w-fit items-center gap-1.5 rounded-full bg-secondary px-2.5 text-[12px] font-medium hover:bg-accent">
+ {again ? <Loader2 className="size-3 animate-spin" /> : <Repeat2 className="size-3" />} Run again
+ </button>
+ </div>
+ ) : (
+ <div className="relative overflow-hidden rounded-xl bg-muted" style={{ aspectRatio: ratio }}>
+ <div className="skeleton-sweep absolute inset-0 animate-skeleton" />
+ <div className="absolute inset-x-0 bottom-0 p-3">
+ <p className="shimmer-text animate-shimmer-text truncate text-[13px] font-medium">{now ? (now.request.step?.label ?? "Generating…") : "In queue"}…</p>
+ <p className="font-mono text-[11px] text-muted-foreground">
+ {steps.length > 1 ? `Step ${Math.min(done + 1, steps.length)} of ${steps.length} · ` : ""}
+ {elapsed(run.createdAt)}
+ </p>
+ </div>
+ {steps.length > 1 && <div className="absolute inset-x-0 top-0 h-0.5 bg-primary/70 transition-[width] duration-500" style={{ width: `${Math.round((done / steps.length) * 100)}%` }} />}
+ </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 transition-opacity hover:bg-black/65 focus-visible:opacity-100 data-[state=open]:opacity-100 sm:opacity-0 sm:group-hover/run:opacity-100" aria-label={`${run.title} actions`}>
+ <MoreHorizontal className="size-4" />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {outputs.map(({ o }, i) => (
+ <DropdownMenuItem key={o.url} asChild>
+ <a href={o.url} download>
+ <Download /> Download{outputs.length > 1 ? ` ${i + 1}` : ""}
+ </a>
+ </DropdownMenuItem>
+ ))}
+ {canCompose && (
+ <DropdownMenuItem onClick={() => onCompose(run)}>
+ <Type /> Set your text
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuItem onClick={runAgain} disabled={again}>
+ <Repeat2 /> Run again
+ </DropdownMenuItem>
+ {run.generations.some(active) && (
+ <DropdownMenuItem onClick={() => run.generations.filter(active).forEach((g) => void cancel(g))}>
+ <X /> Cancel
+ </DropdownMenuItem>
+ )}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onClick={() => forget.mutate(run.id)}>Remove from this list</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ <div className="mt-2 min-w-0 px-0.5">
+ <h3 className="truncate text-[14px] font-medium">{run.title}</h3>
+ <p className="truncate text-[12px] text-muted-foreground">
+ {[format?.cardLabel, run.engine === "open" ? "Open source" : "Cloud", timeAgo(run.createdAt), cost ? formatCost(cost) : "", brand?.name].filter(Boolean).join(" · ")}
+ </p>
+ {canCompose && (
+ <button onClick={() => onCompose(run)} className="mt-1.5 inline-flex h-7 items-center gap-1.5 rounded-full bg-brand-faint px-2.5 text-[12px] font-medium text-brand-text hover:bg-brand-faint-hover">
+ <Type className="size-3" /> Set your text
+ </button>
+ )}
+ {steps.length > 1 && (
+ <div className="scrollbar-none mt-1.5 flex gap-1 overflow-x-auto pb-0.5">
+ {steps.map((g) => (
+ <StepChip key={g.id} g={g} />
+ ))}
+ </div>
+ )}
+ {run.meta.script && status.state !== "running" && <p className="mt-1.5 line-clamp-2 text-[12px] text-muted-foreground italic">“{run.meta.script}”</p>}
+ </div>
+ </article>
+ );
+}
+
+/** A flow's runs, newest first, each with its result, live step chips and actions. */
+export function RunsList({ feature, empty, limit }: { feature: RunFeature; empty?: React.ReactNode; limit?: number }) {
+ const runs = useRuns(feature);
+ const brands = useBrands();
+ const [open, setOpen] = useState<{ id: string; index: number } | null>(null);
+ const [compose, setCompose] = useState<MarketingRun | null>(null);
+ const list = useMemo(() => (limit ? runs.data?.slice(0, limit) : runs.data) ?? [], [runs.data, limit]);
+ const flat = useMemo(() => list.flatMap((r) => r.generations.filter((g) => r.finalIds.includes(g.id) && g.status === "succeeded").flatMap((g) => g.outputs.map((_, i) => ({ g, i })))), [list]);
+ const pos = open ? flat.findIndex((f) => f.g.id === open.id && f.i === open.index) : -1;
+ if (runs.isLoading)
+ return (
+ <div className="grid grid-cols-2 gap-x-4 gap-y-6 md:grid-cols-3 xl:grid-cols-4">
+ {Array.from({ length: 4 }, (_, i) => (
+ <div key={i}>
+ <Skeleton className="aspect-[3/4] rounded-xl" />
+ <Skeleton className="mt-2 h-4 w-2/3" />
+ </div>
+ ))}
+ </div>
+ );
+ if (!list.length) return <>{empty}</>;
+ const composeFinal = compose?.generations.find((g) => compose.finalIds.includes(g.id));
+ const composeBrand = brands.data?.find((b) => b.id === compose?.meta.brandId) ?? null;
+ return (
+ <>
+ <div className="grid grid-cols-2 gap-x-4 gap-y-7 md:grid-cols-3 xl:grid-cols-4">
+ {list.map((r) => (
+ <RunCard key={r.id} run={r} brand={brands.data?.find((b) => b.id === r.meta.brandId)} onOpen={(g, index) => setOpen({ id: g.id, index })} onCompose={setCompose} />
+ ))}
+ </div>
+ {open && pos >= 0 && (
+ <Viewer
+ generation={flat[pos].g}
+ index={flat[pos].i}
+ onIndex={(index) => setOpen({ id: flat[pos].g.id, index })}
+ onClose={() => setOpen(null)}
+ onPrev={pos > 0 ? () => setOpen({ id: flat[pos - 1].g.id, index: flat[pos - 1].i }) : undefined}
+ onNext={pos < flat.length - 1 ? () => setOpen({ id: flat[pos + 1].g.id, index: flat[pos + 1].i }) : undefined}
+ />
+ )}
+ {compose && composeFinal && (
+ <AdEditor
+ open
+ onOpenChange={(o) => !o && setCompose(null)}
+ title={compose.title}
+ image={composeFinal.outputs.find((o) => o.kind === "image")?.url}
+ ratios={[composeFinal.request.params?.aspectRatio && composeFinal.request.params.aspectRatio !== "auto" ? composeFinal.request.params.aspectRatio : "3:4"]}
+ initial={{ headline: compose.meta.overlay?.headline ?? "", body: compose.meta.overlay?.body ?? "", cta: compose.meta.overlay?.cta ?? "", layout: compose.meta.format === "poster" ? "frame" : "overlay" }}
+ brand={composeBrand}
+ onSaveToLibrary={async (url, ratio, text) => {
+ await send(`/api/marketing/runs/${compose.id}/compose`, "POST", { url, ratio, text: [text.headline, text.body, text.cta].filter(Boolean).join(" · ") });
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/src/components/marketing/shell.tsx b/src/components/marketing/shell.tsx
new file mode 100644
index 00000000..ce3225ce
--- /dev/null
+++ b/src/components/marketing/shell.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { Clapperboard, Copy, LayoutTemplate, MousePointerClick, Target } from "lucide-react";
+import Link from "next/link";
+import { SidebarTrigger } from "@/components/ui/sidebar";
+import { EngineSwitch } from "@/components/studio/engine-switch";
+import { useEngine } from "@/lib/api";
+import type { Engine } from "@/lib/catalog/types";
+import { cn } from "@/lib/utils";
+
+export type SuiteTab = "studio" | "click" | "ads" | "multiplier";
+
+const TABS: { id: SuiteTab; href: string; label: string; icon: typeof Target }[] = [
+ { id: "studio", href: "/marketing", label: "Marketing Studio", icon: LayoutTemplate },
+ { id: "click", href: "/marketing/click-to-ad", label: "Click to Ad", icon: MousePointerClick },
+ { id: "ads", href: "/ads", label: "Ads Studio", icon: Target },
+ { id: "multiplier", href: "/ads/multiplier", label: "Ad Multiplier", icon: Copy },
+];
+
+/** The marketing suite's sticky header: title, the four tools as tabs, and the engine switch. */
+export function MarketingHeader({ title, active, engine, onEngine, right }: { title: string; active: SuiteTab; engine?: Engine; onEngine?: (e: Engine) => void; right?: React.ReactNode }) {
+ return (
+ <header className="sticky top-0 z-30 border-b border-transparent bg-background/85 backdrop-blur supports-[backdrop-filter]:bg-background/70">
+ <div className="flex h-14 min-w-0 items-center gap-2 px-3 sm:px-6">
+ <SidebarTrigger className="md:hidden" />
+ <h1 className="min-w-0 truncate font-heading text-[22px] leading-none">{title}</h1>
+ <div className="ml-auto flex shrink-0 items-center gap-2">
+ {right}
+ {engine && onEngine && <EngineSwitch value={engine} onChange={onEngine} />}
+ </div>
+ </div>
+ <nav aria-label="Marketing tools" className="scrollbar-none -mb-px flex gap-1 overflow-x-auto px-3 sm:px-6">
+ {TABS.map((t) => (
+ <Link
+ key={t.id}
+ href={t.href}
+ aria-current={t.id === active ? "page" : undefined}
+ className={cn(
+ "inline-flex h-9 shrink-0 items-center gap-1.5 border-b-2 border-transparent px-2.5 text-[13px] font-medium whitespace-nowrap text-muted-foreground transition-colors hover:text-foreground",
+ t.id === active && "border-primary text-foreground",
+ )}
+ >
+ <t.icon className="size-3.5" />
+ {t.label}
+ </Link>
+ ))}
+ </nav>
+ </header>
+ );
+}
+
+/** The engine for marketing views (shared with every studio: the same switch, the same Settings lock). */
+export function useMarketingEngine() {
+ const [engine, setEngine, mode] = useEngine();
+ return { engine: mode === "both" ? engine : (mode as Engine), setEngine, mode };
+}
+
+export const EmptyIcon = ({ icon: Icon = Clapperboard }: { icon?: typeof Clapperboard }) => (
+ <div className="mx-auto grid size-14 place-items-center rounded-2xl bg-brand-faint text-brand-text">
+ <Icon className="size-6" />
+ </div>
+);
diff --git a/src/components/marketing/template-gallery.tsx b/src/components/marketing/template-gallery.tsx
new file mode 100644
index 00000000..2a6039fb
--- /dev/null
+++ b/src/components/marketing/template-gallery.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import { Play, Search } from "lucide-react";
+import { useDeferredValue, useMemo, useState } from "react";
+import { useEdgeFade } from "@/components/studio/use-edge-fade";
+import { CATEGORIES, FORMATS, interleaved, templatesFor, type MarketingCategory, type MarketingTemplate } from "@/lib/catalog/marketing";
+import { cn } from "@/lib/utils";
+import { TemplatePreview } from "./template-preview";
+
+export type MediaFilter = "all" | "image" | "video";
+
+function TemplateCard({ t, selected, onPick }: { t: MarketingTemplate; selected: boolean; onPick: (t: MarketingTemplate) => void }) {
+ const f = FORMATS[t.format];
+ const video = f.kind === "video";
+ return (
+ <button
+ type="button"
+ onClick={() => onPick(t)}
+ aria-pressed={selected}
+ aria-label={`${t.name} — ${f.cardLabel}${video ? " video" : ""} template`}
+ className={cn("group/tpl min-w-0 rounded-2xl text-left outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2", selected && "ring-2 ring-primary ring-offset-2 ring-offset-background")}
+ >
+ <div className="relative aspect-[3/4] overflow-hidden rounded-2xl bg-muted transition-transform duration-300 ease-move group-hover/tpl:scale-[1.015]">
+ <TemplatePreview id={t.id} look={t.look} video={video} />
+ <span className="absolute top-2 left-2 rounded-full bg-black/45 px-2 py-0.5 text-[11px] font-medium text-white backdrop-blur">{f.cardLabel}</span>
+ {video && (
+ <span className="absolute top-2 right-2 grid size-6 place-items-center rounded-full bg-black/45 text-white backdrop-blur" aria-hidden>
+ <Play className="size-3 fill-current" />
+ </span>
+ )}
+ </div>
+ <p className="mt-2 truncate px-0.5 text-[13px] font-medium">{t.name}</p>
+ </button>
+ );
+}
+
+/** "Explore templates": categories, Images/Videos, search, and the cards. */
+export function TemplateGallery({ category, onCategory, media, onMedia, selected, onPick }: { category: MarketingCategory | "all"; onCategory: (c: MarketingCategory | "all") => void; media: MediaFilter; onMedia: (m: MediaFilter) => void; selected?: string; onPick: (t: MarketingTemplate) => void }) {
+ const [q, setQ] = useState("");
+ const query = useDeferredValue(q.trim().toLowerCase());
+ const [show, setShow] = useState(30);
+ const list = useMemo(() => {
+ const base = templatesFor(category, media);
+ const found = query ? base.filter((t) => `${t.name} ${FORMATS[t.format].cardLabel} ${FORMATS[t.format].name} ${t.prompt}`.toLowerCase().includes(query)) : base;
+ return category === "all" && !query ? interleaved(found) : found;
+ }, [category, media, query]);
+ const [fadeRef, fadeStyle] = useEdgeFade<HTMLDivElement>();
+ return (
+ <section aria-labelledby="explore-templates">
+ <div className="flex flex-wrap items-end justify-between gap-3">
+ <h2 id="explore-templates" className="font-heading text-[24px] leading-tight">
+ Explore templates
+ </h2>
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <label className="relative min-w-0">
+ <Search className="pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search templates" aria-label="Search templates" className="h-8 w-44 rounded-full border bg-background pr-3 pl-8 text-[13px] outline-none focus:border-primary" />
+ </label>
+ <div role="radiogroup" aria-label="Media" className="inline-flex rounded-full bg-muted p-0.5">
+ {(["all", "image", "video"] as const).map((m) => (
+ <button key={m} role="radio" aria-checked={media === m} onClick={() => onMedia(m)} className={cn("h-7 rounded-full px-3 text-[12px] font-medium text-muted-foreground", media === m && "bg-background text-foreground shadow-soft")}>
+ {m === "all" ? "All" : m === "image" ? "Images" : "Videos"}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ <div ref={fadeRef} style={fadeStyle} className="scrollbar-none mt-3 -mx-1 flex gap-1.5 overflow-x-auto px-1 pb-1">
+ {CATEGORIES.map((c) => (
+ <button
+ key={c.id}
+ type="button"
+ aria-pressed={category === c.id}
+ onClick={() => {
+ onCategory(c.id);
+ setShow(30);
+ }}
+ className={cn("inline-flex h-8 shrink-0 items-center rounded-full px-3 text-[13px] font-medium whitespace-nowrap transition-colors", category === c.id ? "bg-foreground text-background" : "bg-secondary text-secondary-foreground hover:bg-accent")}
+ >
+ {c.label}
+ </button>
+ ))}
+ </div>
+ {list.length ? (
+ <>
+ <div className="mt-4 grid grid-cols-2 gap-x-3 gap-y-5 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
+ {list.slice(0, show).map((t) => (
+ <TemplateCard key={t.id} t={t} selected={t.id === selected} onPick={onPick} />
+ ))}
+ </div>
+ {list.length > show && (
+ <div className="mt-6 flex justify-center">
+ <button type="button" onClick={() => setShow((n) => n + 40)} className="h-9 rounded-full bg-secondary px-4 text-[13px] font-medium hover:bg-accent">
+ Show more ({list.length - show})
+ </button>
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="py-16 text-center">
+ <p className="font-heading text-[22px]">No templates match “{q}”</p>
+ <button type="button" onClick={() => setQ("")} className="mt-3 text-[13px] font-medium text-brand-text hover:underline">
+ Clear search
+ </button>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/src/components/marketing/template-preview.tsx b/src/components/marketing/template-preview.tsx
new file mode 100644
index 00000000..393e99cb
--- /dev/null
+++ b/src/components/marketing/template-preview.tsx
@@ -0,0 +1,395 @@
+"use client";
+
+import { memo } from "react";
+import type { PreviewScene, TemplateLook } from "@/lib/catalog/marketing";
+import { cn } from "@/lib/utils";
+
+/**
+ * Procedural template previews: an SVG still per scene (a product silhouette on the template's own
+ * set — plinth, splash, flat lay, a selfie frame, a headline layout…) in the template's colours.
+ * Video templates move on hover or focus (CSS only; nothing moves under reduced motion).
+ */
+
+const CSS = `
+.mkp-float{animation:mkp-float 3.2s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
+.mkp-spin{animation:mkp-spin 6s linear infinite;transform-box:fill-box;transform-origin:center}
+.mkp-pulse{animation:mkp-pulse 1.8s ease-in-out infinite;transform-box:fill-box;transform-origin:center}
+.mkp-slide{animation:mkp-slide 2.6s ease-in-out infinite;transform-box:fill-box}
+.mkp-talk{animation:mkp-talk .5s ease-in-out infinite alternate;transform-box:fill-box;transform-origin:center}
+.mkp [class^="mkp-"]{animation-play-state:paused}
+.mkp[data-video]:hover [class^="mkp-"],.mkp[data-video]:focus-within [class^="mkp-"],button:focus-visible .mkp[data-video] [class^="mkp-"]{animation-play-state:running}
+@keyframes mkp-float{0%,100%{transform:translateY(0) rotate(-3deg)}50%{transform:translateY(-7%) rotate(4deg)}}
+@keyframes mkp-spin{to{transform:rotate(360deg)}}
+@keyframes mkp-pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.12)}}
+@keyframes mkp-slide{0%,100%{transform:translateX(-6%)}50%{transform:translateX(6%)}}
+@keyframes mkp-talk{from{transform:scaleY(.4)}to{transform:scaleY(1)}}
+@media (prefers-reduced-motion:reduce){.mkp [class^="mkp-"]{animation:none!important}}
+`;
+
+/** Trig in SVG attributes is rounded: server and browser engines may print the last digits differently. */
+const r2 = (n: number) => Math.round(n * 100) / 100;
+
+const c = (l: number, ch: number, h: number, a = 1) => `oklch(${l} ${ch} ${h}${a < 1 ? ` / ${a}` : ""})`;
+
+/** Stable 0–n pick from an id. */
+export function pick(id: string, n: number): number {
+ let h = 2166136261;
+ for (const ch of id) h = Math.imul(h ^ ch.charCodeAt(0), 16777619);
+ return Math.abs(h) % n;
+}
+
+type Shape = "bottle" | "jar" | "box" | "can" | "tube";
+const SHAPES: Shape[] = ["bottle", "jar", "box", "can", "tube"];
+
+/** A product silhouette centred at (x, y), `s` tall. */
+function Product({ shape, x, y, s, fill, accent, className }: { shape: Shape; x: number; y: number; s: number; fill: string; accent: string; className?: string }) {
+ const w = s * (shape === "box" ? 0.62 : shape === "can" ? 0.46 : shape === "jar" ? 0.6 : shape === "tube" ? 0.3 : 0.38);
+ const top = y - s / 2;
+ return (
+ <g className={className}>
+ <ellipse cx={x} cy={y + s / 2} rx={w * 0.7} ry={s * 0.05} fill="black" opacity={0.18} />
+ {shape === "bottle" && (
+ <>
+ <rect x={x - w * 0.18} y={top} width={w * 0.36} height={s * 0.16} rx={s * 0.02} fill={accent} />
+ <rect x={x - w / 2} y={top + s * 0.14} width={w} height={s * 0.86} rx={w * 0.28} fill={fill} />
+ </>
+ )}
+ {shape === "jar" && (
+ <>
+ <rect x={x - w / 2} y={top + s * 0.18} width={w} height={s * 0.82} rx={w * 0.16} fill={fill} />
+ <rect x={x - w * 0.46} y={top + s * 0.06} width={w * 0.92} height={s * 0.16} rx={s * 0.03} fill={accent} />
+ </>
+ )}
+ {shape === "box" && <rect x={x - w / 2} y={top + s * 0.1} width={w} height={s * 0.9} rx={s * 0.03} fill={fill} />}
+ {shape === "can" && (
+ <>
+ <rect x={x - w / 2} y={top + s * 0.08} width={w} height={s * 0.92} rx={w * 0.12} fill={fill} />
+ <rect x={x - w / 2} y={top + s * 0.08} width={w} height={s * 0.06} rx={s * 0.02} fill={accent} opacity={0.7} />
+ </>
+ )}
+ {shape === "tube" && (
+ <>
+ <path d={`M${x - w / 2} ${top + s * 0.1} h${w} l${-w * 0.12} ${s * 0.8} h${-w * 0.76} z`} fill={fill} />
+ <rect x={x - w * 0.26} y={top + s * 0.86} width={w * 0.52} height={s * 0.14} rx={s * 0.02} fill={accent} />
+ </>
+ )}
+ {/* label */}
+ <rect x={x - w * 0.32} y={y - s * 0.02} width={w * 0.64} height={s * 0.18} rx={s * 0.015} fill={accent} opacity={0.85} />
+ </g>
+ );
+}
+
+const Person = ({ x, y, s, skin, shirt, className }: { x: number; y: number; s: number; skin: string; shirt: string; className?: string }) => (
+ <g className={className}>
+ <path d={`M${x - s * 0.42} ${y + s} q${s * 0.42} ${-s * 0.7} ${s * 0.84} 0 z`} fill={shirt} />
+ <circle cx={x} cy={y + s * 0.09} r={s * 0.215} fill={c(0.3, 0.04, 40)} />
+ <circle cx={x} cy={y + s * 0.15} r={s * 0.19} fill={skin} />
+ </g>
+);
+
+const Bars = ({ x, y, w, n, color, h = 7, gap = 5 }: { x: number; y: number; w: number; n: number; color: string; h?: number; gap?: number }) => (
+ <g>
+ {Array.from({ length: n }, (_, i) => (
+ <rect key={i} x={x} y={y + i * (h + gap)} width={w * (i === n - 1 ? 0.6 : 1)} height={h} rx={h / 2} fill={color} />
+ ))}
+ </g>
+);
+
+function Scene({ scene, id, look, W, H, video }: { scene: PreviewScene; id: string; look: TemplateLook; W: number; H: number; video: boolean }) {
+ const h1 = look.hue;
+ const h2 = look.hue2 ?? (look.hue + 40) % 360;
+ const dark = !!look.dark;
+ const shape = SHAPES[pick(id, SHAPES.length)];
+ const fill = dark ? c(0.86, 0.05, h1) : c(0.45, 0.13, h1);
+ const accent = dark ? c(0.75, 0.14, h2) : c(0.93, 0.04, h2);
+ const s = H * 0.42;
+ const cx = W / 2;
+ const cy = H * 0.56;
+ const anim = video ? (scene === "orbit" || scene === "burst" ? "mkp-spin" : scene === "kinetic" || scene === "split" ? "mkp-slide" : "mkp-float") : undefined;
+ const prod = (o: Partial<{ x: number; y: number; s: number; className: string }> = {}) => <Product shape={shape} x={o.x ?? cx} y={o.y ?? cy} s={o.s ?? s} fill={fill} accent={accent} className={o.className ?? anim} />;
+ const ink = dark ? c(0.95, 0.01, h1) : c(0.25, 0.05, h1);
+ switch (scene) {
+ case "pedestal":
+ return (
+ <>
+ <path d={`M${cx + W * 0.08} ${cy + s * 0.5} L${W} ${cy + s * 0.3} L${W} ${cy + s * 0.62} Z`} fill="black" opacity={0.12} />
+ <rect x={cx - W * 0.24} y={cy + s * 0.5} width={W * 0.48} height={H * 0.3} rx={6} fill={c(0.86, 0.03, h2)} />
+ <ellipse cx={cx} cy={cy + s * 0.5} rx={W * 0.24} ry={H * 0.025} fill={c(0.92, 0.02, h2)} />
+ {prod({ y: cy - s * 0.02, s: s * 0.95 })}
+ </>
+ );
+ case "flatlay":
+ return (
+ <>
+ <rect x={W * 0.08} y={H * 0.1} width={W * 0.84} height={H * 0.8} rx={10} fill={c(0.93, 0.02, h1)} transform={`rotate(-4 ${cx} ${H / 2})`} />
+ <circle cx={W * 0.25} cy={H * 0.27} r={W * 0.09} fill={c(0.8, 0.06, h2)} />
+ <circle cx={W * 0.78} cy={H * 0.75} r={W * 0.07} fill={c(0.7, 0.1, (h2 + 60) % 360)} />
+ <path d={`M${W * 0.7} ${H * 0.18} q${W * 0.1} ${H * 0.1} 0 ${H * 0.2}`} stroke={c(0.6, 0.12, 140)} strokeWidth={4} fill="none" />
+ {prod({ s: s * 0.8, y: H * 0.52 })}
+ </>
+ );
+ case "splash":
+ case "water":
+ return (
+ <>
+ {[0, 1, 2].map((i) => (
+ <ellipse key={i} cx={cx} cy={cy + s * 0.52} rx={W * (0.2 + i * 0.12)} ry={H * (0.03 + i * 0.012)} fill="none" stroke={c(0.85, 0.08, h2, 0.6 - i * 0.15)} strokeWidth={2.5} />
+ ))}
+ {scene === "splash" &&
+ Array.from({ length: 9 }, (_, i) => {
+ const a = (-160 + i * 17.5) * (Math.PI / 180);
+ return <circle key={i} className={video ? "mkp-pulse" : undefined} cx={r2(cx + Math.cos(a) * W * 0.32)} cy={r2(cy + Math.sin(a) * H * 0.3)} r={3 + (i % 3) * 2.5} fill={c(0.88, 0.08, h2, 0.85)} />;
+ })}
+ {prod()}
+ </>
+ );
+ case "float":
+ return (
+ <>
+ {[-1, 0, 1].map((i) => (
+ <g key={i} transform={`rotate(${i * 14} ${cx + i * W * 0.26} ${cy - Math.abs(i) * H * 0.08})`}>
+ <Product shape={shape} x={cx + i * W * 0.26} y={cy - (1 - Math.abs(i)) * H * 0.08} s={s * 0.62} fill={fill} accent={accent} className={anim} />
+ </g>
+ ))}
+ </>
+ );
+ case "ice":
+ return (
+ <>
+ {Array.from({ length: 10 }, (_, i) => (
+ <rect key={i} x={W * (0.06 + (i % 5) * 0.19)} y={H * (0.72 + Math.floor(i / 5) * 0.1) - (i % 2) * 8} width={W * 0.16} height={W * 0.16} rx={6} fill={c(0.95, 0.03, 220, 0.75)} transform={`rotate(${(i * 23) % 40 - 20} ${W * (0.14 + (i % 5) * 0.19)} ${H * 0.78})`} />
+ ))}
+ {prod({ y: cy - s * 0.06 })}
+ </>
+ );
+ case "shadow":
+ return (
+ <>
+ {Array.from({ length: 6 }, (_, i) => (
+ <path key={i} d={`M${-W * 0.2 + i * W * 0.22} 0 l${W * 0.5} ${H} l${W * 0.08} 0 l${-W * 0.5} ${-H} z`} fill="black" opacity={0.08} />
+ ))}
+ <rect x={0} y={cy + s * 0.48} width={W} height={H} fill={c(0.82, 0.05, h1)} />
+ {prod()}
+ </>
+ );
+ case "blocks":
+ return (
+ <>
+ <rect x={cx - W * 0.3} y={cy + s * 0.5} width={W * 0.34} height={H * 0.3} fill={c(0.62, 0.17, h1)} />
+ <rect x={cx + W * 0.04} y={cy + s * 0.32} width={W * 0.28} height={H * 0.4} fill={c(0.7, 0.14, h2)} />
+ <circle cx={cx + W * 0.18} cy={cy + s * 0.32} r={W * 0.06} fill={c(0.9, 0.1, (h2 + 90) % 360)} />
+ {prod({ x: cx - W * 0.13, y: cy + s * 0.02, s: s * 0.9 })}
+ </>
+ );
+ case "nature":
+ return (
+ <>
+ <ellipse cx={cx} cy={cy + s * 0.62} rx={W * 0.55} ry={H * 0.13} fill={c(0.55, 0.12, 135)} />
+ {[0.18, 0.72, 0.4].map((x, i) => (
+ <ellipse key={i} cx={W * x} cy={cy + s * (0.52 + i * 0.06)} rx={W * 0.1} ry={H * 0.045} fill={c(0.7, 0.02, 60 + i * 20)} />
+ ))}
+ {prod()}
+ </>
+ );
+ case "studio":
+ case "listing":
+ return (
+ <>
+ <rect x={0} y={cy + s * 0.48} width={W} height={H} fill={c(0.95, 0.01, h1)} />
+ {prod()}
+ {scene === "listing" &&
+ [0.35, 0.55, 0.75].map((y, i) => (
+ <g key={i}>
+ <line x1={cx + W * 0.14} y1={H * y} x2={W * 0.78} y2={H * y} stroke={ink} strokeWidth={1.5} opacity={0.5} />
+ <circle cx={W * 0.8} cy={H * y} r={3.5} fill={ink} opacity={0.6} />
+ <rect x={W * 0.82} y={H * y - 4} width={W * 0.12} height={8} rx={4} fill={ink} opacity={0.35} />
+ </g>
+ ))}
+ {scene === "studio" && <Product shape={shape} x={cx} y={cy + s * 1.02} s={s} fill={fill} accent={accent} className="" />}
+ </>
+ );
+ case "shelf":
+ return (
+ <>
+ {Array.from({ length: 24 }, (_, i) => (
+ <rect key={i} x={(i % 6) * (W / 6) + 1} y={Math.floor(i / 6) * (H / 7) + 1} width={W / 6 - 2} height={H / 7 - 2} fill={c(0.9, 0.04, h2, 0.6)} />
+ ))}
+ <rect x={0} y={cy + s * 0.5} width={W} height={H * 0.06} fill={c(0.8, 0.03, h1)} />
+ {prod({ x: cx + W * 0.1 })}
+ <rect x={cx - W * 0.32} y={cy + s * 0.2} width={W * 0.12} height={s * 0.3} rx={4} fill={c(0.75, 0.05, h2)} />
+ </>
+ );
+ case "noir":
+ return (
+ <>
+ <radialGradient id={`rim-${id}`} cx="50%" cy="45%" r="45%">
+ <stop offset="0%" stopColor={c(0.55, 0.12, h2, 0.7)} />
+ <stop offset="100%" stopColor="transparent" />
+ </radialGradient>
+ <rect width={W} height={H} fill={`url(#rim-${id})`} />
+ {prod()}
+ <Product shape={shape} x={cx} y={cy + s * 1.02} s={s} fill={fill} accent={accent} className="opacity-25" />
+ </>
+ );
+ case "picnic":
+ return (
+ <>
+ {Array.from({ length: 8 }, (_, i) => (
+ <g key={i}>
+ <rect x={(i * W) / 8} y={cy + s * 0.3} width={W / 16} height={H} fill={c(0.6, 0.18, 25, 0.45)} />
+ <rect x={0} y={cy + s * 0.3 + (i * H) / 16} width={W} height={H / 32} fill={c(0.6, 0.18, 25, 0.45)} />
+ </g>
+ ))}
+ <circle cx={W * 0.22} cy={cy + s * 0.5} r={W * 0.05} fill={c(0.55, 0.2, 25)} />
+ <circle cx={W * 0.8} cy={cy + s * 0.42} r={W * 0.04} fill={c(0.55, 0.2, 25)} />
+ {prod()}
+ </>
+ );
+ case "citrus":
+ return (
+ <>
+ {Array.from({ length: 7 }, (_, i) => {
+ const a = (i / 7) * Math.PI * 2;
+ return (
+ <g key={i} className={video ? "mkp-pulse" : undefined}>
+ <circle cx={r2(cx + Math.cos(a) * W * 0.36)} cy={r2(cy + Math.sin(a) * H * 0.28)} r={W * 0.085} fill={c(0.82, 0.16, (h2 + i * 18) % 360)} />
+ <circle cx={r2(cx + Math.cos(a) * W * 0.36)} cy={r2(cy + Math.sin(a) * H * 0.28)} r={W * 0.06} fill={c(0.9, 0.12, (h2 + i * 18) % 360)} />
+ </g>
+ );
+ })}
+ {prod({ s: s * 0.85 })}
+ </>
+ );
+ case "model":
+ return (
+ <>
+ <Person x={cx - W * 0.06} y={H * 0.2} s={H * 0.72} skin={c(0.78, 0.06, 55)} shirt={c(0.55, 0.12, h2)} />
+ {prod({ x: cx + W * 0.2, y: H * 0.55, s: s * 0.55 })}
+ </>
+ );
+ case "selfie":
+ return (
+ <>
+ <rect x={W * 0.18} y={H * 0.08} width={W * 0.64} height={H * 0.84} rx={W * 0.08} fill={c(0.2, 0.02, h1)} />
+ <rect x={W * 0.21} y={H * 0.11} width={W * 0.58} height={H * 0.78} rx={W * 0.06} fill={c(0.82, 0.06, h2)} />
+ <Person x={cx} y={H * 0.26} s={H * 0.62} skin={c(0.78, 0.06, 55)} shirt={c(0.5, 0.13, h1)} />
+ {prod({ x: cx + W * 0.16, y: H * 0.62, s: s * 0.4 })}
+ {/* captions */}
+ <rect x={W * 0.3} y={H * 0.74} width={W * 0.4} height={H * 0.045} rx={4} fill="white" opacity={0.92} />
+ <g transform={`translate(${W * 0.27} ${H * 0.16})`}>
+ {[0, 1, 2].map((i) => (
+ <rect key={i} className={video ? "mkp-talk" : undefined} x={i * 7} y={0} width={4} height={14} rx={2} fill="white" opacity={0.8} style={{ animationDelay: `${i * 0.15}s` }} />
+ ))}
+ </g>
+ </>
+ );
+ case "orbit":
+ return (
+ <>
+ <ellipse cx={cx} cy={cy} rx={W * 0.4} ry={H * 0.12} fill="none" stroke={c(0.8, 0.1, h2, 0.6)} strokeWidth={2} strokeDasharray="6 6" />
+ <g className={video ? "mkp-spin" : undefined}>
+ <circle cx={cx + W * 0.4} cy={cy} r={5} fill={c(0.9, 0.12, h2)} />
+ </g>
+ <Product shape={shape} x={cx} y={cy} s={s} fill={fill} accent={accent} className={video ? "mkp-float" : undefined} />
+ </>
+ );
+ case "kinetic":
+ case "type":
+ return (
+ <>
+ <text x={W * 0.06} y={H * 0.42} fontSize={H * 0.36} fontWeight={900} fill={c(dark ? 0.4 : 0.75, 0.14, h2, 0.65)} className={video ? "mkp-slide" : undefined} fontFamily="system-ui, sans-serif">
+ {scene === "type" ? "AA" : "GO"}
+ </text>
+ {prod({ y: cy + s * 0.12, s: s * 0.9 })}
+ <Bars x={W * 0.08} y={H * 0.82} w={W * 0.5} n={2} color={ink} h={6} />
+ </>
+ );
+ case "collage":
+ return (
+ <>
+ {[-10, 6, -4].map((r, i) => (
+ <rect key={i} x={W * (0.1 + i * 0.22)} y={H * (0.16 + i * 0.18)} width={W * 0.42} height={H * 0.3} fill={c(0.85 - i * 0.12, 0.12, (h1 + i * 50) % 360)} transform={`rotate(${r} ${W / 2} ${H / 2})`} className={video ? "mkp-float" : undefined} />
+ ))}
+ {prod({ s: s * 0.8 })}
+ <rect x={W * 0.6} y={H * 0.1} width={W * 0.24} height={H * 0.05} fill={c(0.9, 0.05, 60, 0.8)} transform={`rotate(12 ${W * 0.7} ${H * 0.12})`} />
+ </>
+ );
+ case "cards":
+ return (
+ <>
+ {[0, 1, 2].map((i) => (
+ <g key={i} className={video ? "mkp-slide" : undefined} style={{ animationDelay: `${i * 0.2}s` }}>
+ <rect x={W * (0.12 + i * 0.06)} y={H * (0.2 + i * 0.2)} width={W * 0.64} height={H * 0.16} rx={10} fill={dark ? c(0.3, 0.05, h1) : "white"} opacity={0.95} />
+ <circle cx={W * (0.2 + i * 0.06)} cy={H * (0.28 + i * 0.2)} r={W * 0.04} fill={c(0.65, 0.16, (h2 + i * 40) % 360)} />
+ <Bars x={W * (0.28 + i * 0.06)} y={H * (0.25 + i * 0.2)} w={W * 0.36} n={2} color={ink} h={5} gap={5} />
+ </g>
+ ))}
+ </>
+ );
+ case "split":
+ return (
+ <>
+ <rect x={0} y={0} width={W / 2} height={H} fill={c(0.75, 0.02, h1)} />
+ <rect x={W / 2} y={0} width={W / 2} height={H} fill={c(0.8, 0.12, h2)} />
+ <line x1={W / 2} y1={0} x2={W / 2} y2={H} stroke="white" strokeWidth={3} />
+ <Product shape={shape} x={W * 0.25} y={cy} s={s * 0.7} fill={c(0.6, 0.01, h1)} accent={c(0.8, 0.01, h1)} className="" />
+ {prod({ x: W * 0.75, s: s * 0.8 })}
+ </>
+ );
+ case "headline":
+ case "badge":
+ case "stars":
+ case "burst":
+ return (
+ <>
+ {scene === "burst" && (
+ <g className={video ? "mkp-spin" : undefined}>
+ {Array.from({ length: 16 }, (_, i) => (
+ <path key={i} d={`M${cx} ${cy} l${r2(Math.cos((i * Math.PI) / 8) * W)} ${r2(Math.sin((i * Math.PI) / 8) * W)} l${r2(Math.cos(((i + 0.5) * Math.PI) / 8) * W)} ${r2(Math.sin(((i + 0.5) * Math.PI) / 8) * W)} z`} fill={c(0.85, 0.12, h2, 0.35)} />
+ ))}
+ </g>
+ )}
+ {prod({ y: H * 0.6, s: s * 0.85 })}
+ <Bars x={W * 0.08} y={H * 0.1} w={W * 0.7} n={2} color={ink} h={H * 0.04} gap={H * 0.02} />
+ {scene === "stars" &&
+ Array.from({ length: 5 }, (_, i) => (
+ <path key={i} transform={`translate(${W * (0.1 + i * 0.09)} ${H * 0.27}) scale(${W / 260})`} d="M10 0l3 7h7l-6 4 2 7-6-4-6 4 2-7-6-4h7z" fill={c(0.8, 0.16, 85)} />
+ ))}
+ {scene === "badge" && (
+ <g className={video ? "mkp-pulse" : undefined}>
+ <circle cx={W * 0.78} cy={H * 0.3} r={W * 0.12} fill={c(0.65, 0.18, h2)} />
+ <circle cx={W * 0.78} cy={H * 0.3} r={W * 0.09} fill="none" stroke="white" strokeWidth={2} strokeDasharray="3 3" />
+ </g>
+ )}
+ <rect x={W * 0.08} y={H * 0.86} width={W * 0.32} height={H * 0.06} rx={H * 0.03} fill={c(0.6, 0.17, h2)} />
+ </>
+ );
+ default:
+ return prod();
+ }
+}
+
+export const TemplatePreview = memo(function TemplatePreview({ id, look, video, className }: { id: string; look: TemplateLook; video?: boolean; className?: string }) {
+ const W = 240;
+ const H = 320;
+ const h1 = look.hue;
+ const h2 = look.hue2 ?? (look.hue + 40) % 360;
+ const bg = look.dark ? [c(0.24, 0.04, h1), c(0.14, 0.03, h2)] : [c(0.9, 0.06, h1), c(0.8, 0.09, h2)];
+ return (
+ <div className={cn("mkp relative size-full overflow-hidden", className)} data-video={video ? "" : undefined}>
+ <style href="fuobe-marketing-preview" precedence="default">
+ {CSS}
+ </style>
+ <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid slice" className="size-full" aria-hidden="true">
+ <defs>
+ <linearGradient id={`bg-${id}`} x1="0" y1="0" x2="1" y2="1">
+ <stop offset="0%" stopColor={bg[0]} />
+ <stop offset="100%" stopColor={bg[1]} />
+ </linearGradient>
+ </defs>
+ <rect width={W} height={H} fill={`url(#bg-${id})`} />
+ <Scene scene={look.scene} id={id} look={look} W={W} H={H} video={!!video} />
+ </svg>
+ </div>
+ );
+});
diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.ts
index cabd402e..ef384828 100644
--- a/src/lib/catalog/marketing.ts
+++ b/src/lib/catalog/marketing.ts
@@ -626,6 +626,37 @@ export function creativeStatusText(s: CreativeStatus, error?: string | null): st
export const MULTIPLIER = { minSeconds: 4, maxSeconds: 30, maxImages: 20, maxChars: 4000, defaultPrompt: "Recreate this ad.", qualities: ["480p", "720p", "1080p"] as const } as const;
+/** The part of the reference clip that's used (seconds). */
+export interface ClipRange {
+ start: number;
+ end: number;
+}
+
+const tenth = (n: number) => Math.round(n * 10) / 10;
+
+/** The first usable part of a fresh clip: all of it, or its first 30 s. */
+export const initialClip = (duration: number): ClipRange => ({ start: 0, end: tenth(Math.min(duration, MULTIPLIER.maxSeconds)) });
+
+/**
+ * Keep an in/out range inside the clip and within 4–30 s where the clip allows: the point that
+ * moved stays put and the other one follows (a clip shorter than 4 s stays as it is).
+ */
+export function clampClip(r: ClipRange, duration: number, moved: "start" | "end"): ClipRange {
+ const { minSeconds: min, maxSeconds: max } = MULTIPLIER;
+ let start = Math.min(Math.max(0, r.start), duration);
+ let end = Math.min(Math.max(0, r.end), duration);
+ if (moved === "start") {
+ if (end - start > max) end = Math.min(duration, start + max);
+ if (end - start < min) end = Math.min(duration, start + min);
+ if (end - start < min) start = Math.max(0, end - min);
+ } else {
+ if (end - start > max) start = Math.max(0, end - max);
+ if (end - start < min) start = Math.max(0, end - min);
+ if (end - start < min) end = Math.min(duration, start + min);
+ }
+ return { start: tenth(start), end: tenth(end) };
+}
+
export interface MultiplierParts {
mode: "prompt" | "sections";
prompt?: string;
@@ -826,6 +857,8 @@ export interface MarketingRunMeta {
script?: string;
mode?: "prompt" | "sections";
notes?: string[];
+ /** What the run was made from, so "Run again" can repeat it. */
+ input?: Record<string, unknown>;
}
export interface MarketingRun {
diff --git a/src/server/marketing.ts b/src/server/marketing.ts
index 2d695db1..0614a8e5 100644
--- a/src/server/marketing.ts
+++ b/src/server/marketing.ts
@@ -42,7 +42,7 @@ import { getBrand, getProduct } from "./brand";
import { createPipeline, type PipelineStep } from "./chains";
import { db } from "./db";
import { llmText } from "./enhance";
-import { createGenerations, listGenerations, previewChained } from "./generations";
+import { createGenerations, listGenerations, previewChained, recordLocalGeneration } from "./generations";
import { provider } from "./providers";
import { engineMode } from "./settings";
@@ -828,7 +828,7 @@ interface RunRow {
}
/** Create the run's generations (one request, or a pipeline) and record the run. */
-export function launch(plan: RunPlan): MarketingRun {
+export function launch(plan: RunPlan, input?: object): MarketingRun {
const engine = engineMode();
if (engine !== "both" && engine !== plan.engine) throw new PlanError(engine === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");
const batchId = nanoid(10);
@@ -843,7 +843,7 @@ export function launch(plan: RunPlan): MarketingRun {
byKey = Object.fromEntries(Object.entries(made.byKey).map(([k, g]) => [k, [g]]));
}
const finalIds = plan.finals.flatMap((k) => byKey[k]?.map((g) => g.id) ?? []);
- const row: RunRow = { id: nanoid(10), feature: plan.feature, batch_id: batchId, final_ids_json: JSON.stringify(finalIds), engine: plan.engine, title: plan.title, meta_json: JSON.stringify({ ...plan.meta, notes: plan.notes }), created_at: Date.now() };
+ const row: RunRow = { id: nanoid(10), feature: plan.feature, batch_id: batchId, final_ids_json: JSON.stringify(finalIds), engine: plan.engine, title: plan.title, meta_json: JSON.stringify({ ...plan.meta, notes: plan.notes, ...(input && { input }) }), created_at: Date.now() };
db().prepare("INSERT INTO marketing_runs (id, feature, batch_id, final_ids_json, engine, title, meta_json, created_at) VALUES (@id, @feature, @batch_id, @final_ids_json, @engine, @title, @meta_json, @created_at)").run(row);
return toRun(row);
}
@@ -904,7 +904,7 @@ export async function runMarketing(input: MarketingInput): Promise<{ runs: Marke
const runs = f.pipeline === "image" ? 1 : Math.min(input.batch ?? 1, f.batch);
// Check the whole plan (prices, models, engine mode, demo/real) before creating anything.
estimatePlan(plan);
- return { runs: Array.from({ length: runs }, () => launch(plan)), script };
+ return { runs: Array.from({ length: runs }, () => launch(plan, { ...input, batch: 1 })), script };
}
export function estimateClickToAd(input: ClickToAdInput): RunEstimate {
@@ -930,7 +930,7 @@ export async function runClickToAd(input: ClickToAdInput): Promise<{ run: Market
const script = input.script?.trim() ? fitScript(input.script, seconds) : (await clickToAdScript(input)).script;
const plan = planClickToAd(input, { product: ctx.product, brand: ctx.brand, script });
estimatePlan(plan);
- return { run: launch(plan), script };
+ return { run: launch(plan, { ...input, script }), script };
}
export function estimateMultiplier(input: MultiplierInput): RunEstimate {
@@ -941,7 +941,34 @@ export function estimateMultiplier(input: MultiplierInput): RunEstimate {
export function runMultiplier(input: MultiplierInput): MarketingRun[] {
const plan = planMultiplier(input, { higgsfield: higgsfieldReady() });
estimatePlan(plan);
- return Array.from({ length: input.versions ?? 1 }, () => launch(plan));
+ return Array.from({ length: input.versions ?? 1 }, () => launch(plan, { ...input, versions: 1 }));
+}
+
+/** "Run again": the same input as a new run (a UGC script is written afresh unless it was given). */
+export async function rerun(id: string): Promise<MarketingRun[]> {
+ const r = getRun(id);
+ if (!r) throw new PlanError("Not found");
+ const input = r.meta.input;
+ if (!input) throw new PlanError("This run can't be repeated — start it again from the form");
+ if (r.feature === "click-to-ad") return [(await runClickToAd(ClickToAdBody.parse(input))).run];
+ if (r.feature === "ad-multiplier") return runMultiplier(MultiplierBody.parse(input));
+ return (await runMarketing(MarketingBody.parse(input))).runs;
+}
+
+/** An open-engine poster/ad with its words set in the browser (an uploaded PNG), recorded in the Library. */
+export function saveRunComposite(id: string, input: { url: string; ratio: string; text: string }) {
+ const r = getRun(id);
+ if (!r) throw new PlanError("Not found");
+ const source = r.generations.find((g) => r.finalIds.includes(g.id))?.outputs.find((o) => o.kind === "image")?.url;
+ return recordLocalGeneration({
+ feature: r.feature,
+ modelId: "local-ad-compose",
+ op: "edit",
+ prompt: input.text.slice(0, 500) || r.title,
+ inputs: source ? { images: [source] } : {},
+ params: { aspectRatio: input.ratio },
+ output: { url: input.url, kind: "image", contentType: "image/png" },
+ });
}
// ---------------------------------------------------------------------------
diff --git a/tests/marketing-api.test.ts b/tests/marketing-api.test.ts
index d78a7ee7..8c2e9571 100644
--- a/tests/marketing-api.test.ts
+++ b/tests/marketing-api.test.ts
@@ -35,6 +35,9 @@ const readRoute = await import("@/app/api/products/read/route");
const runsRoute = await import("@/app/api/marketing/runs/route");
const estimateRoute = await import("@/app/api/marketing/estimate/route");
const multiplierEstimate = await import("@/app/api/ads/multiplier/estimate/route");
+const multiplierRoute = await import("@/app/api/ads/multiplier/route");
+const againRoute = await import("@/app/api/marketing/runs/[id]/again/route");
+const composeRoute = await import("@/app/api/marketing/runs/[id]/compose/route");
const adsEstimate = await import("@/app/api/ads/estimate/route");
const creativesRoute = await import("@/app/api/ads/creatives/route");
const creativeRoute = await import("@/app/api/ads/creatives/[id]/route");
@@ -361,6 +364,31 @@ describe("Ad Multiplier", () => {
const bad = await (await multiplierEstimate.POST(json("POST", { engine: "cloud", video: video(), duration: 45, mode: "prompt", quality: "720p" }))).json();
expect(bad.blocker).toBe("Video duration: 4-30 seconds");
});
+
+ it("makes versions in demo mode, runs them again with the same input, and saves a composed still", async () => {
+ const res = await multiplierRoute.POST(json("POST", { engine: "cloud", video: video(), duration: 10, mode: "prompt", prompt: "Recreate this ad.", quality: "720p", versions: 2 }));
+ expect(res.status).toBe(201);
+ const { runs } = await res.json();
+ expect(runs).toHaveLength(2);
+ expect(runs[0].meta.input).toMatchObject({ mode: "prompt", versions: 1 });
+ const again = await againRoute.POST(json("POST"), params({ id: runs[0].id }));
+ expect(again.status).toBe(201);
+ const next = (await again.json()).runs;
+ expect(next).toHaveLength(1);
+ expect(next[0].id).not.toBe(runs[0].id);
+ expect(next[0].title).toBe(runs[0].title);
+ expect((await againRoute.POST(json("POST"), params({ id: "nope" }))).status).toBe(404);
+ const list = await (await runsRoute.GET(json("GET", undefined, "http://x/api/marketing/runs?feature=ad-multiplier"))).json();
+ expect(list.items.map((r: { id: string }) => r.id)).toEqual(expect.arrayContaining([runs[0].id, runs[1].id, next[0].id]));
+
+ const png = upload("composed.png");
+ const saved = await composeRoute.POST(json("POST", { url: png, ratio: "9:16", text: "New headline · Shop now" }), params({ id: runs[0].id }));
+ expect(saved.status).toBe(201);
+ const g = await saved.json();
+ expect(g).toMatchObject({ status: "succeeded", modelId: "local-ad-compose", prompt: "New headline · Shop now" });
+ expect(g.outputs[0].url).toBe(png);
+ expect((await composeRoute.POST(json("POST", { url: "https://x.example/a.png", ratio: "9:16" }), params({ id: runs[0].id }))).status).toBe(400);
+ });
});
describe("Ads Studio", () => {
diff --git a/tests/marketing-catalog.test.ts b/tests/marketing-catalog.test.ts
index 4b3bed07..0586b168 100644
--- a/tests/marketing-catalog.test.ts
+++ b/tests/marketing-catalog.test.ts
@@ -27,7 +27,7 @@ import {
type FormatId,
} from "@/lib/catalog/marketing";
import type { Generation } from "@/lib/catalog/types";
-import { AD_LAYOUTS, AD_SIZE, contrast, coverCrop, exportName, fitText, planAd, planRects, readableOn, themeFrom, wrapText, type Measure } from "@/components/ads/layout";
+import { AD_LAYOUTS, contrast, coverCrop, exportName, fitText, planAd, planRects, readableOn, sizeFor, themeFrom, wrapText, type Measure } from "@/components/ads/layout";
describe("marketing catalog", () => {
it("ships Fuobe's own templates for every category, with unique ids and valid formats", () => {
@@ -193,13 +193,15 @@ describe("ad compositing layout", () => {
expect(huge.lines[1].endsWith("…")).toBe(true);
});
- it("keeps every box inside the canvas for each format and layout", () => {
+ it("keeps every box inside the canvas for each format and layout (and a generated poster's own ratio)", () => {
const content = { headline: "Granola that tastes like a slow Sunday morning", body: "Organic oats, maple and sea salt, roasted in small batches in Portland.", cta: "Shop now", brand: "Ember & Oat" };
- for (const ratio of ["1:1", "4:5", "9:16"] as const) {
+ expect(sizeFor("3:4")).toEqual({ w: 1080, h: 1440 });
+ expect(sizeFor("nonsense")).toEqual(sizeFor("1:1"));
+ for (const ratio of ["1:1", "4:5", "9:16", "3:4", "2:3", "4:3", "3:2", "16:9"]) {
for (const layout of AD_LAYOUTS.map((l) => l.id)) {
for (const logo of [null, { w: 400, h: 120 }]) {
const plan = planAd({ ratio, layout, content, theme, image: { w: 1024, h: 1280 }, logo, measure });
- const { w, h } = AD_SIZE[ratio];
+ const { w, h } = sizeFor(ratio);
expect(plan.w).toBe(w);
for (const r of planRects(plan)) {
expect(r.x, `${ratio} ${layout}`).toBeGreaterThanOrEqual(-0.5);
@@ -209,7 +211,7 @@ describe("ad compositing layout", () => {
}
// The headline never runs into the CTA.
if (plan.cta && layout !== "band") expect(plan.headline.y + plan.headline.lines.length * plan.headline.lineHeight).toBeLessThanOrEqual(plan.cta.y + 0.5);
- expect(plan.headline.lines.join(" ")).toBe(content.headline);
+ expect(plan.headline.lines.join(" "), `${ratio} ${layout}`).toBe(content.headline);
if (logo) expect(plan.brand).toBeUndefined();
}
}