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.

34.6 KB
Raw Blame
"use client";

import { useQueryClient } from "@tanstack/react-query";
import { ArrowUp, ChevronDown, Globe, Image as ImageIcon, LayoutTemplate, Loader2, SlidersHorizontal, Type, Video, X } from "lucide-react";
import { useRouter, 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 { RunPlaceChip, useRunPlace } from "@/components/studio/run-place-chip";
import { mainModel, ownerOnlyWay } from "@/lib/run-place";
import { BrandChip } from "@/components/brand/brand-dialog";
import { inputCls } from "@/components/brand/fields";
import { withoutOwnGpu } from "@/lib/catalog/engines";
import { Switch } from "@/components/ui/switch";
import { DRAWN_WORDS_HINT, DRAWN_WORDS_LABEL, FORMATS, formatModels, isCodeTemplate, looksLikeWebsite, pickable, MAX_PROMPT, openingAspect, TEMPLATE_INDEX, visibleTemplate, type FormatId, type MarketingCategory, type MarketingTemplate, type RunEstimate } from "@/lib/catalog/marketing";
import { SelfHostNote } from "@/components/self-host-note";
import { StarterSection } from "@/components/starters/starter-section";
import { useIsOwner, useLikelyVisitor, useModelAccess, usePlaceName } from "@/lib/api";
import { keepOffered, offered } from "@/lib/model-access";
import type { StarterCardData } from "@/lib/starters/types";
import { cn } from "@/lib/utils";
import { addRuns, send, useBrands, useEstimate, useProducts } from "./hooks";
import { KineticTemplate } from "./kinetic-template";
import type { MarketingRun } from "@/lib/catalog/marketing";
import { toastError } from "@/lib/refusals";
import { templateCover } from "@/lib/template-covers";
import type { ModelInfo } from "./model-info";
import { FitNotes, type FitNote } from "@/components/studio/fit-notes";
import { AvatarSlot, HookPicker, ProductSlot, productChoice, SettingPicker, VoiceControl, type ProductChoice } from "./pickers";
import { ProductParam } from "./product-param";
import { RunsList } from "./runs";
import { EmptyIcon, MarketingHeader, useMarketingEngine } from "./shell";
import { TemplateGallery, type MediaFilter } from "./template-gallery";
import { TemplatePreview } from "./template-preview";
import { plainTagline } from "@/lib/plain-tagline";
import { onAttr, TAB_PILL, TabRow, useSwapFade } from "@/components/ui/tab-row";

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;
  /** SaaS motion: a website or social link to make the video about. */
  website: string;
  /** "Words drawn by the model" (formats with words): the headline and button drawn in place, not set on top. */
  drawnWords?: boolean;
}

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, website: "" };

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: openingAspect(d, t, f.id),
    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, engine }: { draft: Draft; set: (p: Partial<Draft>) => void; models: Record<string, ModelInfo>; engine: "cloud" | "open" }) {
  const [open, setOpen] = useState(false);
  const f = FORMATS[draft.format];
  // Models switched off in Settings → Models & licences leave the menu, and the pick falls back to one that is on.
  const access = useModelAccess();
  // A guest or an account: Marketing Studio runs on a self-hosted Fuobe only, so no model reads "on your GPU".
  const visitor = useLikelyVisitor();
  const listed = formatModels(f, engine, { product: !!draft.product, avatar: !!draft.avatar }, !!draft.drawnWords);
  // One listed only to say it runs on your GPU (the Original's Standalone shot in the cloud) is shown, never picked.
  const choices = keepOffered(pickable(listed), (c) => offered(access, c.id, engine));
  const elsewhere = listed.filter((c) => c.unavailable);
  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>
            {f.pipeline === "ugc" && <p className="-mt-1 mb-1.5 text-[11px] text-muted-foreground">The whole video: the script is sized to what&apos;s left after the hook and the product close-up</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-muted-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">{visitor ? withoutOwnGpu(c.note ?? plainTagline(models[c.id]?.tagline ?? "")) : (c.note ?? plainTagline(models[c.id]?.tagline ?? ""))}</span>
              </button>
            ))}
            {elsewhere.map((c) => (
              <div key={c.id} aria-disabled="true" className="w-full rounded-lg px-2.5 py-1.5 text-left opacity-60">
                <span className="block text-[13px] font-medium">{models[c.id]?.name ?? c.id}</span>
                <span className="block text-[11px] text-muted-foreground">{c.note}</span>
              </div>
            ))}
          </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;
  const drawnId = "marketing-drawn-words";
  return (
    <ResponsivePanel
      open={open}
      onOpenChange={setOpen}
      title="Words on the image"
      description="Set exactly, letter for letter: Fuobe Marketing Image and open-source results get them set on top in your brand fonts; GPT Image, Ideogram and Recraft draw them."
      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>
        {/* Off by default: words set on top keep your exact fonts. On: a model that places boxes draws them in place. */}
        <div className="flex items-start gap-3 rounded-xl bg-muted/60 p-3">
          <div className="min-w-0 flex-1">
            <label htmlFor={drawnId} className="block text-[13px] font-medium">
              {DRAWN_WORDS_LABEL}
            </label>
            <p id={`${drawnId}-hint`} className="mt-0.5 text-[11px] leading-snug text-muted-foreground">
              {DRAWN_WORDS_HINT}
            </p>
          </div>
          <Switch id={drawnId} checked={!!draft.drawnWords} onCheckedChange={(v) => set({ drawnWords: v, modelId: undefined })} aria-describedby={`${drawnId}-hint`} className="mt-0.5 shrink-0" />
        </div>
      </div>
    </ResponsivePanel>
  );
}

