Skip to content

Unrestricted Open-source alternative to AI video platforms — Free AI image & video generation studio with 600+ models (Flux, Midjourney, Kling, Sora, Veo). No content filters. Self-hosted, MIT licensed.

34.5 KB
Raw Blame
"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import toast, { Toaster } from "react-hot-toast";
import { runMotionGraphics, runMotionGraphicsEdit } from "../muapi.js";
import { formatErrorMessage } from "../utils/formatError.js";
import { scopedPersistKey, migrateLegacyPersistKey } from "../persistKey.js";
import MobileGenerationActions, {
  GenerationCopyButtons,
} from "./MobileGenerationActions.jsx";
import {
  PROMPT_CONTROL_LABEL_CLASS,
  PromptAspectRatioIcon,
  PromptAction,
  PromptChevronIcon,
  PromptComposer,
  PromptControls,
  PromptFooter,
  PromptMenuItem,
  PromptMenuList,
  PromptPopover,
  PromptPopoverHeader,
  PromptDurationIcon,
  PromptSegmentedControl,
  PromptSegmentOption,
  PromptTextarea,
  promptControlClassName,
} from "./prompt/PromptComposer.jsx";
import en from "../messages/en/vibeMotionStudio.json";
import zh from "../messages/zh/vibeMotionStudio.json";
import { resolveCopy } from "../i18nUtils";

// ── helpers ───────────────────────────────────────────────────────────────────
async function downloadFile(url, filename) {
  try {
    const res = await fetch(url);
    const blob = await res.blob();
    const blobUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = blobUrl;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(blobUrl);
  } catch {
    window.open(url, "_blank");
  }
}

const formatTime = (s) =>
  `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;

// ── icons ─────────────────────────────────────────────────────────────────────
const CheckSvg = () => (
  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#22d3ee" strokeWidth="4">
    <polyline points="20 6 9 17 4 12" />
  </svg>
);

// ── Dropdown helper ───────────────────────────────────────────────────────────
function DropdownItem({ label, selected, onClick }) {
  return (
    <PromptMenuItem
      selected={selected}
      onClick={onClick}
    >
      {label}
    </PromptMenuItem>
  );
}

// ── Main Component ────────────────────────────────────────────────────────────
export default function VibeMotionStudio({
  apiKey,
  onGenerationStart,
  onGenerationEnd,
  onGenerationComplete,
  onGenerationError,
  locale = "en",
}) {
  const copy = resolveCopy(en, zh, locale);
  const LEGACY_PERSIST_KEY = "hg_vibe_motion_studio_persistent";
  const PERSIST_KEY = scopedPersistKey(LEGACY_PERSIST_KEY, apiKey);
  useEffect(() => {
    migrateLegacyPersistKey(LEGACY_PERSIST_KEY, PERSIST_KEY);
  }, [PERSIST_KEY]);

  // ── Params ────────────────────────────────────────────────────────────────
  const [prompt, setPrompt] = useState("");
  const [aspectRatio, setAspectRatio] = useState("16:9");
  const [duration, setDuration] = useState(6);

  // ── Edit mode ─────────────────────────────────────────────────────────────
  const [editMode, setEditMode] = useState(false);
  const [editSourceId, setEditSourceId] = useState(null);  // request_id of source

  // ── Dropdown open state ───────────────────────────────────────────────────
  const [openDropdown, setOpenDropdown] = useState(null); // "ar" | "dur" | "source"
  const controlsRef = useRef(null);
  const textareaRef = useRef(null);

  // ── Generation state ──────────────────────────────────────────────────────
  const [generating, setGenerating] = useState(false);
  const [generateError, setGenerateError] = useState(null);
  const [elapsedTime, setElapsedTime] = useState(0);
  const timerRef = useRef(null);
  const pendingRequestId = useRef(null);

  // ── History ───────────────────────────────────────────────────────────────
  const [history, setHistory] = useState([]);
  const [fullscreenUrl, setFullscreenUrl] = useState(null);

  // ── Load from localStorage ─────────────────────────────────────────────────
  useEffect(() => {
    try {
      const saved = JSON.parse(localStorage.getItem(PERSIST_KEY) || "[]");
      if (Array.isArray(saved)) {
        // Strip any wrongly-persisted canEdit:false flags from old bug — restore all entries as remixable
        const restored = saved.map((h) => {
          const { canEdit, ...rest } = h;
          return rest; // canEdit is only an in-memory hint, never persisted
        });
        setHistory(restored);
      }
    } catch (_) {}
  }, []);

  const saveHistory = useCallback((items) => {
    setHistory(items);
    // Strip canEdit from persisted data — it is an in-memory hint only
    const stripped = items.map(({ canEdit, ...rest }) => rest);
    try { localStorage.setItem(PERSIST_KEY, JSON.stringify(stripped)); } catch (_) {}
  }, []);

  // ── Close dropdowns on outside click ─────────────────────────────────────
  useEffect(() => {
    const handler = (e) => {
      if (controlsRef.current && !controlsRef.current.contains(e.target)) {
        setOpenDropdown(null);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);
  // ── Timer ─────────────────────────────────────────────────────────────────
  const startTimer = () => {
    setElapsedTime(0);
    timerRef.current = setInterval(() => setElapsedTime((t) => t + 1), 1000);
  };
  const stopTimer = () => { clearInterval(timerRef.current); timerRef.current = null; };
  useEffect(() => () => stopTimer(), []);

  // ── Generate ──────────────────────────────────────────────────────────────
  const handleGenerate = useCallback(async () => {
    if (!prompt.trim() || generating) return;
    onGenerationStart?.();
    setGenerating(true);
    setGenerateError(null);
    startTimer();
    try {
      let result;
      if (editMode) {
        result = await runMotionGraphicsEdit(apiKey, {
          request_id: editSourceId,
          edit_prompt: prompt.trim(),
          aspect_ratio: aspectRatio,
          duration_seconds: duration,
          onRequestId: (id) => { pendingRequestId.current = id; },
        });
      } else {
        result = await runMotionGraphics(apiKey, {
          prompt: prompt.trim(),
          aspect_ratio: aspectRatio,
          duration_seconds: duration,
          onRequestId: (id) => { pendingRequestId.current = id; },
        });
      }

      const videoUrl = result?.output?.video || result?.url || result?.outputs?.[0];
      const requestId = result?.id || result?.request_id || pendingRequestId.current;

      const entry = {
        id: requestId || Date.now().toString(),
        requestId,
        url: videoUrl,
        prompt: prompt.trim(),
        aspectRatio,
        duration,
        mode: editMode ? "edit" : "generate",
        sourceId: editMode ? editSourceId : null,
        timestamp: new Date().toISOString(),
        // Mark as editable — only generations created with saved animation code can be remixed
        canEdit: true,
      };

      const next = [entry, ...history].slice(0, 30);
      saveHistory(next);
      onGenerationComplete?.({ url: videoUrl, type: "video" });
    } catch (err) {
      // Detect the backend's "animation code not saved" limitation
      const raw = err.message || "";
      const isStaleEdit =
        raw.includes("animation code") ||
        raw.includes("does not have saved") ||
        raw.includes("Original generation does not");

      if (isStaleEdit) {
        console.warn("[VibeMotionStudio] Remix unavailable:", raw.slice(0, 120));
        const msg = copy.errors.staleEditUnavailable;
        if (onGenerationError) onGenerationError(msg);
        else toast.error(msg);
        setEditMode(false);
        setEditSourceId(null);
      } else {
        console.error("[VibeMotionStudio]", err);
        const errMsg = formatErrorMessage(raw || err, copy.errors.generationFailed);
        if (onGenerationError) onGenerationError(errMsg);
        else toast.error(errMsg);
      }
    } finally {
      setGenerating(false);
      stopTimer();
      onGenerationEnd?.();
    }
  }, [
    apiKey,
    prompt,
    editMode,
    editSourceId,
    aspectRatio,
    duration,
    history,
    saveHistory,
    onGenerationComplete,
    onGenerationEnd,
    onGenerationError,
    onGenerationStart,
    copy,
  ]);

  const handleKeyDown = (e) => {
    if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) handleGenerate();
  };

  const toggleDropdown = (type) => (e) => {
    e.stopPropagation();
    setOpenDropdown((prev) => (prev === type ? null : type));
  };

  const ASPECT_RATIOS = ["16:9", "9:16", "1:1"];
  const DURATION_OPTIONS = [5, 6, 8, 10, 12, 15, 20, 25, 30];

  // Show all entries with a requestId as editable UNLESS they are explicitly marked canEdit:false
  // (entries loaded from localStorage without the flag are treated as optimistically editable)
  const editSources = history.filter((h) => h.requestId && h.canEdit !== false);
  const sourceEntry = editSources.find((h) => h.requestId === editSourceId);

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <div className="w-full h-full flex flex-col items-center justify-center bg-app-bg relative overflow-hidden">
      {/* ── Fullscreen overlay ── */}
      {fullscreenUrl && (
        <div
          className="fixed inset-0 z-[200] bg-black/95 flex items-center justify-center"
          onClick={() => setFullscreenUrl(null)}
        >
          <video
            src={fullscreenUrl}
            autoPlay loop controls
            className="max-h-[90vh] max-w-[90vw] rounded shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          />
          <button
            className="absolute top-6 right-6 text-white/60 hover:text-white transition-colors text-3xl font-light leading-none"
            onClick={() => setFullscreenUrl(null)}
          >×</button>
        </div>
      )}

      {/* ── GALLERY AREA ── */}
      <div className="flex-1 w-full max-w-7xl mx-auto overflow-y-auto custom-scrollbar pb-40 lg:pb-32 px-2">
        {generating && (
          /* ── Loading card at top of grid ── */
          <div className="w-full pt-6 flex justify-center animate-fade-in-up">
            <div className="flex flex-col items-center gap-4 py-16">
              <div className="relative w-20 h-20">
                <div className="absolute inset-0 rounded-full border-2 border-violet-500/20 animate-ping" />
                <div className="absolute inset-2 rounded-full border-2 border-[#22d3ee]/30 animate-spin" />
                <div className="absolute inset-4 rounded-full border-2 border-violet-400/50 animate-[spin_1.5s_linear_infinite_reverse]" />
                <div className="absolute inset-0 flex items-center justify-center">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-violet-400 animate-pulse">
                    <path d="M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 17l-6.2 4.3 2.4-7.4L2 9.4h7.6z"/>
                  </svg>
                </div>
              </div>
              <div className="flex flex-col items-center gap-1">
                <span className="text-white/80 font-semibold text-sm">
                  {editMode ? copy.loading.remixing : copy.loading.generating}
                </span>
                <span className="text-white/30 text-xs">{copy.loading.backend}</span>
              </div>
              <div className="flex items-center gap-2 text-white/30 text-xs bg-white/[0.03] px-4 py-1.5 rounded-full border border-white/[0.05]">
                <svg className="animate-spin" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
                  <circle cx="12" cy="12" r="10" strokeOpacity="0.2"/>
                  <path d="M12 2a10 10 0 0 1 10 10"/>
                </svg>
                {formatTime(elapsedTime)}
              </div>
            </div>
          </div>
        )}

        {!generating && history.length > 0 ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 w-full pt-4 animate-fade-in-up">
            {history.map((entry, idx) => (
              <div
                key={entry.id || idx}
                className="relative group rounded overflow-hidden border border-white/10 bg-[#0a0a0a] shadow-xl hover:border-primary/50 transition-all duration-300 flex flex-col cursor-pointer"
                onClick={() => setFullscreenUrl(entry.url)}
              >
                {/* Video thumbnail */}
                <video
                  src={entry.url}
                  className="w-full aspect-video object-cover bg-black/40 hover:opacity-80 transition-opacity"
                  controls={false}
                  loop
                  muted
                  playsInline
                  onMouseOver={(e) => e.target.play()}
                  onMouseOut={(e) => { e.target.pause(); e.target.currentTime = 0; }}
                />

                {/* ── Mode tag (top-left) ── */}
                <div className={`absolute top-2 left-2 px-2 py-0.5 rounded-md text-[9px] font-bold uppercase tracking-wider backdrop-blur-sm border ${
                  entry.mode === "edit"
                    ? "bg-[#22d3ee]/20 text-[#22d3ee] border-[#22d3ee]/30"
                    : "bg-violet-600/30 text-violet-300 border-violet-500/30"
                }`}>
                  {entry.mode === "edit" ? copy.card.modeEdit : copy.card.modeGenerated}
                </div>

                {/* ── Hover overlay actions ── */}
                <div className="absolute top-2 right-2 hidden md:flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  <GenerationCopyButtons
                    prompt={entry.prompt}
                    onCopyError={onGenerationError}
                  />
                  <button
                    type="button"
                    title={copy.card.download}
                    onClick={(e) => { e.stopPropagation(); downloadFile(entry.url, `motion-${entry.id || idx}.mp4`); }}
                    className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                      <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />
                    </svg>
                  </button>
                  {entry.requestId && entry.canEdit !== false ? (
                    <button
                      type="button"
                      title={copy.card.remixThis}
                      onClick={(e) => {
                        e.stopPropagation();
                        setEditMode(true);
                        setEditSourceId(entry.requestId);
                        setPrompt("");
                        setTimeout(() => textareaRef.current?.focus(), 50);
                      }}
                      className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-[#22d3ee] hover:text-black transition-all border border-white/10"
                    >
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                      </svg>
                    </button>
                  ) : entry.requestId && entry.canEdit === false ? (
                    /* Legacy generation — animation code not saved by API, remix not available */
                    <div
                      title={copy.card.legacyRemixUnavailable}
                      className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white/20 border border-white/5 cursor-not-allowed"
                    >
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" className="opacity-40">
                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                        <line x1="4" y1="4" x2="20" y2="20" stroke="currentColor" strokeWidth="2"/>
                      </svg>
                    </div>
                  ) : null}
                  <button
                    type="button"
                    title={copy.card.delete}
                    onClick={(e) => {
                      e.stopPropagation();
                      if (confirm(copy.card.confirmDelete)) {
                        setHistory(prev => prev.filter((_, i) => i !== idx));
                      }
                    }}
                    className="p-2 bg-black/60 backdrop-blur-md rounded-full text-red-400 hover:bg-red-500 hover:text-white transition-all border border-white/10"
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                      <polyline points="3 6 5 6 21 6" />
                      <path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" />
                      <line x1="10" y1="11" x2="10" y2="17" />
                      <line x1="14" y1="11" x2="14" y2="17" />
                    </svg>
                  </button>
                </div>
                <MobileGenerationActions
                  prompt={entry.prompt}
                  onCopyError={onGenerationError}
                  actions={[
                    {
                      kind: "download",
                      label: copy.mobileActions.download,
                      onSelect: () =>
                        downloadFile(entry.url, `motion-${entry.id || idx}.mp4`),
                    },
                    entry.requestId &&
                      entry.canEdit !== false && {
                        kind: "remix",
                        label: copy.mobileActions.remix,
                        onSelect: () => {
                          setEditMode(true);
                          setEditSourceId(entry.requestId);
                          setPrompt("");
                          setTimeout(() => textareaRef.current?.focus(), 50);
                        },
                      },
                    {
                      kind: "delete",
                      label: copy.mobileActions.delete,
                      danger: true,
                      onSelect: () => {
                        if (confirm(copy.card.confirmDelete)) {
                          setHistory((prev) => prev.filter((_, i) => i !== idx));
                        }
                      },
                    },
                  ]}
                />

                {/* ── Card footer: prompt + metadata ── */}
                <div className="p-3 bg-black/80 backdrop-blur-sm border-t border-white/5 flex-1 flex flex-col justify-between gap-2">
                  <p className="text-white/70 text-xs line-clamp-3 leading-relaxed" title={entry.prompt}>
                    {entry.prompt || copy.card.noPrompt}
                  </p>
                  <div className="flex items-center justify-between mt-1 flex-wrap gap-1">
                    <div className="flex items-center gap-2">
                      <span className="text-[10px] font-bold text-primary px-2 py-0.5 bg-primary/10 rounded border border-primary/20 whitespace-nowrap">
                        {copy.card.tag}
                      </span>
                      <div className="flex gap-2">
                        {entry.aspectRatio && (
                          <span className="text-[10px] text-white/40">{entry.aspectRatio}</span>
                        )}
                        {entry.duration && (
                          <span className="text-[10px] text-white/40">{entry.duration}s</span>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : !generating ? (
          /* ── Empty State ── */
          <div className="flex flex-col items-center justify-center h-full animate-fade-in-up transition-all duration-700 min-h-[50vh]">
            {/* Overlapping floating cards */}
            <div className="flex items-center justify-center gap-1.5 md:gap-3 mb-10 select-none scale-90 sm:scale-100">
              <div className="w-18 h-22 sm:w-24 sm:h-28 rounded-2xl border border-white/10 shadow-2xl -rotate-[12deg] transform hover:rotate-0 hover:scale-110 hover:z-20 transition-all duration-300 overflow-hidden bg-white/[0.01] flex-shrink-0">
                <img
                  src="https://d3adwkbyhxyrtq.cloudfront.net/webassets/videomodels/sdxl-image.avif"
                  alt="Creative asset 1"
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="w-18 h-22 sm:w-24 sm:h-28 rounded-2xl border border-white/10 shadow-2xl -rotate-[4deg] transform hover:rotate-0 hover:scale-110 hover:z-20 transition-all duration-300 overflow-hidden bg-white/[0.01] -ml-3 sm:-ml-4 flex-shrink-0">
                <img
                  src="https://d3adwkbyhxyrtq.cloudfront.net/webassets/videomodels/chroma-image.avif"
                  alt="Creative asset 2"
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="w-18 h-18 sm:w-24 sm:h-24 rounded-full border border-white/10 shadow-2xl rotate-[6deg] transform hover:rotate-0 hover:scale-110 hover:z-20 transition-all duration-300 overflow-hidden bg-white/[0.01] -ml-3 sm:-ml-4 flex-shrink-0">
                <img
                  src="https://d3adwkbyhxyrtq.cloudfront.net/webassets/videomodels/neta-lumina.avif"
                  alt="Creative asset 3"
                  className="w-full h-full object-cover"
                />
              </div>
              <div className="w-18 h-22 sm:w-24 sm:h-28 rounded-2xl border border-white/10 shadow-2xl rotate-[12deg] transform hover:rotate-0 hover:scale-110 hover:z-20 transition-all duration-300 overflow-hidden bg-white/[0.01] -ml-3 sm:-ml-4 flex-shrink-0">
                <img
                  src="https://d3adwkbyhxyrtq.cloudfront.net/webassets/videomodels/perfect-pony-xl.avif"
                  alt="Creative asset 4"
                  className="w-full h-full object-cover"
                />
              </div>
            </div>

            <h1 className="text-2xl sm:text-4xl md:text-5xl font-extrabold tracking-tight mb-4 text-center px-4 flex flex-col items-center">
              <span className="text-white font-black uppercase text-xl sm:text-3xl tracking-wide mb-1 opacity-90">{copy.empty.titleLine1}</span>
              <span className="text-[#22d3ee] font-black uppercase text-2xl sm:text-4xl sm:mt-1 tracking-tight">
                {copy.empty.titleLine2}
              </span>
            </h1>
            <p className="text-white/40 text-xs sm:text-sm font-medium tracking-wide text-center max-w-lg leading-relaxed px-4">
              {copy.empty.description}
            </p>
          </div>
        ) : null}
      </div>

      {/* ── BOTTOM PROMPT BAR — matches VideoStudio exactly ── */}
      <PromptComposer>

          {/* ── Top Row: Mode Toggle & Edit Source Banner ── */}
          <div className="flex items-center justify-between gap-3 px-1">
            {/* Left: Mode toggle pill */}
            <PromptSegmentedControl className="flex-shrink-0">
              <PromptSegmentOption
                type="button"
                onClick={() => { setEditMode(false); setEditSourceId(null); }}
                selected={!editMode}
              >
                {copy.modeToggle.generate}
              </PromptSegmentOption>
              <PromptSegmentOption
                type="button"
                onClick={() => setEditMode(true)}
                disabled={editSources.length === 0}
                selected={editMode}
                className="disabled:opacity-30 disabled:cursor-not-allowed"
              >
                {copy.modeToggle.edit}
              </PromptSegmentOption>
            </PromptSegmentedControl>

            {/* Right: Edit mode status banner beside toggle buttons */}
            {editMode && (
              <div className="flex items-center gap-2 px-3 py-1 bg-[#22d3ee]/5 border border-[#22d3ee]/10 rounded-full text-[11px] text-[#22d3ee] font-medium tracking-tight min-w-0 max-w-full overflow-hidden">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="flex-shrink-0">
                  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                </svg>
                <span className="truncate">
                  {sourceEntry
                    ? `${copy.editBanner.editingPrefix} "${sourceEntry.prompt?.slice(0, 45)}${sourceEntry.prompt?.length > 45 ? "…" : ""}"`
                    : copy.editBanner.selectSource}
                </span>
                <button
                  onClick={() => { setEditMode(false); setEditSourceId(null); setPrompt(""); }}
                  className="ml-auto text-[#22d3ee]/40 hover:text-[#22d3ee] transition-colors text-sm leading-none flex-shrink-0"
                  title={copy.editBanner.cancelEdit}
                >
                  ×
                </button>
              </div>
            )}
          </div>

            {/* Bottom: Textarea full width */}
            <div className="w-full">
              <PromptTextarea
                ref={textareaRef}
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder={
                  editMode
                    ? copy.placeholder.edit
                    : copy.placeholder.generate
                }
              />
            </div>

          {/* ── Error banner ── */}
          {generateError && (
            <div className="flex items-center gap-2 px-3 py-1.5 bg-red-500/10 border border-red-500/20 rounded text-red-400 text-xs">
              <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
              {generateError}
            </div>
          )}

          {/* ── Controls row: dropdowns + generate button ── */}
          <PromptFooter>
            <PromptControls ref={controlsRef}>

              {/* ── Aspect Ratio dropdown ── */}
              <div className="relative">
                <button
                  type="button"
                  onClick={toggleDropdown("ar")}
                  className={promptControlClassName({
                    active: openDropdown === "ar",
                  })}
                >
                  <PromptAspectRatioIcon />
                  <span className={PROMPT_CONTROL_LABEL_CLASS}>
                    {aspectRatio}
                  </span>
                </button>
                {openDropdown === "ar" && (
                  <PromptPopover>
                    <PromptPopoverHeader>{copy.controls.aspectRatio}</PromptPopoverHeader>
                    <PromptMenuList>
                      {ASPECT_RATIOS.map((ar) => (
                        <DropdownItem
                          key={ar}
                          label={ar}
                          selected={aspectRatio === ar}
                          onClick={() => { setAspectRatio(ar); setOpenDropdown(null); }}
                        />
                      ))}
                    </PromptMenuList>
                  </PromptPopover>
                )}
              </div>

              {/* ── Duration dropdown ── */}
              <div className="relative">
                <button
                  type="button"
                  onClick={toggleDropdown("dur")}
                  className={promptControlClassName({
                    active: openDropdown === "dur",
                  })}
                >
                  <PromptDurationIcon />
                  <span className={PROMPT_CONTROL_LABEL_CLASS}>
                    {duration}s
                  </span>
                </button>
                {openDropdown === "dur" && (
                  <PromptPopover>
                    <PromptPopoverHeader>{copy.controls.duration}</PromptPopoverHeader>
                    <PromptMenuList>
                      {DURATION_OPTIONS.map((d) => (
                        <DropdownItem
                          key={d}
                          label={`${d}s`}
                          selected={duration === d}
                          onClick={() => { setDuration(d); setOpenDropdown(null); }}
                        />
                      ))}
                    </PromptMenuList>
                  </PromptPopover>
                )}
              </div>

              {/* Edit source picker dropdown — only shown in edit mode */}
              {editMode && editSources.length > 0 && (
                <div className="relative">
                  <button
                    type="button"
                    onClick={toggleDropdown("source")}
                    className={promptControlClassName({ active: true })}
                  >
                    <div className="w-4 h-4 bg-[#22d3ee]/20 rounded flex items-center justify-center border border-[#22d3ee]/30">
                      <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="#22d3ee" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
                        <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
                      </svg>
                    </div>
                    <span className={`${PROMPT_CONTROL_LABEL_CLASS} text-[#22d3ee]/70 max-w-[120px] truncate`}>
                      {sourceEntry ? `${copy.controls.sourcePrefix} ${sourceEntry.prompt?.slice(0, 20)}…` : copy.controls.pickSource}
                    </span>
                    <PromptChevronIcon />
                  </button>
                  {openDropdown === "source" && (
                    <PromptPopover className="w-64">
                      <PromptPopoverHeader>{copy.controls.sourceGeneration}</PromptPopoverHeader>
                      <div className="flex flex-col gap-1">
                        {editSources.map((src) => (
                          <div
                            key={src.requestId}
                            className="flex items-center gap-3 p-2 hover:bg-white/5 rounded cursor-pointer transition-all group/opt"
                            onClick={() => { setEditSourceId(src.requestId); setOpenDropdown(null); }}
                          >
                            <div className="w-10 h-7 rounded overflow-hidden bg-black/40 flex-shrink-0 border border-white/5">
                              <video src={src.url} className="w-full h-full object-cover" muted playsInline />
                            </div>
                            <div className="flex-1 min-w-0">
                              <p className="text-[11px] text-white/70 truncate leading-tight group-hover/opt:text-white">{src.prompt}</p>
                              <p className="text-[9px] text-white/30 mt-0.5">{src.aspectRatio} · {src.duration}s</p>
                            </div>
                            {editSourceId === src.requestId && <CheckSvg />}
                          </div>
                        ))}
                      </div>
                    </PromptPopover>
                  )}
                </div>
              )}

              <span className="text-[10px] text-white/20 hidden sm:block ml-2">{copy.controls.shortcutHint}</span>
            </PromptControls>

            {/* ── Generate Button — matches VideoStudio exactly ── */}
            <PromptAction
              onClick={handleGenerate}
              disabled={generating || !prompt.trim() || (editMode && !editSourceId)}
            >
              {generating ? (
                <>
                  <span className="animate-spin inline-block text-black">◌</span>{" "}
                  {editMode ? copy.generateButton.remixing : copy.generateButton.generating}
                </>
              ) : editMode ? (
                <span>{copy.generateButton.remix}</span>
              ) : (
                <span>{copy.generateButton.generate}</span>
              )}
            </PromptAction>
          </PromptFooter>
      </PromptComposer>
      <Toaster position="top-right" containerStyle={{ zIndex: 99999 }} toastOptions={{ duration: 5000, style: { background: '#18181b', color: '#ffffff', border: '1px solid rgba(255,255,255,0.15)', fontSize: '13px', borderRadius: '12px', boxShadow: '0 10px 30px rgba(0,0,0,0.6)', maxWidth: '440px', wordBreak: 'break-word', whiteSpace: 'pre-wrap', padding: '12px 16px' } }} />
    </div>
  );
}