/** SaaS motion's "Website or social link" (one of prompt / product / website). */
function WebsitePanel({ draft, set }: { draft: Draft; set: (p: Partial<Draft>) => void }) {
  const [open, setOpen] = useState(false);
  const v = draft.website.trim();
  const bad = !!v && !looksLikeWebsite(v);
  return (
    <ResponsivePanel
      open={open}
      onOpenChange={setOpen}
      title="Website or social link"
      description="What the video is about when there's no product photo: your site or a social profile."
      trigger={
        <button type="button" className={cn(chipBase, v && !bad ? chipOn : chipIdle, "max-w-44")} aria-label={v ? `Website: ${v}` : "Add a website or social link"}>
          <Globe className="size-3.5" />
          <span className="truncate">{v ? v.replace(/^https?:\/\//i, "") : "Website"}</span>
        </button>
      }
    >
      <label className="block space-y-1.5">
        <span className="text-[12px] font-medium text-muted-foreground">Link</span>
        <input value={draft.website} onChange={(e) => set({ website: e.target.value })} maxLength={300} inputMode="url" placeholder="www.example.com" aria-invalid={bad || undefined} className={cn(inputCls, bad && "border-destructive")} />
        {bad && <span className="block text-[11px] text-destructive">Enter a valid website URL</span>}
      </label>
    </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, owner }: { onTemplate: (t: MarketingTemplate) => void; onTab: (t: "templates" | "generations") => void; owner: boolean }) {
  const q = useSearchParams();
  // The address read last: a ready shoot opened from this page (?template=…&product=…) is read too, once.
  const done = useRef<string | null>(null);
  useEffect(() => {
    // An owner-only template's address is read again once the owner is known.
    const key = `${q.toString()}|${owner}`;
    if (done.current === key) return;
    done.current = key;
    const t = q.get("template");
    const found = t ? TEMPLATE_INDEX.get(t) : undefined;
    if (found && visibleTemplate(found, owner)) onTemplate(found);
    if (q.get("tab") === "generations") onTab("generations");
  }, [q, onTemplate, onTab, owner]);
  return null;
}

/**
 * Marketing Studio: pick a template (or a format), add your product, avatar, hook and brand kit, and generate.
 * starters: the ready shoots (a product with its photo and a template; src/lib/starters/catalog.ts), above the templates
 * while there are no saved products.
 */
export function MarketingStudio({ models, starters = [] }: { models: Record<string, ModelInfo>; starters?: StarterCardData[] }) {
  const qc = useQueryClient();
  const { engine, setEngine } = useMarketingEngine();
  const [tab, setTab] = useState<"templates" | "generations">("templates");
  const viewRef = useSwapFade<HTMLDivElement>(tab);
  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);
  // Focus anywhere in the composer, its popovers and dialogs included.
  const [engaged, setEngaged] = useState(false);
  const composer = useRef<HTMLDivElement>(null);
  const prompt = useRef<HTMLTextAreaElement>(null);
  // A run doesn't go to an account's own GPU or key yet (only the studios' generations do): said up front, with no
  // upload slots and no Generate, instead of a run the server refuses. The slots show once the owner is known
  // (useIsOwner), so a visitor never sees them and then gone.
  const visitor = useLikelyVisitor();
  const isOwner = useIsOwner();
  const router = useRouter();
  const set = (p: Partial<Draft>) => setDraft((d) => ({ ...d, ...p }));
  const f = FORMATS[draft.format];
  const found = draft.templateId ? TEMPLATE_INDEX.get(draft.templateId) : undefined;
  const template = visibleTemplate(found, isOwner) ? found : undefined;
  // A template drawn by Kinetic Motion opens its own panel (words, brand, sizes, live preview, Save) instead of the
  // composer: nothing is generated, so it is open to everyone and asks only on Save.
  const code = isCodeTemplate(template);
  const panel = useRef<HTMLDivElement>(null);
  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 products = useProducts();
  const noProducts = products.isSuccess && !products.data.length;

  const pickTemplate = (t: MarketingTemplate) => {
    setDraft((d) => withTemplate(d, t));
    if (isCodeTemplate(t)) requestAnimationFrame(() => panel.current?.scrollIntoView({ behavior: "smooth", block: "start" }));
    else requestAnimationFrame(() => prompt.current?.focus({ preventScroll: true }));
  };

  const body = useMemo(
    () => ({
      engine,
      format: draft.format,
      templateId: draft.templateId ?? undefined,
      // A pick that runs on your GPU only (the Original's Standalone shot) isn't sent to the cloud: its default runs.
      modelId: draft.modelId && !formatModels(f, engine, { product: true, avatar: true }, !!draft.drawnWords).some((c) => c.unavailable && c.id === draft.modelId) ? draft.modelId : undefined,
      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,
      website: f.oneOf?.includes("website") && looksLikeWebsite(draft.website) ? draft.website.trim() : undefined,
      drawnWords: f.text && f.pipeline === "image" && draft.drawnWords ? true : undefined,
    }),
    [draft, engine, f, brandId],
  );
  const est = useEstimate<RunEstimate>("/api/marketing/estimate", draft.avatar?.uploading || draft.voiceSample?.uploading ? null : body);
  const badSite = !!f.oneOf?.includes("website") && !!draft.website.trim() && !looksLikeWebsite(draft.website);
  // While hosted runs are on, a visitor's Generate opens the studio that makes it now, on this studio's GPUs.
  const site = usePlaceName();
  const way = visitor && site ? ownerOnlyWay("image") : null;
  const blocker = visitor
    ? way
      ? `${way.label} · runs on ${site!.text}`
      : "Marketing Studio isn't available here"
    : draft.product === null && f.product === "required"
      ? "Attach a product to generate"
      : badSite
        ? "Enter a valid website URL"
        : est.data?.blocker;
  // Where the run happens and its price, as the studios say it (the chip by the send button); a guest or an account is
  // told the tool isn't available here, with no price.
  const priced = est.data && !est.data.blocker ? est.data : undefined;
  const fits = est.data?.fits;
  // A note the fit already says (with its fix) isn't said again in the line under the composer.
  const notes = (est.data?.notes ?? []).filter((n) => !fits?.some((c) => c.note === n));
  const fitFix = (c: FitNote) =>
    c.switchTo ? () => set({ modelId: c.switchTo!.id }) : c.use === undefined ? undefined : c.setting === "aspectRatio" ? () => set({ aspectRatio: String(c.use) }) : c.setting === "duration" ? () => set({ duration: Number(c.use) }) : undefined;
  // Until the run is priced (no product yet), the chip names the model Settings has picked, as the studios' model chip does.
  const access = useModelAccess();
  const picked = useMemo(() => {
    const choices = keepOffered(pickable(formatModels(f, engine, { product: !!draft.product, avatar: !!draft.avatar }, !!draft.drawnWords)), (c) => offered(access, c.id, engine));
    const c = choices.find((x) => x.id === draft.modelId) ?? choices[0];
    return c ? (models[c.id]?.name ?? undefined) : undefined;
  }, [f, engine, draft.product, draft.avatar, draft.drawnWords, draft.modelId, access, models]);
  const place = useRunPlace({
    engine,
    models: priced ? priced.steps.map((s) => s.modelName) : picked ? [picked] : undefined,
    model: mainModel(priced?.steps) ?? picked,
    costUsd: priced?.costUsd,
    demo: priced?.demo,
    ownerOnly: "Marketing Studio",
  });
  const sendTip = place?.send ? ` · ${place.send}` : "";

  // Until a template is picked or you start on the composer it stays slim (the attachment tiles fold
  // away), so the template gallery behind it stays in view.
  const slim = !template && !engaged && !draft.product && !draft.avatar && !draft.reference && !draft.prompt.trim();
  const leaveComposer = () =>
    requestAnimationFrame(() => {
      const a = document.activeElement;
      if (!a || !(composer.current?.contains(a) || a.closest("[data-radix-popper-content-wrapper], [role=dialog]"))) setEngaged(false);
    });

  const generate = async () => {
    if (visitor) {
      if (way) router.push(way.href);
      return;
    }
    if (blocker) {
      setEngaged(true);
      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) {
      toastError(e);
    } 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-content min-w-0 flex-col">
      <MarketingHeader title="Marketing Studio" active="studio" engine={engine} onEngine={setEngine} selfHostedOnly />
      <Suspense fallback={null}>
        <UrlParams onTemplate={pickTemplate} onTab={setTab} owner={isOwner} />
        <ProductParam products={products.data} onProduct={(p) => set({ product: productChoice(p) })} />
      </Suspense>
      <div className="mx-auto w-full min-w-0 max-w-[1240px] flex-1 px-4 pb-10 sm:px-6">
        {/* With no products yet, the ready shoots come first: a lower hero keeps them above the docked composer. */}
        <div className={cn("pt-6 pb-2 text-center", noProducts ? "sm:pt-6" : "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" ? (visitor ? "open-source models" : "your own GPU, free") : "Fuobe Marketing Image or partner models in the cloud"}.
          </p>
        </div>
        {code && template && (
          <div ref={panel} className="mt-4 scroll-mt-40">
            <KineticTemplate key={template.id} template={template} onClose={() => setDraft((d) => withTemplate(d, null, d.format))} kitId={brandId} onKit={pickBrand} />
          </div>
        )}
        {!code && noProducts && <StarterSection surface="marketing" starters={starters} center compact className="mt-6 mb-4" />}
        {/* Under the ready shoots, so it doesn't read as an answer to them. */}
        {visitor && !code && <SelfHostNote className="mx-auto mt-3 max-w-xl text-center">Marketing Studio isn&apos;t available here.</SelfHostNote>}
        <TabRow role="tablist" aria-label="View" fade={false} className="mx-auto mt-4 w-fit">
          {(["templates", "generations"] as const).map((t) => (
            <button key={t} role="tab" aria-selected={tab === t} onClick={() => setTab(t)} className={TAB_PILL} {...onAttr(tab === t)}>
              {t === "templates" ? "Templates" : "My generations"}
            </button>
          ))}
        </TabRow>
        <div ref={viewRef} className="mt-6">
          {tab === "templates" ? (
            <>
              {/* Once there are products of your own, the ready shoots are one row above the templates. */}
              {!!products.data?.length && <StarterSection surface="marketing" starters={starters} row center className="mb-12" />}
              <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>
      </div>

      {/* Docked composer (a Kinetic template has its own panel) */}
      <div hidden={code} className="sticky bottom-chrome z-20 bg-gradient-to-t from-background via-background/95 to-transparent px-4 pt-8 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-6">
        <div
          ref={composer}
          data-slim={slim || undefined}
          onFocus={() => setEngaged(true)}
          onBlur={leaveComposer}
          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={cn("scrollbar-none flex items-center gap-2 overflow-x-auto px-1 pt-1.5 pb-1", slim && "hidden")}>
            {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} cover={templateCover("marketing", template.id)} sizes="36px" />
                </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>
            )}
            {/* A guest or an account gets no upload slots: nothing is uploaded for a run that can't start here. */}
            {isOwner && f.product !== "none" && <ProductSlot value={draft.product} onChange={(p) => set({ product: p })} required={f.product === "required"} brandId={brandId} pulse={pulse === "product"} />}
            {isOwner && f.avatar !== "none" && <AvatarSlot value={draft.avatar} onChange={(a) => set({ avatar: a })} pulse={pulse === "avatar"} />}
            {isOwner && 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.oneOf?.includes("website") && <WebsitePanel draft={draft} set={set} />}
              {f.brandKit && <BrandChip value={brandId} onChange={pickBrand} />}
              <SettingsPanel draft={draft} set={set} models={models} engine={engine} />
            </div>
            <RunPlaceChip place={place} steps={priced?.steps} engine={engine} onEngine={setEngine} pending={est.isFetching && !est.data} compact className="max-sm:shrink-0 sm:max-w-[16rem]" />
            <Tooltip>
              <TooltipTrigger asChild>
                <button
                  type="button"
                  onClick={() => void generate()}
                  disabled={visitor}
                  aria-label={template ? "Recreate template" : "Generate"}
                  aria-disabled={!!blocker || busy}
                  className={cn("grid size-10 shrink-0 place-items-center rounded-full text-primary-foreground transition-colors", blocker ? "bg-primary/70 hover:bg-primary/80" : "bg-primary hover:bg-primary/90")}
                >
                  {busy ? <Loader2 className="size-4 animate-spin" /> : <ArrowUp className="size-4" />}
                </button>
              </TooltipTrigger>
              <TooltipContent>{blocker ?? (template ? `Recreate template${sendTip}` : `Generate${sendTip}`)}</TooltipContent>
            </Tooltip>
          </div>
          {notes.length && !blocker ? <p className="hidden truncate px-2 pt-1 text-[11px] text-muted-foreground sm:block">{notes[0]}</p> : null}
          {/* Phones have no hover: what blocks Generate sits under the composer (the chip says where it runs and its price). */}
          {(!!blocker || !!notes.length) && (
            <p className="min-w-0 truncate px-2 pt-1 text-[11px] text-muted-foreground sm:hidden" aria-live="polite">
              {blocker ?? notes[0] ?? ""}
            </p>
          )}
          {/* A shape or length picked here that the run makes differently: said before it runs, with the way to what is made. */}
          {!blocker && <FitNotes fits={fits} apply={fitFix} className="px-1" />}
        </div>
      </div>
    </div>
  );
}